-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstatements.go
More file actions
2516 lines (2397 loc) · 76.7 KB
/
statements.go
File metadata and controls
2516 lines (2397 loc) · 76.7 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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package explain
import (
"fmt"
"strings"
"github.com/sqlc-dev/doubleclick/ast"
)
func explainInsertQuery(sb *strings.Builder, n *ast.InsertQuery, indent string, depth int) {
// Count children
children := 0
if n.Infile != "" {
children++
}
if n.Compression != "" {
children++
}
if n.Function != nil {
children++
} else if n.Table != "" {
children++ // Table identifier
if n.Database != "" {
children++ // Database identifier (separate from table)
}
}
if len(n.ColumnExpressions) > 0 || len(n.Columns) > 0 || n.AllColumns {
children++ // Column list
}
if n.Select != nil {
children++
}
if n.HasSettings {
children++
}
if n.PartitionBy != nil {
children++
}
// Note: InsertQuery uses 3 spaces after name in ClickHouse explain
fmt.Fprintf(sb, "%sInsertQuery (children %d)\n", indent, children)
// FROM INFILE path comes first
if n.Infile != "" {
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, n.Infile)
}
// COMPRESSION value comes next
if n.Compression != "" {
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, n.Compression)
}
if n.Function != nil {
Node(sb, n.Function, depth+1)
} else if n.Table != "" {
if n.Database != "" {
// Database-qualified: output separate identifiers
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Database)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Table)
} else {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Table)
}
}
// PARTITION BY clause (output after Function/Table)
if n.PartitionBy != nil {
if ident, ok := n.PartitionBy.(*ast.Identifier); ok {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, ident.Name())
} else {
Node(sb, n.PartitionBy, depth+1)
}
}
// Column list
if len(n.ColumnExpressions) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.ColumnExpressions))
for _, expr := range n.ColumnExpressions {
Node(sb, expr, depth+2)
}
} else if n.AllColumns {
fmt.Fprintf(sb, "%s ExpressionList (children 1)\n", indent)
fmt.Fprintf(sb, "%s Asterisk\n", indent)
} else if len(n.Columns) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Columns))
for _, col := range n.Columns {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, col.Parts[len(col.Parts)-1])
}
}
if n.Select != nil {
// For INSERT with SELECT, temporarily clear Format from the SELECT
// (FORMAT in INSERT belongs to INSERT, not SELECT, and shouldn't be output in EXPLAIN)
if swu, ok := n.Select.(*ast.SelectWithUnionQuery); ok {
for _, sel := range swu.Selects {
if sq, ok := sel.(*ast.SelectQuery); ok && sq.Format != nil {
savedFormat := sq.Format
sq.Format = nil
defer func() { sq.Format = savedFormat }()
}
}
}
// If this INSERT has an inherited WITH clause (from WITH ... INSERT syntax),
// use the special explain function that outputs WITH at the end of each SelectQuery
if len(n.With) > 0 {
ExplainSelectWithInheritedWith(sb, n.Select, n.With, depth+1)
} else {
Node(sb, n.Select, depth+1)
}
}
if n.HasSettings {
fmt.Fprintf(sb, "%s Set\n", indent)
}
}
func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string, depth int) {
if n == nil {
fmt.Fprintf(sb, "%s*ast.CreateQuery\n", indent)
return
}
// Handle special CREATE types
if n.CreateFunction {
children := 2 // identifier + lambda
fmt.Fprintf(sb, "%sCreateFunctionQuery %s (children %d)\n", indent, n.FunctionName, children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.FunctionName)
if n.FunctionBody != nil {
Node(sb, n.FunctionBody, depth+1)
}
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)
}
return
}
if n.CreateDictionary {
// Dictionary: count children = database identifier (if any) + table identifier + attributes (if any) + definition (if any)
children := 1 // table identifier
hasDatabase := n.Database != ""
if hasDatabase {
children++ // database identifier
}
if len(n.DictionaryAttrs) > 0 {
children++
}
if n.DictionaryDef != nil {
children++
}
// Format: "CreateQuery [database] [table] (children N)"
if hasDatabase {
fmt.Fprintf(sb, "%sCreateQuery %s %s (children %d)\n", indent, n.Database, n.Table, children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Database)
} else {
fmt.Fprintf(sb, "%sCreateQuery %s (children %d)\n", indent, n.Table, children)
}
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Table)
// Dictionary attributes
if len(n.DictionaryAttrs) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.DictionaryAttrs))
for _, attr := range n.DictionaryAttrs {
explainDictionaryAttributeDeclaration(sb, attr, indent+" ", depth+2)
}
}
// Dictionary definition
if n.DictionaryDef != nil {
explainDictionaryDefinition(sb, n.DictionaryDef, indent+" ", depth+1)
}
return
}
name := n.Table
if n.View != "" {
name = n.View
}
if n.CreateDatabase {
name = n.Database
}
// Check for database-qualified table/view name
hasDatabase := n.Database != "" && !n.CreateDatabase && (n.Table != "" || n.View != "")
// Check for column-level PRIMARY KEY modifiers (e.g., "a String PRIMARY KEY")
hasColumnPrimaryKey := false
for _, col := range n.Columns {
if col.PrimaryKey {
hasColumnPrimaryKey = true
break
}
}
// Count children: name + columns + engine/storage
children := 1 // name identifier
if hasDatabase {
children++ // additional identifier for database
}
if len(n.Columns) > 0 || len(n.Indexes) > 0 || len(n.Projections) > 0 || len(n.Constraints) > 0 {
children++
}
hasStorageChild := n.Engine != nil || len(n.OrderBy) > 0 || len(n.PrimaryKey) > 0 || n.PartitionBy != nil || n.SampleBy != nil || n.TTL != nil || len(n.Settings) > 0 || len(n.ColumnsPrimaryKey) > 0 || hasColumnPrimaryKey
if hasStorageChild {
children++
}
// For materialized views with TO clause but no storage, count ViewTargets as a child
if n.Materialized && n.To != "" && !hasStorageChild {
children++ // ViewTargets
}
if n.AsSelect != nil {
children++
}
if n.AsTableFunction != nil {
children++
}
// Count Format as a child if present
hasFormat := n.Format != ""
if hasFormat {
children++
}
// Count Comment as a child if present
if n.Comment != "" {
children++
}
// ClickHouse adds an extra space before (children N) for CREATE DATABASE
if n.CreateDatabase {
fmt.Fprintf(sb, "%sCreateQuery %s (children %d)\n", indent, EscapeIdentifier(name), children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, EscapeIdentifier(name))
} else if hasDatabase {
// Database-qualified: CreateQuery db table (children N)
fmt.Fprintf(sb, "%sCreateQuery %s %s (children %d)\n", indent, EscapeIdentifier(n.Database), EscapeIdentifier(name), children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, EscapeIdentifier(n.Database))
fmt.Fprintf(sb, "%s Identifier %s\n", indent, EscapeIdentifier(name))
} else {
fmt.Fprintf(sb, "%sCreateQuery %s (children %d)\n", indent, EscapeIdentifier(name), children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, EscapeIdentifier(name))
}
if len(n.Columns) > 0 || len(n.Indexes) > 0 || len(n.Projections) > 0 || len(n.Constraints) > 0 {
childrenCount := 0
if len(n.Columns) > 0 {
childrenCount++
}
if len(n.Indexes) > 0 {
childrenCount++
}
if len(n.Projections) > 0 {
childrenCount++
}
if len(n.Constraints) > 0 {
childrenCount++
}
// Check for PRIMARY KEY constraints in column declarations
var primaryKeyColumns []string
for _, col := range n.Columns {
if col.PrimaryKey {
primaryKeyColumns = append(primaryKeyColumns, col.Name)
}
}
if len(primaryKeyColumns) > 0 {
childrenCount++ // Add for Function tuple containing PRIMARY KEY columns
}
// Check for inline PRIMARY KEY (from column list, e.g., "n int, primary key n")
if len(n.ColumnsPrimaryKey) > 0 || n.HasEmptyColumnsPrimaryKey {
childrenCount++ // Add for the primary key identifier(s)
}
fmt.Fprintf(sb, "%s Columns definition (children %d)\n", indent, childrenCount)
if len(n.Columns) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Columns))
for _, col := range n.Columns {
Column(sb, col, depth+3)
}
}
if len(n.Indexes) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Indexes))
for _, idx := range n.Indexes {
Index(sb, idx, depth+3)
}
}
if len(n.Projections) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Projections))
for _, proj := range n.Projections {
explainProjection(sb, proj, indent+" ", depth+3)
}
}
// Output constraints wrapped in Constraint nodes
if len(n.Constraints) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Constraints))
for _, constraint := range n.Constraints {
fmt.Fprintf(sb, "%s Constraint (children 1)\n", indent)
Node(sb, constraint.Expression, depth+4)
}
}
// Output PRIMARY KEY columns as Function tuple
if len(primaryKeyColumns) > 0 {
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(primaryKeyColumns))
for _, colName := range primaryKeyColumns {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, colName)
}
}
// Output inline PRIMARY KEY (from column list)
if len(n.ColumnsPrimaryKey) > 0 || n.HasEmptyColumnsPrimaryKey {
if n.HasEmptyColumnsPrimaryKey {
// Empty PRIMARY KEY ()
fmt.Fprintf(sb, "%s Function tuple (children 1)\n", indent)
fmt.Fprintf(sb, "%s ExpressionList\n", indent)
} else if len(n.ColumnsPrimaryKey) > 1 {
// Multiple columns: wrap in Function tuple
fmt.Fprintf(sb, "%s Function tuple (children 1)\n", indent)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.ColumnsPrimaryKey))
for _, pk := range n.ColumnsPrimaryKey {
Node(sb, pk, depth+4)
}
} else {
// Single column: output directly
for _, pk := range n.ColumnsPrimaryKey {
Node(sb, pk, depth+2)
}
}
}
}
// 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
// (it will be output at CreateQuery level instead)
if hasFormat {
inCreateQueryContext = true
}
Node(sb, n.AsSelect, depth+1)
if hasFormat {
inCreateQueryContext = false
}
}
hasStorage := n.Engine != nil || len(n.OrderBy) > 0 || len(n.PrimaryKey) > 0 || n.PartitionBy != nil || n.SampleBy != nil || n.TTL != nil || len(n.Settings) > 0 || len(n.ColumnsPrimaryKey) > 0 || hasColumnPrimaryKey
if hasStorage {
storageChildren := 0
if n.Engine != nil {
storageChildren++
}
if n.PartitionBy != nil {
storageChildren++
}
if len(n.OrderBy) > 0 {
storageChildren++
}
if len(n.PrimaryKey) > 0 {
storageChildren++
}
// SAMPLE BY is always shown in EXPLAIN AST when present
if n.SampleBy != nil {
storageChildren++
}
if n.TTL != nil {
storageChildren++
}
if len(n.Settings) > 0 {
storageChildren++
}
// For materialized views, wrap storage definition in ViewTargets
// and use extra indentation for storage children
storageIndent := indent + " " // 1 space for regular storage (format strings add 1 more)
storageChildDepth := depth + 2
if n.Materialized {
fmt.Fprintf(sb, "%s ViewTargets (children %d)\n", indent, 1)
if storageChildren > 0 {
fmt.Fprintf(sb, "%s Storage definition (children %d)\n", indent, storageChildren)
} else {
fmt.Fprintf(sb, "%s Storage definition\n", indent)
}
storageIndent = indent + " " // 2 spaces for materialized (format strings add 1 more = 3 total)
storageChildDepth = depth + 3
} else {
if storageChildren > 0 {
fmt.Fprintf(sb, "%s Storage definition (children %d)\n", indent, storageChildren)
} else {
fmt.Fprintf(sb, "%s Storage definition\n", indent)
}
}
if n.Engine != nil {
if n.Engine.HasParentheses {
fmt.Fprintf(sb, "%s Function %s (children %d)\n", storageIndent, n.Engine.Name, 1)
if len(n.Engine.Parameters) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", storageIndent, len(n.Engine.Parameters))
for _, param := range n.Engine.Parameters {
Node(sb, param, storageChildDepth+2)
}
} else {
fmt.Fprintf(sb, "%s ExpressionList\n", storageIndent)
}
} else {
fmt.Fprintf(sb, "%s Function %s\n", storageIndent, n.Engine.Name)
}
}
if n.PartitionBy != nil {
if ident, ok := n.PartitionBy.(*ast.Identifier); ok {
fmt.Fprintf(sb, "%s Identifier %s\n", storageIndent, ident.Name())
} else {
Node(sb, n.PartitionBy, storageChildDepth)
}
}
// PRIMARY KEY comes before ORDER BY in EXPLAIN output
if len(n.PrimaryKey) > 0 {
if len(n.PrimaryKey) == 1 {
if ident, ok := n.PrimaryKey[0].(*ast.Identifier); ok {
fmt.Fprintf(sb, "%s Identifier %s\n", storageIndent, ident.Name())
} else if lit, ok := n.PrimaryKey[0].(*ast.Literal); ok && lit.Type == ast.LiteralTuple {
// Handle tuple literal (including empty tuple from PRIMARY KEY ())
exprs, _ := lit.Value.([]ast.Expression)
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", storageIndent, 1)
if len(exprs) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", storageIndent, len(exprs))
for _, e := range exprs {
Node(sb, e, storageChildDepth+2)
}
} else {
fmt.Fprintf(sb, "%s ExpressionList\n", storageIndent)
}
} else {
Node(sb, n.PrimaryKey[0], storageChildDepth)
}
} else {
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", storageIndent, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", storageIndent, len(n.PrimaryKey))
for _, p := range n.PrimaryKey {
Node(sb, p, storageChildDepth+2)
}
}
}
// ORDER BY comes after PRIMARY KEY in EXPLAIN output
if len(n.OrderBy) > 0 {
if len(n.OrderBy) == 1 {
if ident, ok := n.OrderBy[0].(*ast.Identifier); ok {
// When ORDER BY has modifiers (ASC/DESC), wrap in StorageOrderByElement
if n.OrderByHasModifiers {
fmt.Fprintf(sb, "%s StorageOrderByElement (children %d)\n", storageIndent, 1)
fmt.Fprintf(sb, "%s Identifier %s\n", storageIndent, ident.Name())
} else {
fmt.Fprintf(sb, "%s Identifier %s\n", storageIndent, ident.Name())
}
} else if lit, ok := n.OrderBy[0].(*ast.Literal); ok && lit.Type == ast.LiteralTuple {
// Handle tuple literal - for ORDER BY with modifiers (DESC/ASC),
// ClickHouse outputs just "Function tuple" without children
// For empty tuples or regular tuples without modifiers, output children
if n.OrderByHasModifiers {
fmt.Fprintf(sb, "%s Function tuple\n", storageIndent)
} else {
exprs, _ := lit.Value.([]ast.Expression)
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", storageIndent, 1)
if len(exprs) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", storageIndent, len(exprs))
for _, e := range exprs {
Node(sb, e, storageChildDepth+2)
}
} else {
fmt.Fprintf(sb, "%s ExpressionList\n", storageIndent)
}
}
} else {
Node(sb, n.OrderBy[0], storageChildDepth)
}
} else {
// Multiple ORDER BY expressions without modifiers
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", storageIndent, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", storageIndent, len(n.OrderBy))
for _, o := range n.OrderBy {
Node(sb, o, storageChildDepth+2)
}
}
}
// SAMPLE BY is always shown in EXPLAIN AST when present
if n.SampleBy != nil {
Node(sb, n.SampleBy, storageChildDepth)
}
if n.TTL != nil {
// Use Elements if available (has WHERE conditions), otherwise use legacy Expression/Expressions
if len(n.TTL.Elements) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", storageIndent, len(n.TTL.Elements))
for _, elem := range n.TTL.Elements {
children := 1
if elem.Where != nil {
children = 2
}
fmt.Fprintf(sb, "%s TTLElement (children %d)\n", storageIndent, children)
Node(sb, elem.Expr, storageChildDepth+2)
if elem.Where != nil {
Node(sb, elem.Where, storageChildDepth+2)
}
}
} else {
// Legacy: use Expression/Expressions
ttlCount := 1 + len(n.TTL.Expressions)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", storageIndent, ttlCount)
fmt.Fprintf(sb, "%s TTLElement (children 1)\n", storageIndent)
Node(sb, n.TTL.Expression, storageChildDepth+2)
for _, expr := range n.TTL.Expressions {
fmt.Fprintf(sb, "%s TTLElement (children 1)\n", storageIndent)
Node(sb, expr, storageChildDepth+2)
}
}
}
if len(n.Settings) > 0 {
fmt.Fprintf(sb, "%s Set\n", storageIndent)
}
} else if n.Materialized && n.To != "" {
// For materialized views with TO clause but no storage definition,
// output just ViewTargets without children
fmt.Fprintf(sb, "%s ViewTargets\n", indent)
}
// For non-materialized views, output AsSelect after storage
if n.AsSelect != nil && !n.Materialized {
// Set context flag to prevent Format from being output at SelectWithUnionQuery level
// (it will be output at CreateQuery level instead)
if hasFormat {
inCreateQueryContext = true
}
// AS SELECT is output directly without Subquery wrapper
Node(sb, n.AsSelect, depth+1)
if hasFormat {
inCreateQueryContext = false
}
}
if n.AsTableFunction != nil {
// AS table_function(...) is output directly
Node(sb, n.AsTableFunction, depth+1)
}
// Output FORMAT clause if present
if hasFormat {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format)
}
// Output COMMENT clause if present
if n.Comment != "" {
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, escapeStringLiteral(n.Comment))
}
}
func explainDropQuery(sb *strings.Builder, n *ast.DropQuery, indent string, depth int) {
// DROP USER has a special output format
if n.User != "" {
fmt.Fprintf(sb, "%sDROP USER query\n", indent)
return
}
// DROP FUNCTION has a special output format
if n.Function != "" {
fmt.Fprintf(sb, "%sDropFunctionQuery\n", indent)
return
}
// DROP ROLE
if n.Role != "" {
fmt.Fprintf(sb, "%sDROP ROLE query\n", indent)
return
}
// DROP QUOTA
if n.Quota != "" {
fmt.Fprintf(sb, "%sDROP QUOTA query\n", indent)
return
}
// DROP POLICY
if n.Policy != "" {
fmt.Fprintf(sb, "%sDROP POLICY query\n", indent)
return
}
// DROP ROW POLICY
if n.RowPolicy != "" {
fmt.Fprintf(sb, "%sDROP ROW POLICY query\n", indent)
return
}
// DROP SETTINGS PROFILE
if n.SettingsProfile != "" {
fmt.Fprintf(sb, "%sDROP SETTINGS PROFILE query\n", indent)
return
}
// DROP INDEX - outputs as DropIndexQuery with two spaces before table name
if n.Index != "" {
fmt.Fprintf(sb, "%sDropIndexQuery %s (children %d)\n", indent, n.Table, 2)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Index)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Table)
return
}
// Handle multiple tables: DROP TABLE t1, t2, t3
if len(n.Tables) > 1 {
fmt.Fprintf(sb, "%sDropQuery (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Tables))
for _, t := range n.Tables {
Node(sb, t, depth+2)
}
return
}
name := n.Table
if n.View != "" {
name = n.View
}
if n.Dictionary != "" {
name = n.Dictionary
}
if n.DropDatabase {
name = n.Database
}
// Check if we have a database-qualified name (for DROP TABLE db.table)
hasDatabase := n.Database != "" && !n.DropDatabase
hasFormat := n.Format != ""
if hasDatabase {
// Database-qualified: DropQuery db table (children 2 or 3)
children := 2
if hasFormat {
children = 3
}
fmt.Fprintf(sb, "%sDropQuery %s %s (children %d)\n", indent, EscapeIdentifier(n.Database), EscapeIdentifier(name), children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, EscapeIdentifier(n.Database))
fmt.Fprintf(sb, "%s Identifier %s\n", indent, EscapeIdentifier(name))
if hasFormat {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format)
}
} else if n.DropDatabase {
// DROP DATABASE uses different spacing
children := 1
if hasFormat {
children = 2
}
fmt.Fprintf(sb, "%sDropQuery %s (children %d)\n", indent, EscapeIdentifier(name), children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, EscapeIdentifier(name))
if hasFormat {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format)
}
} else {
children := 1
if hasFormat {
children++
}
if len(n.Settings) > 0 {
children++
}
fmt.Fprintf(sb, "%sDropQuery %s (children %d)\n", indent, EscapeIdentifier(name), children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, EscapeIdentifier(name))
if hasFormat {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format)
}
if len(n.Settings) > 0 {
fmt.Fprintf(sb, "%s Set\n", indent)
}
}
}
func explainUndropQuery(sb *strings.Builder, n *ast.UndropQuery, indent string, depth int) {
name := n.Table
// Check if we have a database-qualified name (for UNDROP TABLE db.table)
hasDatabase := n.Database != ""
hasFormat := n.Format != ""
if hasDatabase {
// Database-qualified: UndropQuery db table (children 2 or 3)
children := 2
if hasFormat {
children = 3
}
fmt.Fprintf(sb, "%sUndropQuery %s %s (children %d)\n", indent, EscapeIdentifier(n.Database), EscapeIdentifier(name), children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, EscapeIdentifier(n.Database))
fmt.Fprintf(sb, "%s Identifier %s\n", indent, EscapeIdentifier(name))
if hasFormat {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format)
}
} else {
children := 1
if hasFormat {
children = 2
}
fmt.Fprintf(sb, "%sUndropQuery %s (children %d)\n", indent, EscapeIdentifier(name), children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, EscapeIdentifier(name))
if hasFormat {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format)
}
}
}
func explainRenameQuery(sb *strings.Builder, n *ast.RenameQuery, indent string, depth int) {
if n == nil {
fmt.Fprintf(sb, "%s*ast.RenameQuery\n", indent)
return
}
// Count identifiers: 2 per pair if no database, 4 per pair if databases specified
hasSettings := len(n.Settings) > 0
children := 0
for _, pair := range n.Pairs {
if pair.FromDatabase != "" {
children++
}
children++ // from table
if pair.ToDatabase != "" {
children++
}
children++ // to table
}
if hasSettings {
children++
}
fmt.Fprintf(sb, "%sRename (children %d)\n", indent, children)
for _, pair := range n.Pairs {
// From database (only if specified)
if pair.FromDatabase != "" {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, pair.FromDatabase)
}
// From table
fmt.Fprintf(sb, "%s Identifier %s\n", indent, pair.FromTable)
// To database (only if specified)
if pair.ToDatabase != "" {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, pair.ToDatabase)
}
// To table
fmt.Fprintf(sb, "%s Identifier %s\n", indent, pair.ToTable)
}
if hasSettings {
fmt.Fprintf(sb, "%s Set\n", indent)
}
}
func explainExchangeQuery(sb *strings.Builder, n *ast.ExchangeQuery, indent string) {
if n == nil {
fmt.Fprintf(sb, "%s*ast.ExchangeQuery\n", indent)
return
}
// Count identifiers: 2 per table (db + table if qualified, or just table)
// EXCHANGE TABLES outputs as "Rename" in ClickHouse
children := 0
if n.Database1 != "" {
children += 2 // db1 + table1
} else {
children += 1 // just table1
}
if n.Database2 != "" {
children += 2 // db2 + table2
} else {
children += 1 // just table2
}
fmt.Fprintf(sb, "%sRename (children %d)\n", indent, children)
// First table
if n.Database1 != "" {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Database1)
}
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Table1)
// Second table
if n.Database2 != "" {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Database2)
}
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Table2)
}
func explainSetQuery(sb *strings.Builder, indent string) {
fmt.Fprintf(sb, "%sSet\n", indent)
}
func explainSystemQuery(sb *strings.Builder, n *ast.SystemQuery, indent string) {
// Some commands like FLUSH LOGS don't show the log name as a child
// For other commands, table/database names are shown as children
isFlushLogs := strings.HasPrefix(strings.ToUpper(n.Command), "FLUSH LOGS")
// Count children - database and table are children if present and not FLUSH LOGS
children := 0
if !isFlushLogs {
if n.Database != "" {
children++
}
if n.Table != "" {
children++
}
// For commands that need duplicate output, double the count
if n.DuplicateTableOutput && children > 0 {
children *= 2
}
}
if children > 0 {
fmt.Fprintf(sb, "%sSYSTEM query (children %d)\n", indent, children)
if n.Database != "" {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Database)
}
if n.Table != "" {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Table)
}
// Output again for duplicate commands
if n.DuplicateTableOutput {
if n.Database != "" {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Database)
}
if n.Table != "" {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Table)
}
}
} else {
fmt.Fprintf(sb, "%sSYSTEM query\n", indent)
}
}
func explainExplainQuery(sb *strings.Builder, n *ast.ExplainQuery, indent string, depth int) {
// Determine the type string - only show if explicitly specified AND not PLAN (default)
typeStr := ""
if n.ExplicitType && n.ExplainType != ast.ExplainPlan {
typeStr = " " + string(n.ExplainType)
}
// EXPLAIN CURRENT TRANSACTION has no children
if n.ExplainType == ast.ExplainCurrentTransaction {
// At top level (depth 0), ClickHouse outputs "Explain EXPLAIN <TYPE>"
if depth == 0 {
fmt.Fprintf(sb, "%sExplain EXPLAIN%s\n", indent, typeStr)
} else {
fmt.Fprintf(sb, "%sExplain%s\n", indent, typeStr)
}
return
}
// Check if inner statement has FORMAT clause - this should be output as child of Explain
// Also check for SETTINGS after FORMAT (these are at the EXPLAIN level, not part of the SELECT)
var format *ast.Identifier
var hasSettingsAfterFormat bool
var savedSettings []*ast.SettingExpr
if swu, ok := n.Statement.(*ast.SelectWithUnionQuery); ok {
// Check for union-level settings after format
if swu.SettingsAfterFormat && len(swu.Settings) > 0 {
hasSettingsAfterFormat = true
savedSettings = swu.Settings
swu.Settings = nil
defer func() { swu.Settings = savedSettings }()
}
for _, sel := range swu.Selects {
if sq, ok := sel.(*ast.SelectQuery); ok {
if sq.Format != nil {
format = sq.Format
// Temporarily nil out the format so it's not output by SelectWithUnionQuery
sq.Format = nil
defer func() { sq.Format = format }()
}
// Check for settings after format in the SelectQuery
if sq.SettingsAfterFormat && len(sq.Settings) > 0 && !hasSettingsAfterFormat {
hasSettingsAfterFormat = true
savedSettings = sq.Settings
sq.Settings = nil
defer func() { sq.Settings = savedSettings }()
}
break
}
}
}
// Count children: statement + format (if present) + settings (if present)
children := 1
if format != nil {
children++
}
if n.HasSettings || hasSettingsAfterFormat {
children++
}
// At top level (depth 0), ClickHouse outputs "Explain EXPLAIN <TYPE>"
// Nested in subqueries, it outputs "Explain <TYPE>"
if depth == 0 {
fmt.Fprintf(sb, "%sExplain EXPLAIN%s (children %d)\n", indent, typeStr, children)
} else {
fmt.Fprintf(sb, "%sExplain%s (children %d)\n", indent, typeStr, children)
}
// EXPLAIN-level settings (like header = 0) come BEFORE the statement
if n.HasSettings {
fmt.Fprintf(sb, "%s Set\n", indent)
}
// Output the statement
Node(sb, n.Statement, depth+1)
// Format comes after statement
if format != nil {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, format.Parts[len(format.Parts)-1])
}
// Settings after format (at the query level, e.g., FORMAT Null SETTINGS ...) come last
if hasSettingsAfterFormat {
fmt.Fprintf(sb, "%s Set\n", indent)
}
}
func explainShowQuery(sb *strings.Builder, n *ast.ShowQuery, indent string) {
// ClickHouse maps certain SHOW types to ShowTables in EXPLAIN AST
showType := strings.Title(strings.ToLower(string(n.ShowType)))
// SHOW SETTINGS and SHOW DATABASES are displayed as ShowTables in ClickHouse
if showType == "Settings" || showType == "Databases" {
showType = "Tables"
}
// SHOW CREATE DATABASE has special output format
if n.ShowType == ast.ShowCreateDB && n.From != "" {
fmt.Fprintf(sb, "%sShowCreateDatabaseQuery %s (children 1)\n", indent, n.From)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.From)
return
}
// SHOW CREATE DICTIONARY has special output format
if n.ShowType == ast.ShowCreateDictionary && (n.Database != "" || n.From != "") {
if n.Database != "" && n.From != "" {
children := 2
if n.Format != "" {
children++
}
if n.HasSettings {
children++
}
fmt.Fprintf(sb, "%sShowCreateDictionaryQuery %s %s (children %d)\n", indent, n.Database, n.From, children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Database)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.From)
if n.Format != "" {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format)
}
if n.HasSettings {
fmt.Fprintf(sb, "%s Set\n", indent)
}
} else if n.From != "" {
children := 1
if n.Format != "" {
children++
}
if n.HasSettings {
children++
}
fmt.Fprintf(sb, "%sShowCreateDictionaryQuery %s (children %d)\n", indent, n.From, children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.From)
if n.Format != "" {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format)
}
if n.HasSettings {
fmt.Fprintf(sb, "%s Set\n", indent)
}
} else if n.Database != "" {
children := 1
if n.Format != "" {
children++
}
if n.HasSettings {
children++
}
fmt.Fprintf(sb, "%sShowCreateDictionaryQuery %s (children %d)\n", indent, n.Database, children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Database)
if n.Format != "" {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format)
}
if n.HasSettings {
fmt.Fprintf(sb, "%s Set\n", indent)
}
}
return
}
// SHOW CREATE VIEW has special output format
if n.ShowType == ast.ShowCreateView && (n.Database != "" || n.From != "") {
if n.Database != "" && n.From != "" {
children := 2
if n.HasSettings {
children++
}
fmt.Fprintf(sb, "%sShowCreateViewQuery %s %s (children %d)\n", indent, n.Database, n.From, children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Database)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.From)
if n.HasSettings {
fmt.Fprintf(sb, "%s Set\n", indent)
}
} else if n.From != "" {
children := 1
if n.HasSettings {
children++
}
fmt.Fprintf(sb, "%sShowCreateViewQuery %s (children %d)\n", indent, n.From, children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.From)
if n.HasSettings {
fmt.Fprintf(sb, "%s Set\n", indent)
}
} else if n.Database != "" {
children := 1
if n.HasSettings {
children++
}
fmt.Fprintf(sb, "%sShowCreateViewQuery %s (children %d)\n", indent, n.Database, children)
fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Database)
if n.HasSettings {
fmt.Fprintf(sb, "%s Set\n", indent)