-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexpression.go
More file actions
1904 lines (1658 loc) · 43.6 KB
/
expression.go
File metadata and controls
1904 lines (1658 loc) · 43.6 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 parser
import (
"math"
"strconv"
"strings"
"github.com/kyleconroy/doubleclick/ast"
"github.com/kyleconroy/doubleclick/token"
)
// Operator precedence levels
const (
LOWEST = iota
ALIAS_PREC // AS
OR_PREC // OR
AND_PREC // AND
NOT_PREC // NOT
COMPARE // =, !=, <, >, <=, >=, LIKE, IN, BETWEEN, IS
CONCAT_PREC // ||
ADD_PREC // +, -
MUL_PREC // *, /, %
UNARY // -x, NOT x
CALL // function(), array[]
HIGHEST
)
func (p *Parser) precedence(tok token.Token) int {
switch tok {
case token.AS:
return ALIAS_PREC
case token.OR:
return OR_PREC
case token.AND:
return AND_PREC
case token.NOT:
return NOT_PREC
case token.EQ, token.NEQ, token.LT, token.GT, token.LTE, token.GTE,
token.LIKE, token.ILIKE, token.REGEXP, token.IN, token.BETWEEN, token.IS,
token.NULL_SAFE_EQ, token.GLOBAL:
return COMPARE
case token.QUESTION:
return COMPARE // Ternary operator
case token.CONCAT:
return CONCAT_PREC
case token.PLUS, token.MINUS:
return ADD_PREC
case token.ASTERISK, token.SLASH, token.PERCENT, token.DIV, token.MOD:
return MUL_PREC
case token.LPAREN, token.LBRACKET:
return CALL
case token.EXCEPT, token.REPLACE:
return CALL // For asterisk modifiers
case token.COLONCOLON:
return CALL // Cast operator
case token.DOT:
return HIGHEST // Dot access
case token.ARROW:
return OR_PREC // Lambda arrow (just above ALIAS_PREC to allow parsing before AS)
case token.NUMBER:
// Handle .1 as tuple access (number starting with dot)
return LOWEST
default:
return LOWEST
}
}
// precedenceForCurrent returns the precedence for the current token,
// with special handling for tuple access (number starting with dot)
func (p *Parser) precedenceForCurrent() int {
if p.currentIs(token.NUMBER) && strings.HasPrefix(p.current.Value, ".") {
return HIGHEST // Tuple access like t.1
}
return p.precedence(p.current.Token)
}
func (p *Parser) parseExpressionList() []ast.Expression {
var exprs []ast.Expression
if p.currentIs(token.RPAREN) || p.currentIs(token.EOF) {
return exprs
}
expr := p.parseExpression(LOWEST)
if expr != nil {
// Handle implicit alias (identifier without AS)
expr = p.parseImplicitAlias(expr)
exprs = append(exprs, expr)
}
for p.currentIs(token.COMMA) {
p.nextToken()
expr := p.parseExpression(LOWEST)
if expr != nil {
// Handle implicit alias (identifier without AS)
expr = p.parseImplicitAlias(expr)
exprs = append(exprs, expr)
}
}
return exprs
}
// parseGroupingSets parses GROUPING SETS ((a), (b), (a, b))
func (p *Parser) parseGroupingSets() []ast.Expression {
var exprs []ast.Expression
if !p.expect(token.LPAREN) {
return exprs
}
for !p.currentIs(token.RPAREN) && !p.currentIs(token.EOF) {
// Each element in GROUPING SETS is a tuple or a single expression
if p.currentIs(token.LPAREN) {
// Parse as tuple
tuple := p.parseGroupedOrTuple()
exprs = append(exprs, tuple)
} else {
// Single expression
expr := p.parseExpression(LOWEST)
if expr != nil {
exprs = append(exprs, expr)
}
}
// Skip comma if present
if p.currentIs(token.COMMA) {
p.nextToken()
}
}
p.expect(token.RPAREN)
return exprs
}
// parseFunctionArgumentList parses arguments for function calls, stopping at SETTINGS
func (p *Parser) parseFunctionArgumentList() []ast.Expression {
var exprs []ast.Expression
if p.currentIs(token.RPAREN) || p.currentIs(token.EOF) || p.currentIs(token.SETTINGS) {
return exprs
}
expr := p.parseExpression(LOWEST)
if expr != nil {
exprs = append(exprs, expr)
}
for p.currentIs(token.COMMA) {
p.nextToken()
// Stop if we hit SETTINGS
if p.currentIs(token.SETTINGS) {
break
}
expr := p.parseExpression(LOWEST)
if expr != nil {
exprs = append(exprs, expr)
}
}
return exprs
}
// parseImplicitAlias handles implicit column aliases like "SELECT 'a' c0" (meaning 'a' AS c0)
func (p *Parser) parseImplicitAlias(expr ast.Expression) ast.Expression {
// Check if current token can be an implicit alias
// Can be IDENT or certain keywords that are used as aliases (KEY, VALUE, TYPE, etc.)
canBeAlias := p.currentIs(token.IDENT)
if !canBeAlias {
// Some keywords can be used as implicit aliases in ClickHouse
switch p.current.Token {
case token.KEY, token.INDEX, token.VIEW, token.DATABASE, token.TABLE:
canBeAlias = true
}
}
if canBeAlias {
upper := strings.ToUpper(p.current.Value)
// Don't consume SQL set operation keywords that aren't tokens
if upper == "INTERSECT" {
return expr
}
alias := p.current.Value
p.nextToken()
// Set alias on the expression if it supports it
switch e := expr.(type) {
case *ast.Identifier:
e.Alias = alias
return e
case *ast.FunctionCall:
e.Alias = alias
return e
case *ast.Subquery:
e.Alias = alias
return e
case *ast.CastExpr:
// Only set alias on CastExpr if using :: operator syntax
// Function-style CAST() aliases go to AliasedExpr
if e.OperatorSyntax {
e.Alias = alias
return e
}
return &ast.AliasedExpr{
Position: expr.Pos(),
Expr: expr,
Alias: alias,
}
case *ast.CaseExpr:
e.Alias = alias
return e
case *ast.ExtractExpr:
e.Alias = alias
return e
default:
return &ast.AliasedExpr{
Position: expr.Pos(),
Expr: expr,
Alias: alias,
}
}
}
return expr
}
func (p *Parser) parseExpression(precedence int) ast.Expression {
left := p.parsePrefixExpression()
if left == nil {
return nil
}
for !p.currentIs(token.EOF) && precedence < p.precedenceForCurrent() {
left = p.parseInfixExpression(left)
if left == nil {
return nil
}
}
return left
}
func (p *Parser) parsePrefixExpression() ast.Expression {
switch p.current.Token {
case token.IDENT:
return p.parseIdentifierOrFunction()
case token.NUMBER:
return p.parseNumber()
case token.STRING:
return p.parseString()
case token.TRUE, token.FALSE:
return p.parseBoolean()
case token.NULL:
return p.parseNull()
case token.NAN, token.INF:
return p.parseSpecialNumber()
case token.MINUS:
return p.parseUnaryMinus()
case token.PLUS:
return p.parseUnaryPlus()
case token.NOT:
return p.parseNot()
case token.LPAREN:
return p.parseGroupedOrTuple()
case token.LBRACKET:
return p.parseArrayLiteral()
case token.ASTERISK:
return p.parseAsterisk()
case token.CASE:
return p.parseCase()
case token.CAST:
return p.parseCast()
case token.EXTRACT:
return p.parseExtract()
case token.INTERVAL:
// INTERVAL can be a literal (INTERVAL 1 DAY) or identifier reference
// Check if next token can start an interval value
if p.peekIs(token.NUMBER) || p.peekIs(token.LPAREN) || p.peekIs(token.MINUS) || p.peekIs(token.STRING) || p.peekIs(token.IDENT) {
return p.parseInterval()
}
// Otherwise treat as identifier
return p.parseKeywordAsIdentifier()
case token.EXISTS:
return p.parseExists()
case token.PARAM:
return p.parseParameter()
case token.QUESTION:
return p.parsePositionalParameter()
case token.SUBSTRING:
return p.parseSubstring()
case token.TRIM:
return p.parseTrim()
case token.COLUMNS:
return p.parseColumnsMatcher()
case token.ARRAY:
// array(1,2,3) constructor
return p.parseArrayConstructor()
case token.IF:
// IF function
return p.parseIfFunction()
case token.FORMAT:
// format() function (not FORMAT clause)
if p.peekIs(token.LPAREN) {
return p.parseKeywordAsFunction()
}
// format as identifier (e.g., format='Parquet' in function args)
return p.parseKeywordAsIdentifier()
default:
// Handle other keywords that can be used as function names or identifiers
if p.current.Token.IsKeyword() {
if p.peekIs(token.LPAREN) {
return p.parseKeywordAsFunction()
}
// Keywords like ALL, DEFAULT, etc. can be used as identifiers
return p.parseKeywordAsIdentifier()
}
return nil
}
}
func (p *Parser) parseInfixExpression(left ast.Expression) ast.Expression {
switch p.current.Token {
case token.PLUS, token.MINUS, token.ASTERISK, token.SLASH, token.PERCENT,
token.EQ, token.NEQ, token.LT, token.GT, token.LTE, token.GTE,
token.AND, token.OR, token.CONCAT, token.DIV, token.MOD:
return p.parseBinaryExpression(left)
case token.NULL_SAFE_EQ:
return p.parseBinaryExpression(left)
case token.QUESTION:
return p.parseTernary(left)
case token.LIKE, token.ILIKE:
return p.parseLikeExpression(left, false)
case token.REGEXP:
return p.parseRegexpExpression(left, false)
case token.NOT:
// NOT IN, NOT LIKE, NOT BETWEEN, NOT REGEXP, IS NOT
p.nextToken()
switch p.current.Token {
case token.IN:
return p.parseInExpression(left, true)
case token.LIKE:
return p.parseLikeExpression(left, true)
case token.ILIKE:
return p.parseLikeExpression(left, true)
case token.REGEXP:
return p.parseRegexpExpression(left, true)
case token.BETWEEN:
return p.parseBetweenExpression(left, true)
default:
// Put back NOT and treat as binary
return left
}
case token.IN:
return p.parseInExpression(left, false)
case token.GLOBAL:
// GLOBAL IN or GLOBAL NOT IN
p.nextToken()
not := false
if p.currentIs(token.NOT) {
not = true
p.nextToken()
}
if p.currentIs(token.IN) {
expr := p.parseInExpression(left, not)
if inExpr, ok := expr.(*ast.InExpr); ok {
inExpr.Global = true
}
return expr
}
return left
case token.BETWEEN:
return p.parseBetweenExpression(left, false)
case token.IS:
return p.parseIsExpression(left)
case token.LPAREN:
// Function call on identifier
if ident, ok := left.(*ast.Identifier); ok {
return p.parseFunctionCall(ident.Name(), ident.Position)
}
// Parametric function call like quantile(0.9)(number)
if fn, ok := left.(*ast.FunctionCall); ok {
return p.parseParametricFunctionCall(fn)
}
return left
case token.LBRACKET:
return p.parseArrayAccess(left)
case token.DOT:
return p.parseDotAccess(left)
case token.AS:
return p.parseAlias(left)
case token.COLONCOLON:
return p.parseCastOperator(left)
case token.ARROW:
return p.parseLambda(left)
case token.EXCEPT:
// Handle * EXCEPT (col1, col2)
if asterisk, ok := left.(*ast.Asterisk); ok {
return p.parseAsteriskExcept(asterisk)
}
return left
case token.REPLACE:
// Handle * REPLACE (expr AS col)
if asterisk, ok := left.(*ast.Asterisk); ok {
return p.parseAsteriskReplace(asterisk)
}
return left
case token.NUMBER:
// Handle tuple access like t.1 where .1 is lexed as a number
if strings.HasPrefix(p.current.Value, ".") {
return p.parseTupleAccessFromNumber(left)
}
return left
default:
return left
}
}
func (p *Parser) parseIdentifierOrFunction() ast.Expression {
pos := p.current.Pos
name := p.current.Value
p.nextToken()
// Check for function call
if p.currentIs(token.LPAREN) {
return p.parseFunctionCall(name, pos)
}
// Check for qualified identifier (a.b.c)
parts := []string{name}
for p.currentIs(token.DOT) {
p.nextToken()
if p.currentIs(token.CARET) {
// JSON path notation: x.^c0 (traverse into JSON field)
p.nextToken() // skip ^
if p.currentIs(token.IDENT) || p.current.Token.IsKeyword() {
parts = append(parts, "^"+p.current.Value)
p.nextToken()
} else {
break
}
} else if p.currentIs(token.IDENT) || p.current.Token.IsKeyword() {
// Keywords can be used as column/field names (e.g., l_t.key, t.index)
parts = append(parts, p.current.Value)
p.nextToken()
} else if p.currentIs(token.ASTERISK) {
// table.*
p.nextToken()
return &ast.Asterisk{
Position: pos,
Table: strings.Join(parts, "."),
}
} else {
break
}
}
// Check for function call after qualified name
if p.currentIs(token.LPAREN) {
return p.parseFunctionCall(strings.Join(parts, "."), pos)
}
return &ast.Identifier{
Position: pos,
Parts: parts,
}
}
func (p *Parser) parseFunctionCall(name string, pos token.Position) *ast.FunctionCall {
fn := &ast.FunctionCall{
Position: pos,
Name: name,
}
p.nextToken() // skip (
// Handle DISTINCT
if p.currentIs(token.DISTINCT) {
fn.Distinct = true
p.nextToken()
}
// Handle view() and similar functions that take a subquery as argument
// view(SELECT ...) should parse SELECT as a subquery, not expression
if strings.ToLower(name) == "view" && (p.currentIs(token.SELECT) || p.currentIs(token.WITH)) {
subquery := p.parseSelectWithUnion()
fn.Arguments = []ast.Expression{&ast.Subquery{Position: pos, Query: subquery}}
} else if !p.currentIs(token.RPAREN) && !p.currentIs(token.SETTINGS) {
// Parse arguments
fn.Arguments = p.parseFunctionArgumentList()
}
// Handle SETTINGS inside function call (table functions)
if p.currentIs(token.SETTINGS) {
p.nextToken()
fn.Settings = p.parseSettingsList()
}
p.expect(token.RPAREN)
// Handle IGNORE NULLS / RESPECT NULLS (window function modifiers)
// Can appear multiple times (e.g., RESPECT NULLS IGNORE NULLS)
for p.currentIs(token.IDENT) {
upper := strings.ToUpper(p.current.Value)
if upper == "IGNORE" || upper == "RESPECT" {
p.nextToken()
if p.currentIs(token.NULLS) {
p.nextToken()
}
} else {
break
}
}
// Handle FILTER clause for aggregate functions: func() FILTER(WHERE condition)
if p.currentIs(token.IDENT) && strings.ToUpper(p.current.Value) == "FILTER" {
p.nextToken() // skip FILTER
if p.currentIs(token.LPAREN) {
p.nextToken() // skip (
if p.currentIs(token.WHERE) {
p.nextToken() // skip WHERE
// Parse the filter condition - just consume it for now
// The filter is essentially a where clause for the aggregate
p.parseExpression(LOWEST)
}
p.expect(token.RPAREN)
}
}
// Handle OVER clause for window functions
if p.currentIs(token.OVER) {
p.nextToken()
fn.Over = p.parseWindowSpec()
}
// Note: AS alias is handled by the expression parser's infix handling (parseAlias)
// to respect precedence levels when called from contexts like WITH clauses
return fn
}
func (p *Parser) parseWindowSpec() *ast.WindowSpec {
spec := &ast.WindowSpec{
Position: p.current.Pos,
}
if p.currentIs(token.IDENT) {
// Window name reference (OVER w0)
spec.Name = p.current.Value
p.nextToken()
return spec
}
if !p.expect(token.LPAREN) {
return spec
}
// Check for named window reference inside parentheses: OVER (w0)
// This happens when the identifier is not a known clause keyword
if p.currentIs(token.IDENT) {
upper := strings.ToUpper(p.current.Value)
// If it's not a window clause keyword, it's a named window reference
if upper != "PARTITION" && upper != "ORDER" && upper != "ROWS" && upper != "RANGE" && upper != "GROUPS" {
spec.Name = p.current.Value
p.nextToken()
p.expect(token.RPAREN)
return spec
}
}
// Parse PARTITION BY
if p.currentIs(token.PARTITION) {
p.nextToken()
if p.expect(token.BY) {
spec.PartitionBy = p.parseExpressionList()
}
}
// Parse ORDER BY
if p.currentIs(token.ORDER) {
p.nextToken()
if p.expect(token.BY) {
spec.OrderBy = p.parseOrderByList()
}
}
// Parse frame specification
if p.currentIs(token.IDENT) {
frameType := strings.ToUpper(p.current.Value)
if frameType == "ROWS" || frameType == "RANGE" || frameType == "GROUPS" {
spec.Frame = p.parseWindowFrame()
}
}
p.expect(token.RPAREN)
return spec
}
func (p *Parser) parseWindowFrame() *ast.WindowFrame {
frame := &ast.WindowFrame{
Position: p.current.Pos,
}
switch strings.ToUpper(p.current.Value) {
case "ROWS":
frame.Type = ast.FrameRows
case "RANGE":
frame.Type = ast.FrameRange
case "GROUPS":
frame.Type = ast.FrameGroups
}
p.nextToken()
if p.currentIs(token.BETWEEN) {
p.nextToken()
frame.StartBound = p.parseFrameBound()
if p.currentIs(token.AND) {
p.nextToken()
frame.EndBound = p.parseFrameBound()
}
} else {
frame.StartBound = p.parseFrameBound()
}
return frame
}
func (p *Parser) parseFrameBound() *ast.FrameBound {
bound := &ast.FrameBound{
Position: p.current.Pos,
}
if p.currentIs(token.IDENT) && strings.ToUpper(p.current.Value) == "CURRENT" {
p.nextToken()
if p.currentIs(token.IDENT) && strings.ToUpper(p.current.Value) == "ROW" {
p.nextToken()
}
bound.Type = ast.BoundCurrentRow
return bound
}
if p.currentIs(token.IDENT) && strings.ToUpper(p.current.Value) == "UNBOUNDED" {
p.nextToken()
if p.currentIs(token.IDENT) {
switch strings.ToUpper(p.current.Value) {
case "PRECEDING":
bound.Type = ast.BoundUnboundedPre
case "FOLLOWING":
bound.Type = ast.BoundUnboundedFol
}
p.nextToken()
}
return bound
}
// n PRECEDING or n FOLLOWING
bound.Offset = p.parseExpression(LOWEST)
if p.currentIs(token.IDENT) {
switch strings.ToUpper(p.current.Value) {
case "PRECEDING":
bound.Type = ast.BoundPreceding
case "FOLLOWING":
bound.Type = ast.BoundFollowing
}
p.nextToken()
}
return bound
}
func (p *Parser) parseNumber() ast.Expression {
lit := &ast.Literal{
Position: p.current.Pos,
}
value := p.current.Value
p.nextToken()
// Check if this is a hex, binary, or octal number
isHex := strings.HasPrefix(value, "0x") || strings.HasPrefix(value, "0X")
isBin := strings.HasPrefix(value, "0b") || strings.HasPrefix(value, "0B")
isOctal := strings.HasPrefix(value, "0o") || strings.HasPrefix(value, "0O")
// Check for hex float (e.g., 0x1.2p3)
isHexFloat := isHex && (strings.ContainsAny(value, "pP") || strings.Contains(value, "."))
// Check if it's a decimal float (but not a hex/binary/octal integer)
// Note: hex numbers can contain 'e' as a hex digit, so we need to exclude them
isDecimalFloat := !isHex && !isBin && !isOctal && (strings.Contains(value, ".") || strings.ContainsAny(value, "eE"))
if isDecimalFloat {
f, err := strconv.ParseFloat(value, 64)
if err != nil {
lit.Type = ast.LiteralString
lit.Value = value
} else {
lit.Type = ast.LiteralFloat
lit.Value = f
}
} else if isHexFloat {
// Parse hex float (Go doesn't support this directly, approximate)
// For now, store as string - ClickHouse will interpret it
lit.Type = ast.LiteralString
lit.Value = value
} else {
// Determine the base for parsing
// - 0x/0X: hex (base 16)
// - 0b/0B: binary (base 2)
// - 0o/0O: octal (base 8, explicit notation)
// - Otherwise: decimal (base 10) - ClickHouse does NOT use leading zero for octal
base := 10
if isHex {
base = 0 // Let strconv detect hex
} else if isBin {
base = 0 // Let strconv detect binary
} else if isOctal {
base = 0 // Let strconv detect octal with 0o prefix
}
// Note: We explicitly use base 10 for numbers like "077" because
// ClickHouse does NOT interpret leading zeros as octal
// Try signed int64 first
i, err := strconv.ParseInt(value, base, 64)
if err != nil {
// Try unsigned uint64 for large positive numbers
u, uerr := strconv.ParseUint(value, base, 64)
if uerr != nil {
lit.Type = ast.LiteralString
lit.Value = value
} else {
lit.Type = ast.LiteralInteger
lit.Value = u // Store as uint64
}
} else {
lit.Type = ast.LiteralInteger
lit.Value = i
}
}
return lit
}
func (p *Parser) parseString() ast.Expression {
lit := &ast.Literal{
Position: p.current.Pos,
Type: ast.LiteralString,
Value: p.current.Value,
}
p.nextToken()
return lit
}
func (p *Parser) parseBoolean() ast.Expression {
lit := &ast.Literal{
Position: p.current.Pos,
Type: ast.LiteralBoolean,
Value: p.current.Token == token.TRUE,
}
p.nextToken()
return lit
}
func (p *Parser) parseNull() ast.Expression {
lit := &ast.Literal{
Position: p.current.Pos,
Type: ast.LiteralNull,
Value: nil,
}
p.nextToken()
return lit
}
func (p *Parser) parseSpecialNumber() ast.Expression {
lit := &ast.Literal{
Position: p.current.Pos,
Type: ast.LiteralFloat,
}
switch p.current.Token {
case token.NAN:
lit.Value = math.NaN()
case token.INF:
lit.Value = math.Inf(1)
}
p.nextToken()
return lit
}
func (p *Parser) parseUnaryMinus() ast.Expression {
expr := &ast.UnaryExpr{
Position: p.current.Pos,
Op: "-",
}
p.nextToken()
expr.Operand = p.parseExpression(UNARY)
return expr
}
func (p *Parser) parseUnaryPlus() ast.Expression {
expr := &ast.UnaryExpr{
Position: p.current.Pos,
Op: "+",
}
p.nextToken()
expr.Operand = p.parseExpression(UNARY)
return expr
}
func (p *Parser) parseNot() ast.Expression {
expr := &ast.UnaryExpr{
Position: p.current.Pos,
Op: "NOT",
}
p.nextToken()
expr.Operand = p.parseExpression(NOT_PREC)
return expr
}
func (p *Parser) parseGroupedOrTuple() ast.Expression {
pos := p.current.Pos
p.nextToken() // skip (
// Handle empty tuple ()
if p.currentIs(token.RPAREN) {
p.nextToken()
return &ast.Literal{
Position: pos,
Type: ast.LiteralTuple,
Value: []ast.Expression{},
}
}
// Check for subquery (SELECT, WITH, or EXPLAIN)
if p.currentIs(token.SELECT) || p.currentIs(token.WITH) {
subquery := p.parseSelectWithUnion()
p.expect(token.RPAREN)
return &ast.Subquery{
Position: pos,
Query: subquery,
}
}
// EXPLAIN as subquery
if p.currentIs(token.EXPLAIN) {
explain := p.parseExplain()
p.expect(token.RPAREN)
return &ast.Subquery{
Position: pos,
Query: explain,
}
}
// Parse first expression
first := p.parseExpression(LOWEST)
// Check if it's a tuple
if p.currentIs(token.COMMA) {
elements := []ast.Expression{first}
for p.currentIs(token.COMMA) {
p.nextToken()
elements = append(elements, p.parseExpression(LOWEST))
}
p.expect(token.RPAREN)
return &ast.Literal{
Position: pos,
Type: ast.LiteralTuple,
Value: elements,
}
}
p.expect(token.RPAREN)
return first
}
func (p *Parser) parseArrayLiteral() ast.Expression {
lit := &ast.Literal{
Position: p.current.Pos,
Type: ast.LiteralArray,
}
p.nextToken() // skip [
var elements []ast.Expression
if !p.currentIs(token.RBRACKET) {
elements = p.parseExpressionList()
}
lit.Value = elements
p.expect(token.RBRACKET)
return lit
}
func (p *Parser) parseAsterisk() ast.Expression {
asterisk := &ast.Asterisk{
Position: p.current.Pos,
}
p.nextToken()
return asterisk
}
func (p *Parser) parseCase() ast.Expression {
expr := &ast.CaseExpr{
Position: p.current.Pos,
}
p.nextToken() // skip CASE
// Check for CASE operand (simple CASE)
if !p.currentIs(token.WHEN) {
expr.Operand = p.parseExpression(LOWEST)
}
// Parse WHEN clauses
for p.currentIs(token.WHEN) {
when := &ast.WhenClause{
Position: p.current.Pos,
}
p.nextToken() // skip WHEN
when.Condition = p.parseExpression(LOWEST)
if !p.expect(token.THEN) {
break
}
when.Result = p.parseExpression(LOWEST)
expr.Whens = append(expr.Whens, when)
}
// Parse ELSE clause
if p.currentIs(token.ELSE) {
p.nextToken()
expr.Else = p.parseExpression(LOWEST)
}
p.expect(token.END)
// Handle alias
if p.currentIs(token.AS) {
p.nextToken()
if p.currentIs(token.IDENT) {
expr.Alias = p.current.Value
p.nextToken()
}
}
return expr
}
func (p *Parser) parseCast() ast.Expression {
expr := &ast.CastExpr{
Position: p.current.Pos,
}
p.nextToken() // skip CAST
if !p.expect(token.LPAREN) {
return nil
}
// Use ALIAS_PREC to avoid consuming AS as an alias operator
expr.Expr = p.parseExpression(ALIAS_PREC)
// Handle both CAST(x AS Type) and CAST(x, 'Type') or CAST(x, expr) syntax
if p.currentIs(token.AS) {
p.nextToken()
expr.Type = p.parseDataType()
expr.UsedASSyntax = true
} else if p.currentIs(token.COMMA) {
p.nextToken()
// Type can be given as a string literal or an expression (e.g., if(cond, 'Type1', 'Type2'))
if p.currentIs(token.STRING) {
expr.Type = &ast.DataType{
Position: p.current.Pos,
Name: p.current.Value,
}
p.nextToken()
} else {
// Parse as expression for dynamic type casting
expr.TypeExpr = p.parseExpression(LOWEST)
}
}
p.expect(token.RPAREN)
return expr
}
func (p *Parser) parseExtract() ast.Expression {
pos := p.current.Pos
p.nextToken() // skip EXTRACT
if !p.expect(token.LPAREN) {
return nil
}
// Check if it's EXTRACT(field FROM expr) form
// The field must be a known date/time field identifier followed by FROM
if p.currentIs(token.IDENT) && !p.peekIs(token.LPAREN) {
field := strings.ToUpper(p.current.Value)
// Check if it's a known date/time field
dateTimeFields := map[string]bool{
"YEAR": true, "QUARTER": true, "MONTH": true, "WEEK": true,
"DAY": true, "DAYOFWEEK": true, "DAYOFYEAR": true,
"HOUR": true, "MINUTE": true, "SECOND": true,
"TIMEZONE_HOUR": true, "TIMEZONE_MINUTE": true,
}