-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathselect.go
More file actions
544 lines (519 loc) · 15.3 KB
/
select.go
File metadata and controls
544 lines (519 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
package explain
import (
"fmt"
"strings"
"github.com/sqlc-dev/doubleclick/ast"
)
func explainSelectIntersectExceptQuery(sb *strings.Builder, n *ast.SelectIntersectExceptQuery, indent string, depth int) {
fmt.Fprintf(sb, "%sSelectIntersectExceptQuery (children %d)\n", indent, len(n.Selects))
// ClickHouse wraps first operand in SelectWithUnionQuery when EXCEPT is present
hasExcept := false
for _, op := range n.Operators {
if strings.HasPrefix(op, "EXCEPT") {
hasExcept = true
break
}
}
// Check if first operand has a WITH clause to be inherited by subsequent operands
var inheritedWith []ast.Expression
if len(n.Selects) > 0 {
inheritedWith = extractWithClause(n.Selects[0])
}
childIndent := strings.Repeat(" ", depth+1)
for i, sel := range n.Selects {
if hasExcept && i == 0 {
// Wrap first operand in SelectWithUnionQuery -> ExpressionList format
// But if it's already a SelectWithUnionQuery, don't double-wrap
if _, isUnion := sel.(*ast.SelectWithUnionQuery); isUnion {
Node(sb, sel, depth+1)
} else {
fmt.Fprintf(sb, "%sSelectWithUnionQuery (children 1)\n", childIndent)
fmt.Fprintf(sb, "%s ExpressionList (children 1)\n", childIndent)
Node(sb, sel, depth+3)
}
} else if i > 0 && len(inheritedWith) > 0 {
// Subsequent operands inherit the WITH clause from the first operand
explainSelectQueryWithInheritedWith(sb, sel, inheritedWith, depth+1)
} else {
Node(sb, sel, depth+1)
}
}
}
// extractWithClause extracts the WITH clause from a statement (if it's a SelectQuery)
func extractWithClause(stmt ast.Statement) []ast.Expression {
switch s := stmt.(type) {
case *ast.SelectQuery:
return s.With
case *ast.SelectWithUnionQuery:
// Check the first select in the union
if len(s.Selects) > 0 {
return extractWithClause(s.Selects[0])
}
}
return nil
}
// explainSelectQueryWithInheritedWith outputs a SELECT with an inherited WITH clause
// The inherited WITH clause is output AFTER the columns (not before, like a regular WITH)
func explainSelectQueryWithInheritedWith(sb *strings.Builder, stmt ast.Statement, inheritedWith []ast.Expression, depth int) {
sq, ok := stmt.(*ast.SelectQuery)
if !ok {
// Not a SelectQuery, output normally
Node(sb, stmt, depth)
return
}
// If the SelectQuery already has a WITH clause, output normally
if len(sq.With) > 0 {
Node(sb, stmt, depth)
return
}
// Output SelectQuery with inherited WITH clause after columns
indent := strings.Repeat(" ", depth)
children := countSelectQueryChildren(sq) + 1 // +1 for inherited WITH clause
fmt.Fprintf(sb, "%sSelectQuery (children %d)\n", indent, children)
// Columns (ExpressionList) - output BEFORE inherited WITH
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(sq.Columns))
for _, col := range sq.Columns {
Node(sb, col, depth+2)
}
// Inherited WITH clause (ExpressionList) - output AFTER columns
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(inheritedWith))
for _, w := range inheritedWith {
Node(sb, w, depth+2)
}
// FROM (including ARRAY JOIN as part of TablesInSelectQuery)
if sq.From != nil || sq.ArrayJoin != nil {
TablesWithArrayJoin(sb, sq.From, sq.ArrayJoin, depth+1)
}
// PREWHERE
if sq.PreWhere != nil {
Node(sb, sq.PreWhere, depth+1)
}
// WHERE
if sq.Where != nil {
Node(sb, sq.Where, depth+1)
}
// GROUP BY (skip for GROUP BY ALL which doesn't output an expression list)
if len(sq.GroupBy) > 0 && !sq.GroupByAll {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(sq.GroupBy))
for _, g := range sq.GroupBy {
Node(sb, g, depth+2)
}
}
// HAVING
if sq.Having != nil {
Node(sb, sq.Having, depth+1)
}
// QUALIFY
if sq.Qualify != nil {
Node(sb, sq.Qualify, depth+1)
}
// WINDOW clause
if len(sq.Window) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(sq.Window))
for range sq.Window {
fmt.Fprintf(sb, "%s WindowListElement\n", indent)
}
}
// ORDER BY
if len(sq.OrderBy) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(sq.OrderBy))
for _, o := range sq.OrderBy {
Node(sb, o, depth+2)
}
}
// INTERPOLATE
if len(sq.Interpolate) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(sq.Interpolate))
for _, i := range sq.Interpolate {
Node(sb, i, depth+2)
}
}
// OFFSET
if sq.Offset != nil {
Node(sb, sq.Offset, depth+1)
}
// LIMIT BY handling
if sq.LimitByLimit != nil {
Node(sb, sq.LimitByLimit, depth+1)
if len(sq.LimitBy) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(sq.LimitBy))
for _, expr := range sq.LimitBy {
Node(sb, expr, depth+2)
}
}
if sq.Limit != nil {
Node(sb, sq.Limit, depth+1)
}
} else if len(sq.LimitBy) > 0 {
if sq.Limit != nil {
Node(sb, sq.Limit, depth+1)
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(sq.LimitBy))
for _, expr := range sq.LimitBy {
Node(sb, expr, depth+2)
}
} else if sq.Limit != nil {
Node(sb, sq.Limit, depth+1)
}
// SETTINGS
if len(sq.Settings) > 0 && !sq.SettingsAfterFormat {
fmt.Fprintf(sb, "%s Set\n", indent)
}
// TOP clause
if sq.Top != nil {
Node(sb, sq.Top, depth+1)
}
}
func explainSelectWithUnionQuery(sb *strings.Builder, n *ast.SelectWithUnionQuery, indent string, depth int) {
if n == nil {
return
}
children := countSelectUnionChildren(n)
fmt.Fprintf(sb, "%sSelectWithUnionQuery (children %d)\n", indent, children)
// ClickHouse optimizes UNION ALL when selects have identical expressions but different aliases.
// In that case, only the first SELECT is shown since column names come from the first SELECT anyway.
selects := simplifyUnionSelects(n.Selects)
// Wrap selects in ExpressionList
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(selects))
for _, sel := range selects {
Node(sb, sel, depth+2)
}
// INTO OUTFILE clause - check if any SelectQuery has IntoOutfile set
for _, sel := range n.Selects {
if sq, ok := sel.(*ast.SelectQuery); ok && sq.IntoOutfile != nil {
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, sq.IntoOutfile.Filename)
break
}
}
// FORMAT clause - check if any SelectQuery has Format set
// Skip this when inside CreateQuery context, as Format is output at CreateQuery level
if !inCreateQueryContext {
for _, sel := range n.Selects {
if sq, ok := sel.(*ast.SelectQuery); ok && sq.Format != nil {
Node(sb, sq.Format, depth+1)
break
}
}
}
// When SETTINGS comes AFTER FORMAT, it's output at SelectWithUnionQuery level
for _, sel := range n.Selects {
if sq, ok := sel.(*ast.SelectQuery); ok && sq.SettingsAfterFormat && len(sq.Settings) > 0 {
fmt.Fprintf(sb, "%s Set\n", indent)
break
}
}
}
func explainSelectQuery(sb *strings.Builder, n *ast.SelectQuery, indent string, depth int) {
children := countSelectQueryChildren(n)
fmt.Fprintf(sb, "%sSelectQuery (children %d)\n", indent, children)
// WITH clause (ExpressionList) - output before columns
if len(n.With) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.With))
for _, w := range n.With {
Node(sb, w, depth+2)
}
}
// Columns (ExpressionList)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Columns))
for _, col := range n.Columns {
Node(sb, col, depth+2)
}
// FROM (including ARRAY JOIN as part of TablesInSelectQuery)
if n.From != nil || n.ArrayJoin != nil {
TablesWithArrayJoin(sb, n.From, n.ArrayJoin, depth+1)
}
// PREWHERE
if n.PreWhere != nil {
Node(sb, n.PreWhere, depth+1)
}
// WHERE
if n.Where != nil {
Node(sb, n.Where, depth+1)
}
// GROUP BY (skip for GROUP BY ALL which doesn't output an expression list)
if len(n.GroupBy) > 0 && !n.GroupByAll {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.GroupBy))
for _, g := range n.GroupBy {
if n.GroupingSets {
// Each grouping set is wrapped in an ExpressionList
// but we need to unwrap tuples and output elements directly
if lit, ok := g.(*ast.Literal); ok && lit.Type == ast.LiteralTuple {
if elements, ok := lit.Value.([]ast.Expression); ok {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(elements))
for _, elem := range elements {
Node(sb, elem, depth+3)
}
} else {
// Fallback for unexpected tuple value type
fmt.Fprintf(sb, "%s ExpressionList (children 1)\n", indent)
Node(sb, g, depth+3)
}
} else {
// Single expression grouping set
fmt.Fprintf(sb, "%s ExpressionList (children 1)\n", indent)
Node(sb, g, depth+3)
}
} else {
Node(sb, g, depth+2)
}
}
}
// HAVING
if n.Having != nil {
Node(sb, n.Having, depth+1)
}
// QUALIFY
if n.Qualify != nil {
Node(sb, n.Qualify, depth+1)
}
// WINDOW clause (named window definitions)
if len(n.Window) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Window))
for range n.Window {
fmt.Fprintf(sb, "%s WindowListElement\n", indent)
}
}
// ORDER BY
if len(n.OrderBy) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.OrderBy))
for _, o := range n.OrderBy {
Node(sb, o, depth+2)
}
}
// INTERPOLATE
if len(n.Interpolate) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Interpolate))
for _, i := range n.Interpolate {
Node(sb, i, depth+2)
}
}
// OFFSET (ClickHouse outputs offset before limit in EXPLAIN AST)
if n.Offset != nil {
Node(sb, n.Offset, depth+1)
}
// LIMIT BY handling
if n.LimitByLimit != nil {
// Case: LIMIT n BY x LIMIT m -> output LimitByLimit, LimitBy, Limit
Node(sb, n.LimitByLimit, depth+1)
if len(n.LimitBy) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.LimitBy))
for _, expr := range n.LimitBy {
Node(sb, expr, depth+2)
}
}
if n.Limit != nil {
Node(sb, n.Limit, depth+1)
}
} else if len(n.LimitBy) > 0 {
// Case: LIMIT n BY x (no second LIMIT) -> output Limit, then LimitBy
if n.Limit != nil {
Node(sb, n.Limit, depth+1)
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.LimitBy))
for _, expr := range n.LimitBy {
Node(sb, expr, depth+2)
}
} else if n.Limit != nil {
// Case: plain LIMIT n (no BY)
Node(sb, n.Limit, depth+1)
}
// SETTINGS is output at SelectQuery level only when NOT after FORMAT
// When SettingsAfterFormat is true, it's output at SelectWithUnionQuery level instead
if len(n.Settings) > 0 && !n.SettingsAfterFormat {
fmt.Fprintf(sb, "%s Set\n", indent)
}
// TOP clause is output at the end
if n.Top != nil {
Node(sb, n.Top, depth+1)
}
}
func explainOrderByElement(sb *strings.Builder, n *ast.OrderByElement, indent string, depth int) {
// ClickHouse uses different formats for WITH FILL:
// - When FROM/TO are simple literals: direct children on OrderByElement
// - When FROM/TO are complex expressions or only STEP present: uses FillModifier wrapper
hasFromOrTo := n.FillFrom != nil || n.FillTo != nil
hasComplexFillExpr := hasFromOrTo && (isComplexExpr(n.FillFrom) || isComplexExpr(n.FillTo))
// Use FillModifier when FROM/TO contain complex expressions (not simple literals)
// When only STEP is present, output it directly as a child (no FillModifier)
useFillModifier := n.WithFill && hasComplexFillExpr
if useFillModifier {
// Use FillModifier wrapper
fillChildren := 0
if n.FillFrom != nil {
fillChildren++
}
if n.FillTo != nil {
fillChildren++
}
if n.FillStep != nil {
fillChildren++
}
children := 2 // expression + FillModifier
fmt.Fprintf(sb, "%sOrderByElement (children %d)\n", indent, children)
Node(sb, n.Expression, depth+1)
fmt.Fprintf(sb, "%s FillModifier (children %d)\n", indent, fillChildren)
if n.FillFrom != nil {
Node(sb, n.FillFrom, depth+2)
}
if n.FillTo != nil {
Node(sb, n.FillTo, depth+2)
}
if n.FillStep != nil {
Node(sb, n.FillStep, depth+2)
}
} else {
// Use direct children for simple literal FROM/TO cases
children := 1 // expression
if n.FillFrom != nil {
children++
}
if n.FillTo != nil {
children++
}
if n.FillStep != nil {
children++
}
if n.Collate != "" {
children++
}
fmt.Fprintf(sb, "%sOrderByElement (children %d)\n", indent, children)
Node(sb, n.Expression, depth+1)
if n.FillFrom != nil {
Node(sb, n.FillFrom, depth+1)
}
if n.FillTo != nil {
Node(sb, n.FillTo, depth+1)
}
if n.FillStep != nil {
Node(sb, n.FillStep, depth+1)
}
if n.Collate != "" {
// COLLATE is output as a string literal
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, n.Collate)
}
}
}
// explainInterpolateElement explains an INTERPOLATE element.
// Format: InterpolateElement (column colname) (children N)
func explainInterpolateElement(sb *strings.Builder, n *ast.InterpolateElement, indent string, depth int) {
children := 0
if n.Value != nil {
children = 1
}
if children > 0 {
fmt.Fprintf(sb, "%sInterpolateElement (column %s) (children %d)\n", indent, n.Column, children)
Node(sb, n.Value, depth+1)
} else {
fmt.Fprintf(sb, "%sInterpolateElement (column %s)\n", indent, n.Column)
}
}
// isComplexExpr checks if an expression is complex (not a simple literal)
func isComplexExpr(expr ast.Expression) bool {
if expr == nil {
return false
}
switch expr.(type) {
case *ast.Literal:
return false
default:
return true
}
}
// hasOnlyLiterals checks if all expressions in a slice are literals
func hasOnlyLiterals(exprs []ast.Expression) bool {
for _, expr := range exprs {
if _, ok := expr.(*ast.Literal); !ok {
return false
}
}
return true
}
func countSelectUnionChildren(n *ast.SelectWithUnionQuery) int {
count := 1 // ExpressionList of selects
// Check if any SelectQuery has IntoOutfile set
for _, sel := range n.Selects {
if sq, ok := sel.(*ast.SelectQuery); ok && sq.IntoOutfile != nil {
count++
break
}
}
// Check if any SelectQuery has Format set
// Skip this when inside CreateQuery context, as Format is output at CreateQuery level
if !inCreateQueryContext {
for _, sel := range n.Selects {
if sq, ok := sel.(*ast.SelectQuery); ok && sq.Format != nil {
count++
break
}
}
}
// When SETTINGS comes AFTER FORMAT, it's counted at SelectWithUnionQuery level
for _, sel := range n.Selects {
if sq, ok := sel.(*ast.SelectQuery); ok && sq.SettingsAfterFormat && len(sq.Settings) > 0 {
count++
break
}
}
return count
}
// simplifyUnionSelects returns all SELECT statements in a UNION.
// ClickHouse does not simplify UNION ALL queries in EXPLAIN AST output.
func simplifyUnionSelects(selects []ast.Statement) []ast.Statement {
return selects
}
func countSelectQueryChildren(n *ast.SelectQuery) int {
count := 1 // columns ExpressionList
// WITH clause
if len(n.With) > 0 {
count++
}
// FROM and ARRAY JOIN together count as one child (TablesInSelectQuery)
if n.From != nil || n.ArrayJoin != nil {
count++
}
if n.PreWhere != nil {
count++
}
if n.Where != nil {
count++
}
if len(n.GroupBy) > 0 && !n.GroupByAll {
count++
}
if n.Having != nil {
count++
}
if n.Qualify != nil {
count++
}
if len(n.Window) > 0 {
count++
}
if len(n.OrderBy) > 0 {
count++
}
if len(n.Interpolate) > 0 {
count++
}
if n.LimitByLimit != nil {
count++ // LIMIT n in "LIMIT n BY x LIMIT m"
}
if n.Limit != nil {
count++
}
if len(n.LimitBy) > 0 {
count++
}
if n.Offset != nil {
count++
}
// SETTINGS is counted at SelectQuery level only when NOT after FORMAT
if len(n.Settings) > 0 && !n.SettingsAfterFormat {
count++
}
// TOP clause
if n.Top != nil {
count++
}
return count
}