-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfunctions.go
More file actions
1424 lines (1318 loc) · 46.5 KB
/
functions.go
File metadata and controls
1424 lines (1318 loc) · 46.5 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"
)
// normalizeIntervalUnit converts interval units to title-cased singular form
// e.g., "years" -> "Year", "MONTH" -> "Month", "days" -> "Day"
func normalizeIntervalUnit(unit string) string {
if len(unit) == 0 {
return ""
}
u := strings.ToLower(unit)
// Remove trailing 's' for plural forms
if strings.HasSuffix(u, "s") && len(u) > 1 {
u = u[:len(u)-1]
}
// Title-case
return strings.ToUpper(u[:1]) + u[1:]
}
func explainFunctionCall(sb *strings.Builder, n *ast.FunctionCall, indent string, depth int) {
explainFunctionCallWithAlias(sb, n, n.Alias, indent, depth)
}
func explainFunctionCallWithAlias(sb *strings.Builder, n *ast.FunctionCall, alias string, indent string, depth int) {
// Handle special function transformations that ClickHouse does internally
if handled := handleSpecialFunction(sb, n, alias, indent, depth); handled {
return
}
children := 1 // arguments ExpressionList
if len(n.Parameters) > 0 {
children++ // parameters ExpressionList
}
// Only count WindowDefinition as a child for inline window specs that have content
// Empty OVER () doesn't produce a WindowDefinition in ClickHouse EXPLAIN AST
// Named refs like "OVER w" are shown in the SELECT's WINDOW clause instead
hasNonEmptyWindowSpec := n.Over != nil && n.Over.Name == "" && windowSpecHasContent(n.Over)
if hasNonEmptyWindowSpec {
children++ // WindowDefinition for OVER clause
}
// Normalize function name
fnName := NormalizeFunctionName(n.Name)
// Append "Distinct" if the function has DISTINCT modifier
if n.Distinct {
fnName = fnName + "Distinct"
}
if alias != "" {
fmt.Fprintf(sb, "%sFunction %s (alias %s) (children %d)\n", indent, fnName, alias, children)
} else {
fmt.Fprintf(sb, "%sFunction %s (children %d)\n", indent, fnName, children)
}
// Arguments (Settings are included as part of argument count)
argCount := len(n.Arguments)
if len(n.Settings) > 0 {
argCount++ // Set is counted as one argument
}
fmt.Fprintf(sb, "%s ExpressionList", indent)
if argCount > 0 {
fmt.Fprintf(sb, " (children %d)", argCount)
}
fmt.Fprintln(sb)
for _, arg := range n.Arguments {
// For view() table function, unwrap Subquery wrapper
// Also reset the subquery context since view() SELECT is not in a Subquery node
if strings.ToLower(n.Name) == "view" {
if sq, ok := arg.(*ast.Subquery); ok {
prevContext := inSubqueryContext
inSubqueryContext = false
Node(sb, sq.Query, depth+2)
inSubqueryContext = prevContext
continue
}
}
Node(sb, arg, depth+2)
}
// Settings appear as Set node inside ExpressionList
if len(n.Settings) > 0 {
fmt.Fprintf(sb, "%s Set\n", indent)
}
// Parameters (for parametric functions)
if len(n.Parameters) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Parameters))
for _, p := range n.Parameters {
Node(sb, p, depth+2)
}
}
// Window definition (for window functions with inline OVER clause)
// WindowDefinition is a sibling to ExpressionList, so use the same indent
// Only output for non-empty inline specs, not named references like "OVER w"
if hasNonEmptyWindowSpec {
explainWindowSpec(sb, n.Over, indent+" ", depth+1)
}
}
// windowSpecHasContent returns true if the window spec has any content.
// ClickHouse EXPLAIN AST never includes WindowDefinition nodes for window
// functions, even when OVER clause has PARTITION BY, ORDER BY, or frame specs.
func windowSpecHasContent(w *ast.WindowSpec) bool {
return false
}
// handleSpecialFunction handles special function transformations that ClickHouse does internally.
// Returns true if the function was handled, false otherwise.
func handleSpecialFunction(sb *strings.Builder, n *ast.FunctionCall, alias string, indent string, depth int) bool {
fnName := strings.ToUpper(n.Name)
// Handle quantified comparison operators (ANY/ALL with comparison operators)
if handled := handleQuantifiedComparison(sb, n, alias, indent, depth); handled {
return true
}
// POSITION('ll' IN 'Hello') -> position('Hello', 'll')
if fnName == "POSITION" && len(n.Arguments) == 1 {
if inExpr, ok := n.Arguments[0].(*ast.InExpr); ok {
// Transform: POSITION(needle IN haystack) -> position(haystack, needle)
explainPositionWithIn(sb, inExpr.Expr, inExpr.List[0], alias, indent, depth)
return true
}
}
// DATE_ADD/DATEADD/TIMESTAMP_ADD/TIMESTAMPADD
if fnName == "DATE_ADD" || fnName == "DATEADD" || fnName == "TIMESTAMP_ADD" || fnName == "TIMESTAMPADD" {
return handleDateAddSub(sb, n, alias, indent, depth, "plus")
}
// DATE_SUB/DATESUB/TIMESTAMP_SUB/TIMESTAMPSUB
if fnName == "DATE_SUB" || fnName == "DATESUB" || fnName == "TIMESTAMP_SUB" || fnName == "TIMESTAMPSUB" {
return handleDateAddSub(sb, n, alias, indent, depth, "minus")
}
// DATE_DIFF/DATEDIFF
if fnName == "DATE_DIFF" || fnName == "DATEDIFF" {
return handleDateDiff(sb, n, alias, indent, depth)
}
return false
}
// handleQuantifiedComparison handles ANY/ALL with comparison operators
// Returns true if the function was handled, false otherwise.
func handleQuantifiedComparison(sb *strings.Builder, n *ast.FunctionCall, alias string, indent string, depth int) bool {
fnName := strings.ToLower(n.Name)
// Check if this is a quantified comparison function
var modifier, op string
if strings.HasPrefix(fnName, "any") {
modifier = "any"
op = fnName[3:]
} else if strings.HasPrefix(fnName, "all") {
modifier = "all"
op = fnName[3:]
} else {
return false
}
// Must have exactly 2 arguments: left expr and subquery
if len(n.Arguments) != 2 {
return false
}
subquery, ok := n.Arguments[1].(*ast.Subquery)
if !ok {
return false
}
// Handle based on the operator and modifier
switch op {
case "equals":
if modifier == "any" {
// x == ANY (subquery) -> in(x, subquery)
return false // Let NormalizeFunctionName handle this
}
// x == ALL (subquery) -> complex with singleValueOrNull
outputQuantifiedWithAggregate(sb, n.Arguments[0], subquery, "in", "singleValueOrNull", alias, indent, depth)
return true
case "notequals":
if modifier == "all" {
// x != ALL (subquery) -> notIn(x, subquery)
return false // Let NormalizeFunctionName handle this
}
// x != ANY (subquery) -> complex notIn with singleValueOrNull
outputQuantifiedWithAggregate(sb, n.Arguments[0], subquery, "notIn", "singleValueOrNull", alias, indent, depth)
return true
case "less":
if modifier == "any" {
// x < ANY (subquery) -> x < max(subquery)
outputQuantifiedWithAggregate(sb, n.Arguments[0], subquery, "less", "max", alias, indent, depth)
} else {
// x < ALL (subquery) -> x < min(subquery)
outputQuantifiedWithAggregate(sb, n.Arguments[0], subquery, "less", "min", alias, indent, depth)
}
return true
case "lessorequals":
if modifier == "any" {
// x <= ANY (subquery) -> x <= max(subquery)
outputQuantifiedWithAggregate(sb, n.Arguments[0], subquery, "lessOrEquals", "max", alias, indent, depth)
} else {
// x <= ALL (subquery) -> x <= min(subquery)
outputQuantifiedWithAggregate(sb, n.Arguments[0], subquery, "lessOrEquals", "min", alias, indent, depth)
}
return true
case "greater":
if modifier == "any" {
// x > ANY (subquery) -> x > min(subquery)
outputQuantifiedWithAggregate(sb, n.Arguments[0], subquery, "greater", "min", alias, indent, depth)
} else {
// x > ALL (subquery) -> x > max(subquery)
outputQuantifiedWithAggregate(sb, n.Arguments[0], subquery, "greater", "max", alias, indent, depth)
}
return true
case "greaterorequals":
if modifier == "any" {
// x >= ANY (subquery) -> x >= min(subquery)
outputQuantifiedWithAggregate(sb, n.Arguments[0], subquery, "greaterOrEquals", "min", alias, indent, depth)
} else {
// x >= ALL (subquery) -> x >= max(subquery)
outputQuantifiedWithAggregate(sb, n.Arguments[0], subquery, "greaterOrEquals", "max", alias, indent, depth)
}
return true
}
return false
}
// outputQuantifiedWithAggregate outputs the ClickHouse AST format for quantified comparisons
// with an aggregate function wrapped around the subquery
func outputQuantifiedWithAggregate(sb *strings.Builder, left ast.Expression, subquery *ast.Subquery, compFunc, aggFunc string, alias string, indent string, depth int) {
if alias != "" {
fmt.Fprintf(sb, "%sFunction %s (alias %s) (children %d)\n", indent, compFunc, alias, 1)
} else {
fmt.Fprintf(sb, "%sFunction %s (children %d)\n", indent, compFunc, 1)
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 2)
Node(sb, left, depth+2)
// Output the subquery wrapped with aggregate function
// Structure: Subquery -> SelectWithUnionQuery -> ExpressionList -> SelectQuery with 4 children
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)
// Second ExpressionList with aggregate function (repeated)
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)
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)
}
// explainPositionWithIn outputs POSITION(needle IN haystack) as position(haystack, needle)
func explainPositionWithIn(sb *strings.Builder, needle, haystack ast.Expression, alias string, indent string, depth int) {
if alias != "" {
fmt.Fprintf(sb, "%sFunction position (alias %s) (children %d)\n", indent, alias, 1)
} else {
fmt.Fprintf(sb, "%sFunction position (children %d)\n", indent, 1)
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 2)
// Arguments are swapped: haystack first, then needle
Node(sb, haystack, depth+2)
Node(sb, needle, depth+2)
}
// handleDateAddSub handles DATE_ADD/DATE_SUB and variants
// opFunc is "plus" for ADD or "minus" for SUB
func handleDateAddSub(sb *strings.Builder, n *ast.FunctionCall, alias string, indent string, depth int, opFunc string) bool {
if len(n.Arguments) == 3 {
// DATE_ADD(unit, n, date) -> plus/minus(date, toIntervalUnit(n))
unitArg := n.Arguments[0]
valueArg := n.Arguments[1]
dateArg := n.Arguments[2]
// Extract unit from identifier
unitName := ""
if ident, ok := unitArg.(*ast.Identifier); ok {
unitName = ident.Name()
}
if unitName != "" {
explainDateAddSubResult(sb, opFunc, dateArg, valueArg, unitName, alias, indent, depth)
return true
}
} else if len(n.Arguments) == 2 {
// DATE_ADD(interval, date) -> plus(interval, date)
// DATE_SUB(date, interval) -> minus(date, interval)
intervalArg := n.Arguments[0]
dateArg := n.Arguments[1]
// Check which argument is the interval
if _, ok := intervalArg.(*ast.IntervalExpr); ok {
// Interval first: plus(interval, date)
explainDateAddSubWithInterval(sb, opFunc, intervalArg, dateArg, alias, indent, depth)
return true
}
// Check if first arg is already a toInterval function (from parser)
if fc, ok := intervalArg.(*ast.FunctionCall); ok && strings.HasPrefix(strings.ToLower(fc.Name), "tointerval") {
// Interval first: plus(interval, date)
explainDateAddSubWithInterval(sb, opFunc, intervalArg, dateArg, alias, indent, depth)
return true
}
// DATE_SUB(date, interval) -> minus(date, interval)
if _, ok := dateArg.(*ast.IntervalExpr); ok {
explainDateAddSubWithInterval(sb, opFunc, intervalArg, dateArg, alias, indent, depth)
return true
}
if fc, ok := dateArg.(*ast.FunctionCall); ok && strings.HasPrefix(strings.ToLower(fc.Name), "tointerval") {
explainDateAddSubWithInterval(sb, opFunc, intervalArg, dateArg, alias, indent, depth)
return true
}
}
return false
}
// explainDateAddSubResult outputs the transformed DATE_ADD/SUB with unit syntax
func explainDateAddSubResult(sb *strings.Builder, opFunc string, dateArg, valueArg ast.Expression, unit string, alias string, indent string, depth int) {
if alias != "" {
fmt.Fprintf(sb, "%sFunction %s (alias %s) (children %d)\n", indent, opFunc, alias, 1)
} else {
fmt.Fprintf(sb, "%sFunction %s (children %d)\n", indent, opFunc, 1)
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 2)
// First arg: date
Node(sb, dateArg, depth+2)
// Second arg: toIntervalUnit(value)
unitNorm := normalizeIntervalUnit(unit)
fmt.Fprintf(sb, "%s Function toInterval%s (children %d)\n", indent, unitNorm, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 1)
Node(sb, valueArg, depth+4)
}
// explainDateAddSubWithInterval outputs the transformed DATE_ADD/SUB with INTERVAL syntax
func explainDateAddSubWithInterval(sb *strings.Builder, opFunc string, arg1, arg2 ast.Expression, alias string, indent string, depth int) {
if alias != "" {
fmt.Fprintf(sb, "%sFunction %s (alias %s) (children %d)\n", indent, opFunc, alias, 1)
} else {
fmt.Fprintf(sb, "%sFunction %s (children %d)\n", indent, opFunc, 1)
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 2)
Node(sb, arg1, depth+2)
Node(sb, arg2, depth+2)
}
// handleDateDiff handles DATE_DIFF/DATEDIFF
// DATE_DIFF(unit, date1, date2[, timezone]) -> dateDiff('unit', date1, date2[, timezone])
func handleDateDiff(sb *strings.Builder, n *ast.FunctionCall, alias string, indent string, depth int) bool {
if len(n.Arguments) < 3 || len(n.Arguments) > 4 {
return false
}
unitArg := n.Arguments[0]
date1Arg := n.Arguments[1]
date2Arg := n.Arguments[2]
// Extract unit from identifier
unitName := ""
if ident, ok := unitArg.(*ast.Identifier); ok {
unitName = ident.Name()
}
if unitName == "" {
return false
}
argCount := 3
if len(n.Arguments) == 4 {
argCount = 4
}
if alias != "" {
fmt.Fprintf(sb, "%sFunction dateDiff (alias %s) (children %d)\n", indent, alias, 1)
} else {
fmt.Fprintf(sb, "%sFunction dateDiff (children %d)\n", indent, 1)
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, argCount)
// First arg: unit as lowercase string literal
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, strings.ToLower(unitName))
// Second and third args: dates
Node(sb, date1Arg, depth+2)
Node(sb, date2Arg, depth+2)
// Fourth arg: optional timezone
if len(n.Arguments) == 4 {
Node(sb, n.Arguments[3], depth+2)
}
return true
}
func explainLambda(sb *strings.Builder, n *ast.Lambda, indent string, depth int) {
explainLambdaWithAlias(sb, n, "", indent, depth)
}
func explainLambdaWithAlias(sb *strings.Builder, n *ast.Lambda, alias string, indent string, depth int) {
// Lambda is represented as Function lambda with tuple of params and body
if alias != "" {
fmt.Fprintf(sb, "%sFunction lambda (alias %s) (children %d)\n", indent, alias, 1)
} else {
fmt.Fprintf(sb, "%sFunction lambda (children %d)\n", indent, 1)
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 2)
// Parameters as tuple
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", indent, 1)
// When there are no parameters, ClickHouse omits the (children N) part
if len(n.Parameters) > 0 {
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Parameters))
for _, p := range n.Parameters {
fmt.Fprintf(sb, "%s Identifier %s\n", indent, p)
}
} else {
fmt.Fprintf(sb, "%s ExpressionList\n", indent)
}
// Body
Node(sb, n.Body, depth+2)
}
func explainCastExpr(sb *strings.Builder, n *ast.CastExpr, indent string, depth int) {
explainCastExprWithAlias(sb, n, n.Alias, indent, depth)
}
func explainCastExprWithAlias(sb *strings.Builder, n *ast.CastExpr, alias string, indent string, depth int) {
// For :: operator syntax with arrays/tuples, determine formatting based on content
useArrayFormat := false
if n.OperatorSyntax {
if lit, ok := n.Expr.(*ast.Literal); ok {
if lit.Type == ast.LiteralArray || lit.Type == ast.LiteralTuple {
// Determine format based on both content and target type
useArrayFormat = shouldUseArrayFormat(lit, n.Type)
}
}
}
// Alias is always shown for :: cast syntax with arrays/tuples
hideAlias := false
// CAST is represented as Function CAST with expr and type as arguments
if alias != "" && !hideAlias {
fmt.Fprintf(sb, "%sFunction CAST (alias %s) (children %d)\n", indent, alias, 1)
} else {
fmt.Fprintf(sb, "%sFunction CAST (children %d)\n", indent, 1)
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 2)
// For :: operator syntax with simple literals, format as string literal
// For function syntax or complex expressions, use normal AST node
if n.OperatorSyntax {
if lit, ok := n.Expr.(*ast.Literal); ok {
// For arrays/tuples of simple primitives, use FormatLiteral (Array_[...] format)
// For strings and other types, use string format
if lit.Type == ast.LiteralArray || lit.Type == ast.LiteralTuple {
if useArrayFormat {
fmt.Fprintf(sb, "%s Literal %s\n", indent, FormatLiteral(lit))
} else {
// Complex content - format as string
exprStr := formatExprAsString(lit)
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, exprStr)
}
} else if lit.Type == ast.LiteralNull {
// NULL stays as Literal NULL, not formatted as a string
fmt.Fprintf(sb, "%s Literal NULL\n", indent)
} else {
// Simple literal - format as string
exprStr := formatExprAsString(lit)
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, exprStr)
}
} else if negatedLit := extractNegatedLiteral(n.Expr); negatedLit != "" {
// Handle negated literal like -0::Int16 -> CAST('-0', 'Int16')
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, negatedLit)
} else {
// Complex expression - use normal AST node
Node(sb, n.Expr, depth+2)
}
} else {
Node(sb, n.Expr, depth+2)
}
// Type is formatted as a literal string, or as a node if it's a dynamic type expression
if n.TypeExpr != nil {
Node(sb, n.TypeExpr, depth+2)
} else {
typeStr := FormatDataType(n.Type)
// Only escape if the DataType doesn't have parameters - this means the entire
// type was parsed from a string literal and may contain unescaped quotes.
// If it has parameters, FormatDataType already handles escaping.
if n.Type == nil || len(n.Type.Parameters) == 0 {
typeStr = escapeStringLiteral(typeStr)
}
fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, typeStr)
}
}
// shouldUseArrayFormat determines whether to use Array_[...] format or string format
// for array/tuple literals in :: cast expressions.
// ClickHouse uses different formats depending on element types:
// - Boolean arrays: Array_[Bool_0, Bool_1] format
// - Numeric arrays: '[1, 2, 3]' string format
func shouldUseArrayFormat(lit *ast.Literal, targetType *ast.DataType) bool {
// First check if the literal contains only primitive literals (not expressions)
if !containsOnlyLiterals(lit) {
return false
}
// Check if array contains boolean elements - these use Array_ format
if containsBooleanElements(lit) {
return true
}
// Check if array contains NULL elements - these use Array_ format
if containsNullElements(lit) {
return true
}
// For arrays of strings, always use string format in :: casts
// This applies to all target types including Array(String)
if lit.Type == ast.LiteralArray && hasStringElements(lit) {
return false
}
// For numeric primitives, use string format in :: casts
return false
}
// containsNullElements checks if a literal array/tuple contains NULL elements
func containsNullElements(lit *ast.Literal) bool {
var exprs []ast.Expression
switch lit.Type {
case ast.LiteralArray, ast.LiteralTuple:
var ok bool
exprs, ok = lit.Value.([]ast.Expression)
if !ok {
return false
}
default:
return false
}
for _, e := range exprs {
innerLit, ok := e.(*ast.Literal)
if !ok {
continue
}
if innerLit.Type == ast.LiteralNull {
return true
}
// Check nested arrays/tuples
if innerLit.Type == ast.LiteralArray || innerLit.Type == ast.LiteralTuple {
if containsNullElements(innerLit) {
return true
}
}
}
return false
}
// containsBooleanElements checks if a literal array/tuple contains boolean elements
func containsBooleanElements(lit *ast.Literal) bool {
var exprs []ast.Expression
switch lit.Type {
case ast.LiteralArray, ast.LiteralTuple:
var ok bool
exprs, ok = lit.Value.([]ast.Expression)
if !ok {
return false
}
default:
return false
}
for _, e := range exprs {
innerLit, ok := e.(*ast.Literal)
if !ok {
continue
}
if innerLit.Type == ast.LiteralBoolean {
return true
}
// Check nested arrays/tuples
if innerLit.Type == ast.LiteralArray || innerLit.Type == ast.LiteralTuple {
if containsBooleanElements(innerLit) {
return true
}
}
}
return false
}
// containsOnlyLiterals checks if a literal array/tuple contains only literal values (no expressions)
func containsOnlyLiterals(lit *ast.Literal) bool {
var exprs []ast.Expression
switch lit.Type {
case ast.LiteralArray, ast.LiteralTuple:
var ok bool
exprs, ok = lit.Value.([]ast.Expression)
if !ok {
return false
}
default:
return true
}
for _, e := range exprs {
innerLit, ok := e.(*ast.Literal)
if !ok {
return false
}
// Nested arrays/tuples need recursive check
if innerLit.Type == ast.LiteralArray || innerLit.Type == ast.LiteralTuple {
if !containsOnlyLiterals(innerLit) {
return false
}
}
}
return true
}
// hasStringElements checks if an array literal contains any string elements
func hasStringElements(lit *ast.Literal) bool {
if lit.Type != ast.LiteralArray {
return false
}
exprs, ok := lit.Value.([]ast.Expression)
if !ok {
return false
}
for _, e := range exprs {
if innerLit, ok := e.(*ast.Literal); ok {
if innerLit.Type == ast.LiteralString {
return true
}
}
}
return false
}
// containsOnlyPrimitives checks if a literal array/tuple contains only primitive literals
// Deprecated: Use shouldUseArrayFormat instead for :: cast expressions
func containsOnlyPrimitives(lit *ast.Literal) bool {
var exprs []ast.Expression
switch lit.Type {
case ast.LiteralArray, ast.LiteralTuple:
var ok bool
exprs, ok = lit.Value.([]ast.Expression)
if !ok {
return false
}
default:
return true
}
for _, e := range exprs {
innerLit, ok := e.(*ast.Literal)
if !ok {
return false
}
// Nested arrays/tuples need recursive check
if innerLit.Type == ast.LiteralArray || innerLit.Type == ast.LiteralTuple {
if !containsOnlyPrimitives(innerLit) {
return false
}
}
}
return true
}
// isNumericExpr checks if an expression is a numeric value (literal or unary minus of numeric)
func isNumericExpr(expr ast.Expression) bool {
if lit, ok := expr.(*ast.Literal); ok {
return lit.Type == ast.LiteralInteger || lit.Type == ast.LiteralFloat
}
if unary, ok := expr.(*ast.UnaryExpr); ok && unary.Op == "-" {
if lit, ok := unary.Operand.(*ast.Literal); ok {
return lit.Type == ast.LiteralInteger || lit.Type == ast.LiteralFloat
}
}
return false
}
// containsOnlyPrimitiveLiterals checks if a tuple literal contains only primitive literals (recursively)
func containsOnlyPrimitiveLiterals(lit *ast.Literal) bool {
if lit.Type != ast.LiteralTuple {
// Non-tuple literals are primitive
return true
}
exprs, ok := lit.Value.([]ast.Expression)
if !ok {
return false
}
for _, e := range exprs {
innerLit, ok := e.(*ast.Literal)
if !ok {
// Non-literal expression in tuple
return false
}
// Recursively check nested tuples
if innerLit.Type == ast.LiteralTuple {
if !containsOnlyPrimitiveLiterals(innerLit) {
return false
}
}
}
return true
}
// containsOnlyPrimitiveLiteralsWithUnary is like containsOnlyPrimitiveLiterals but also handles
// unary negation of numeric literals (e.g., -0., -123)
func containsOnlyPrimitiveLiteralsWithUnary(lit *ast.Literal) bool {
if lit.Type != ast.LiteralTuple {
// Non-tuple literals are primitive
return true
}
exprs, ok := lit.Value.([]ast.Expression)
if !ok {
return false
}
for _, e := range exprs {
// Direct literal
if innerLit, ok := e.(*ast.Literal); ok {
// Recursively check nested tuples
if innerLit.Type == ast.LiteralTuple {
if !containsOnlyPrimitiveLiteralsWithUnary(innerLit) {
return false
}
}
// Arrays inside tuples make it complex
if innerLit.Type == ast.LiteralArray {
return false
}
continue
}
// Unary negation of numeric literal is also primitive
if unary, ok := e.(*ast.UnaryExpr); ok && unary.Op == "-" {
if innerLit, ok := unary.Operand.(*ast.Literal); ok {
if innerLit.Type == ast.LiteralInteger || innerLit.Type == ast.LiteralFloat {
continue
}
}
}
// Non-literal expression in tuple
return false
}
return true
}
// exprToLiteral converts a numeric expression to a literal (handles unary minus)
func exprToLiteral(expr ast.Expression) *ast.Literal {
if lit, ok := expr.(*ast.Literal); ok {
return lit
}
if unary, ok := expr.(*ast.UnaryExpr); ok && unary.Op == "-" {
if lit, ok := unary.Operand.(*ast.Literal); ok {
// Create a new literal with negated value
switch val := lit.Value.(type) {
case int64:
return &ast.Literal{Type: ast.LiteralInteger, Value: -val}
case uint64:
// Convert to int64 and negate
return &ast.Literal{Type: ast.LiteralInteger, Value: -int64(val)}
case float64:
return &ast.Literal{Type: ast.LiteralFloat, Value: -val}
}
}
}
return nil
}
// extractNegatedLiteral checks if expr is a negated literal (like -0, -12)
// and returns its string representation (like "-0", "-12") for :: cast expressions.
// Returns empty string if not a negated literal.
func extractNegatedLiteral(expr ast.Expression) string {
unary, ok := expr.(*ast.UnaryExpr)
if !ok || unary.Op != "-" {
return ""
}
lit, ok := unary.Operand.(*ast.Literal)
if !ok {
return ""
}
switch lit.Type {
case ast.LiteralInteger:
return "-" + formatExprAsString(lit)
case ast.LiteralFloat:
return "-" + formatExprAsString(lit)
}
return ""
}
func explainInExpr(sb *strings.Builder, n *ast.InExpr, indent string, depth int) {
// IN is represented as Function in
fnName := "in"
if n.Not {
fnName = "notIn"
}
if n.Global {
fnName = "global" + strings.Title(fnName)
}
fmt.Fprintf(sb, "%sFunction %s (children %d)\n", indent, fnName, 1)
// Determine if the IN list should be combined into a single tuple literal
// This happens when we have multiple literals of compatible types:
// - All numeric literals/expressions (integers/floats, including unary minus) + NULLs
// - All string literals + NULLs
// - All tuple literals that contain only primitive literals (recursively)
canBeTupleLiteral := false
if n.Query == nil && len(n.List) > 1 {
allNumericOrNull := true
allStringsOrNull := true
allTuples := true
allTuplesArePrimitive := true
hasNonNull := false // Need at least one non-null value
for _, item := range n.List {
if lit, ok := item.(*ast.Literal); ok {
if lit.Type == ast.LiteralNull {
// NULL is compatible with both numeric and string lists
continue
}
hasNonNull = true
if lit.Type != ast.LiteralInteger && lit.Type != ast.LiteralFloat {
allNumericOrNull = false
}
if lit.Type != ast.LiteralString {
allStringsOrNull = false
}
if lit.Type != ast.LiteralTuple {
allTuples = false
} else {
// Check if this tuple contains only primitive literals
if !containsOnlyPrimitiveLiterals(lit) {
allTuplesArePrimitive = false
}
}
} else if isNumericExpr(item) {
// Unary minus of numeric is still numeric
hasNonNull = true
allStringsOrNull = false
allTuples = false
} else {
allNumericOrNull = false
allStringsOrNull = false
allTuples = false
break
}
}
// For tuples, only combine if all contain primitive literals
canBeTupleLiteral = hasNonNull && (allNumericOrNull || allStringsOrNull || (allTuples && allTuplesArePrimitive))
}
// Count arguments: expr + list items or subquery
argCount := 1
if n.Query != nil {
argCount++
} else if canBeTupleLiteral {
// Multiple literals will be combined into a single tuple
argCount++
} else {
// Check if we have a single tuple literal that should be wrapped in Function tuple
if len(n.List) == 1 {
if lit, ok := n.List[0].(*ast.Literal); ok && lit.Type == ast.LiteralTuple {
// Single tuple literal gets wrapped in Function tuple, so count as 1
argCount++
} else {
argCount += len(n.List)
}
} else {
// Non-string items get wrapped in a single Function tuple
argCount++
}
}
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, argCount)
Node(sb, n.Expr, depth+2)
if n.Query != nil {
// Subqueries in IN should be wrapped in Subquery node
fmt.Fprintf(sb, "%s Subquery (children %d)\n", indent, 1)
Node(sb, n.Query, depth+3)
} else if canBeTupleLiteral {
// Combine multiple literals into a single Tuple literal
tupleLit := &ast.Literal{
Type: ast.LiteralTuple,
Value: n.List,
}
fmt.Fprintf(sb, "%s Literal %s\n", indent, FormatLiteral(tupleLit))
} else if len(n.List) == 1 {
// Single element in the list
// If it's a tuple literal, wrap it in Function tuple
// Otherwise, output the element directly
if lit, ok := n.List[0].(*ast.Literal); ok && lit.Type == ast.LiteralTuple {
// Wrap tuple literal in Function tuple
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 1)
Node(sb, n.List[0], depth+4)
} else {
// Single non-tuple element - output directly
Node(sb, n.List[0], depth+2)
}
} else {
// Check if all items are tuple literals (some may have expressions)
allTuples := true
for _, item := range n.List {
if lit, ok := item.(*ast.Literal); !ok || lit.Type != ast.LiteralTuple {
allTuples = false
break
}
}
if allTuples {
// Wrap all tuples in Function tuple
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.List))
for _, item := range n.List {
explainTupleInInList(sb, item.(*ast.Literal), indent+" ", depth+4)
}
} else {
// Wrap non-literal/non-tuple list items in Function tuple
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.List))
for _, item := range n.List {
Node(sb, item, depth+4)
}
}
}
}
// explainTupleInInList renders a tuple in an IN list - either as Literal or Function tuple
func explainTupleInInList(sb *strings.Builder, lit *ast.Literal, indent string, depth int) {
if containsOnlyPrimitiveLiterals(lit) {
// All primitives - render as Literal Tuple_
fmt.Fprintf(sb, "%s Literal %s\n", indent, FormatLiteral(lit))
} else {
// Contains expressions - render as Function tuple
exprs, ok := lit.Value.([]ast.Expression)
if !ok {
fmt.Fprintf(sb, "%s Literal %s\n", indent, FormatLiteral(lit))
return
}
fmt.Fprintf(sb, "%s Function tuple (children %d)\n", indent, 1)
fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(exprs))
for _, e := range exprs {
Node(sb, e, depth+2)
}
}
}
func explainInExprWithAlias(sb *strings.Builder, n *ast.InExpr, alias string, indent string, depth int) {
// IN is represented as Function in with alias
fnName := "in"
if n.Not {
fnName = "notIn"
}
if n.Global {
fnName = "global" + strings.Title(fnName)
}
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)
}
// Determine if the IN list should be combined into a single tuple literal
// Only combine strings into tuple for small lists (up to 10 items)
const maxStringTupleSizeWithAlias = 10
canBeTupleLiteral := false
if n.Query == nil && len(n.List) > 1 {
allNumericOrNull := true
allStringsOrNull := true
allTuples := true
allTuplesArePrimitive := true
hasNonNull := false // Need at least one non-null value
for _, item := range n.List {
if lit, ok := item.(*ast.Literal); ok {
if lit.Type == ast.LiteralNull {
// NULL is compatible with both numeric and string lists
continue