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
7 changes: 7 additions & 0 deletions ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ type SelectWithUnionQuery struct {
Settings []*SettingExpr `json:"settings,omitempty"` // Union-level SETTINGS
SettingsAfterFormat bool `json:"settings_after_format,omitempty"`
SettingsBeforeFormat bool `json:"settings_before_format,omitempty"`
// IsConstructionApplied marks a union whose query-construction settings
// have already been materialized (used by the EXPLAIN printer).
IsConstructionApplied bool `json:"-"`
}

func (s *SelectWithUnionQuery) Pos() token.Position { return s.Position }
Expand Down Expand Up @@ -91,6 +94,9 @@ type SelectQuery struct {
Format *Identifier `json:"format,omitempty"`
// ColumnAliases holds the alias list of a FROM-first query: FROM t (a, b) SELECT a.
ColumnAliases []string `json:"column_aliases,omitempty"`
// ConstructionWrapper marks the outer query synthesized from the
// query-construction settings; it prints LIMIT before OFFSET.
ConstructionWrapper bool `json:"-"`
}

// ArrayJoinClause represents an ARRAY JOIN clause.
Expand Down Expand Up @@ -996,6 +1002,7 @@ type SystemQuery struct {
Table string `json:"table,omitempty"`
OnCluster string `json:"on_cluster,omitempty"`
DuplicateTableOutput bool `json:"duplicate_table_output,omitempty"` // True for commands that need database/table output twice
Parts []Expression `json:"parts,omitempty"` // SCHEDULE MERGE ... PARTS list
Settings []*SettingExpr `json:"settings,omitempty"`
}

Expand Down
368 changes: 368 additions & 0 deletions internal/explain/construction.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,368 @@
package explain

import (
"strconv"
"strings"

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

// ClickHouse 26.x materializes the query-construction settings (select,
// filter, order, sort, limit, offset, page) into the query AST before
// EXPLAIN AST prints it: the (sub)query carrying them in its own SETTINGS
// clause is wrapped as a derived table with an outer SELECT / WHERE /
// ORDER BY / LIMIT / OFFSET. See executeQuery.cpp
// (wrapAsConstructedSelect, wrapNestedConstructionSettings,
// wrapPerArmConstructionSettings, applyQueryConstructionSettings).

// FragmentParser parses the text of a select/filter/order setting. It is
// installed by the parser package to avoid an import cycle. kind is
// "select", "filter" or "order".
var FragmentParser func(kind, text string) []ast.Expression

// OrderByParser parses the text of an order setting.
var OrderByParser func(text string) []*ast.OrderByElement

// constructionDisabled is non-zero while printing a view definition, whose
// construction settings are not materialized.
var constructionDisabled int

func isConstructionSettingName(name string) bool {
switch name {
case "select", "filter", "order", "sort", "limit", "offset", "page":
return true
}
return false
}

type constructionSettings struct {
selectExpr, filterExpr, orderExpr string
sortExpr string
limit, offset float64
present bool
}

func (c *constructionSettings) empty() bool {
return c.selectExpr == "" && c.filterExpr == "" && c.orderExpr == "" && c.sortExpr == "" && c.limit == 0 && c.offset == 0
}

func hasConstructionSetting(settings []*ast.SettingExpr) bool {
for _, s := range settings {
if isConstructionSettingName(s.Name) {
return true
}
}
return false
}

// settingIsDefault reports whether the setting is "name = DEFAULT".
func settingIsDefault(s *ast.SettingExpr) bool {
if id, ok := s.Value.(*ast.Identifier); ok && len(id.Parts) == 1 && strings.EqualFold(id.Parts[0], "DEFAULT") {
return true
}
return false
}

func settingString(e ast.Expression) string {
if lit, ok := e.(*ast.Literal); ok {
switch v := lit.Value.(type) {
case string:
return v
}
}
return ""
}

func settingFloat(e ast.Expression) float64 {
neg := false
if u, ok := e.(*ast.UnaryExpr); ok && u.Op == "-" {
neg = true
e = u.Operand
}
var f float64
if lit, ok := e.(*ast.Literal); ok {
switch v := lit.Value.(type) {
case int64:
f = float64(v)
case uint64:
f = float64(v)
case float64:
f = v
case string:
f, _ = strconv.ParseFloat(strings.TrimSpace(v), 64)
}
if lit.Negative {
neg = !neg
}
}
if neg {
f = -f
}
return f
}

// takeConstructionSettings reads the construction settings of one SETTINGS
// clause into out and returns the clause without them.
func takeConstructionSettings(settings []*ast.SettingExpr, out *constructionSettings) []*ast.SettingExpr {
last := map[string]*ast.SettingExpr{}
reset := map[string]bool{}
var rest []*ast.SettingExpr
for _, s := range settings {
if !isConstructionSettingName(s.Name) {
rest = append(rest, s)
continue
}
if settingIsDefault(s) {
reset[s.Name] = true
continue
}
last[s.Name] = s
}
take := func(name string) (ast.Expression, bool) {
s, ok := last[name]
if !ok || reset[name] {
return nil, false
}
return s.Value, true
}
takeString := func(name string, dst *string) {
if v, ok := take(name); ok {
*dst = settingString(v)
out.present = true
}
}
takeString("select", &out.selectExpr)
takeString("filter", &out.filterExpr)
var order, sort string
takeString("order", &order)
takeString("sort", &sort)
if order != "" {
out.orderExpr, out.sortExpr = order, ""
} else if sort != "" {
out.orderExpr, out.sortExpr = "", sort
}
var limit, offset float64
has := false
if v, ok := take("limit"); ok {
limit, has = settingFloat(v), true
}
if v, ok := take("offset"); ok {
offset, has = settingFloat(v), true
}
if v, ok := take("page"); ok {
has = true
page := settingFloat(v)
if page > 0 {
offset = limit * (page - 1)
} else if page < 0 {
offset = limit * (page + 1)
limit = -limit
}
}
if has {
out.limit, out.offset = limit, offset
out.present = true
}
return rest
}

func floatLiteral(f float64) *ast.Literal {
return &ast.Literal{Type: ast.LiteralFloat, Value: f}
}

// sortToOrderBy converts the sort setting ("-a, b, 2") to ORDER BY elements.
func sortToOrderBy(sort string) []*ast.OrderByElement {
var res []*ast.OrderByElement
for _, item := range strings.Split(sort, ",") {
item = strings.TrimSpace(item)
desc := false
if strings.HasPrefix(item, "-") {
desc, item = true, item[1:]
} else if strings.HasPrefix(item, "+") {
item = item[1:]
}
if item == "" {
continue
}
var e ast.Expression
if n, err := strconv.ParseUint(item, 10, 64); err == nil {
e = &ast.Literal{Type: ast.LiteralInteger, Value: n}
} else {
e = &ast.Identifier{Parts: []string{item}}
}
res = append(res, &ast.OrderByElement{Expression: e, Descending: desc})
}
return res
}

// wrapAsConstructedSelect builds SELECT [select] FROM (inner) [WHERE filter]
// [ORDER BY order] [LIMIT limit] [OFFSET offset].
func wrapAsConstructedSelect(inner ast.Statement, cs *constructionSettings) *ast.SelectWithUnionQuery {
outer := &ast.SelectQuery{ConstructionWrapper: true}
if cs.selectExpr != "" && FragmentParser != nil {
outer.Columns = FragmentParser("select", cs.selectExpr)
} else {
outer.Columns = []ast.Expression{&ast.Asterisk{}}
}
innerUnion, ok := inner.(*ast.SelectWithUnionQuery)
if !ok {
innerUnion = &ast.SelectWithUnionQuery{Selects: []ast.Statement{inner}}
}
outer.From = &ast.TablesInSelectQuery{Tables: []*ast.TablesInSelectQueryElement{{
Table: &ast.TableExpression{Table: &ast.Subquery{Query: innerUnion}},
}}}
if cs.filterExpr != "" && FragmentParser != nil {
if exprs := FragmentParser("filter", cs.filterExpr); len(exprs) > 0 {
outer.Where = exprs[0]
}
}
if cs.orderExpr != "" && OrderByParser != nil {
outer.OrderBy = OrderByParser(cs.orderExpr)
} else if cs.sortExpr != "" {
outer.OrderBy = sortToOrderBy(cs.sortExpr)
}
if cs.limit != 0 {
outer.Limit = floatLiteral(cs.limit)
}
if cs.offset != 0 {
outer.Offset = floatLiteral(cs.offset)
}
return &ast.SelectWithUnionQuery{Selects: []ast.Statement{outer}}
}

// copySelect returns a shallow copy of a select query.
func copySelect(sq *ast.SelectQuery) *ast.SelectQuery {
c := *sq
return &c
}

// applyConstruction returns the union to print in place of n, with the
// construction settings materialized. topLevel is true for the outermost
// query of a statement.
func applyConstruction(n *ast.SelectWithUnionQuery, topLevel bool) *ast.SelectWithUnionQuery {
if n == nil || n.IsConstructionApplied || constructionDisabled > 0 {
return n
}
found := hasConstructionSetting(n.Settings)
for _, s := range n.Selects {
if sq, ok := s.(*ast.SelectQuery); ok && hasConstructionSetting(sq.Settings) {
found = true
}
}
if !found {
return n
}
cp := *n
n = &cp
n.Selects = append([]ast.Statement(nil), n.Selects...)

// Per-arm settings: a construction setting on a non-last arm.
if len(n.Selects) >= 2 {
perArm := false
for _, s := range n.Selects[:len(n.Selects)-1] {
if sq, ok := s.(*ast.SelectQuery); ok && hasConstructionSetting(sq.Settings) {
perArm = true
}
}
if perArm {
for i, s := range n.Selects {
sq, ok := s.(*ast.SelectQuery)
if !ok || !hasConstructionSetting(sq.Settings) {
continue
}
var cs constructionSettings
sq = copySelect(sq)
sq.Settings = takeConstructionSettings(sq.Settings, &cs)
n.Selects[i] = sq
if !cs.empty() {
w := wrapAsConstructedSelect(sq, &cs)
w.IsConstructionApplied = true
n.Selects[i] = w
}
}
}
}

if topLevel {
var cs constructionSettings
n.Settings = takeConstructionSettings(n.Settings, &cs)
var format *ast.Identifier
var lastSettings []*ast.SettingExpr
for i, s := range n.Selects {
sq, ok := s.(*ast.SelectQuery)
if !ok {
continue
}
sq = copySelect(sq)
if sq.Format != nil {
format = sq.Format
sq.Format = nil
}
var tmp constructionSettings
if i == len(n.Selects)-1 {
sq.Settings = takeConstructionSettings(sq.Settings, &cs)
lastSettings = sq.Settings
sq.Settings = nil
} else {
sq.Settings = takeConstructionSettings(sq.Settings, &tmp)
}
n.Selects[i] = sq
}
if cs.empty() {
// Nothing to wrap: put the remaining settings back where they were.
if len(n.Selects) > 0 {
if sq, ok := n.Selects[len(n.Selects)-1].(*ast.SelectQuery); ok {
sq.Settings = lastSettings
}
if sq, ok := n.Selects[0].(*ast.SelectQuery); ok && format != nil {
sq.Format = format
}
}
n.IsConstructionApplied = true
return n
}
outerSettings := n.Settings
for _, s := range lastSettings {
dup := false
for _, o := range outerSettings {
if o.Name == s.Name {
dup = true
}
}
if !dup {
outerSettings = append(outerSettings, s)
}
}
n.Settings = nil
n.SettingsBeforeFormat, n.SettingsAfterFormat = false, false
n.IsConstructionApplied = true
w := wrapAsConstructedSelect(n, &cs)
if outer, ok := w.Selects[0].(*ast.SelectQuery); ok {
outer.Format = format
}
if len(outerSettings) > 0 {
w.Settings = outerSettings
w.SettingsBeforeFormat = true
}
w.IsConstructionApplied = true
return w
}

// Nested: the (sub)query's own SETTINGS clauses.
var cs constructionSettings
n.Settings = takeConstructionSettings(n.Settings, &cs)
for i, s := range n.Selects {
if sq, ok := s.(*ast.SelectQuery); ok && hasConstructionSetting(sq.Settings) {
sq = copySelect(sq)
sq.Settings = takeConstructionSettings(sq.Settings, &cs)
n.Selects[i] = sq
}
}
n.IsConstructionApplied = true
if !cs.present || cs.empty() {
return n
}
w := wrapAsConstructedSelect(n, &cs)
w.IsConstructionApplied = true
return w
}
Loading
Loading