-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse_select.go
More file actions
1938 lines (1666 loc) · 47.4 KB
/
parse_select.go
File metadata and controls
1938 lines (1666 loc) · 47.4 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 provides T-SQL parsing functionality.
package parser
import (
"fmt"
"strings"
"github.com/kyleconroy/teesql/ast"
)
func (p *Parser) parsePrintStatement() (*ast.PrintStatement, error) {
// Consume PRINT
p.nextToken()
// Parse expression
expr, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
// Skip optional semicolon
if p.curTok.Type == TokenSemicolon {
p.nextToken()
}
return &ast.PrintStatement{Expression: expr}, nil
}
func (p *Parser) parseThrowStatement() (*ast.ThrowStatement, error) {
// Consume THROW
p.nextToken()
stmt := &ast.ThrowStatement{}
// THROW can be used without arguments (re-throw)
if p.curTok.Type == TokenSemicolon || p.curTok.Type == TokenEOF ||
p.curTok.Type == TokenSelect || p.curTok.Type == TokenPrint || p.curTok.Type == TokenThrow {
return stmt, nil
}
// Parse error number
errNum, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
stmt.ErrorNumber = errNum
// Expect comma
if p.curTok.Type != TokenComma {
return nil, fmt.Errorf("expected comma after error number, got %s", p.curTok.Literal)
}
p.nextToken()
// Parse message
msg, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
stmt.Message = msg
// Expect comma
if p.curTok.Type != TokenComma {
return nil, fmt.Errorf("expected comma after message, got %s", p.curTok.Literal)
}
p.nextToken()
// Parse state
state, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
stmt.State = state
// Skip optional semicolon
if p.curTok.Type == TokenSemicolon {
p.nextToken()
}
return stmt, nil
}
func (p *Parser) parseSelectStatement() (*ast.SelectStatement, error) {
stmt := &ast.SelectStatement{}
// Parse query expression (handles UNION, parens, etc.)
qe, into, err := p.parseQueryExpressionWithInto()
if err != nil {
return nil, err
}
stmt.QueryExpression = qe
stmt.Into = into
// Parse optional OPTION clause
if p.curTok.Type == TokenOption {
hints, err := p.parseOptionClause()
if err != nil {
return nil, err
}
stmt.OptimizerHints = hints
}
// Skip optional semicolon
if p.curTok.Type == TokenSemicolon {
p.nextToken()
}
return stmt, nil
}
func (p *Parser) parseQueryExpression() (ast.QueryExpression, error) {
qe, _, err := p.parseQueryExpressionWithInto()
return qe, err
}
func (p *Parser) parseQueryExpressionWithInto() (ast.QueryExpression, *ast.SchemaObjectName, error) {
// Parse primary query expression (could be SELECT or parenthesized)
left, into, err := p.parsePrimaryQueryExpression()
if err != nil {
return nil, nil, err
}
// Track if we have any binary operations
hasBinaryOp := false
// Check for binary operations (UNION, EXCEPT, INTERSECT)
for p.curTok.Type == TokenUnion || p.curTok.Type == TokenExcept || p.curTok.Type == TokenIntersect {
hasBinaryOp = true
var opType string
switch p.curTok.Type {
case TokenUnion:
opType = "Union"
case TokenExcept:
opType = "Except"
case TokenIntersect:
opType = "Intersect"
}
p.nextToken()
// Check for ALL
all := false
if p.curTok.Type == TokenAll {
all = true
p.nextToken()
}
// Parse the right side
right, rightInto, err := p.parsePrimaryQueryExpression()
if err != nil {
return nil, nil, err
}
// INTO can only appear in the first query of a UNION
if rightInto != nil && into == nil {
into = rightInto
}
bqe := &ast.BinaryQueryExpression{
BinaryQueryExpressionType: opType,
All: all,
FirstQueryExpression: left,
SecondQueryExpression: right,
}
left = bqe
}
// Parse ORDER BY after all UNION operations
if p.curTok.Type == TokenOrder {
obc, err := p.parseOrderByClause()
if err != nil {
return nil, nil, err
}
if hasBinaryOp {
// Attach to BinaryQueryExpression
if bqe, ok := left.(*ast.BinaryQueryExpression); ok {
bqe.OrderByClause = obc
}
} else {
// Attach to QuerySpecification
if qs, ok := left.(*ast.QuerySpecification); ok {
qs.OrderByClause = obc
}
}
}
return left, into, nil
}
func (p *Parser) parsePrimaryQueryExpression() (ast.QueryExpression, *ast.SchemaObjectName, error) {
if p.curTok.Type == TokenLParen {
p.nextToken() // consume (
qe, into, err := p.parseQueryExpressionWithInto()
if err != nil {
return nil, nil, err
}
if p.curTok.Type != TokenRParen {
return nil, nil, fmt.Errorf("expected ), got %s", p.curTok.Literal)
}
p.nextToken() // consume )
return &ast.QueryParenthesisExpression{QueryExpression: qe}, into, nil
}
return p.parseQuerySpecificationWithInto()
}
func (p *Parser) parseQuerySpecificationWithInto() (*ast.QuerySpecification, *ast.SchemaObjectName, error) {
qs, err := p.parseQuerySpecificationCore()
if err != nil {
return nil, nil, err
}
// Check for INTO clause after SELECT elements, before FROM
var into *ast.SchemaObjectName
if p.curTok.Type == TokenInto {
p.nextToken() // consume INTO
into, err = p.parseSchemaObjectName()
if err != nil {
return nil, nil, err
}
}
// Parse optional FROM clause
if p.curTok.Type == TokenFrom {
fromClause, err := p.parseFromClause()
if err != nil {
return nil, nil, err
}
qs.FromClause = fromClause
}
// Parse optional WHERE clause
if p.curTok.Type == TokenWhere {
whereClause, err := p.parseWhereClause()
if err != nil {
return nil, nil, err
}
qs.WhereClause = whereClause
}
// Parse optional GROUP BY clause
if p.curTok.Type == TokenGroup {
groupByClause, err := p.parseGroupByClause()
if err != nil {
return nil, nil, err
}
qs.GroupByClause = groupByClause
}
// Parse optional HAVING clause
if p.curTok.Type == TokenHaving {
havingClause, err := p.parseHavingClause()
if err != nil {
return nil, nil, err
}
qs.HavingClause = havingClause
}
// Note: ORDER BY is parsed at the top level in parseQueryExpressionWithInto
// to correctly handle UNION/EXCEPT/INTERSECT cases
return qs, into, nil
}
func (p *Parser) parseQuerySpecificationCore() (*ast.QuerySpecification, error) {
qs := &ast.QuerySpecification{
UniqueRowFilter: "NotSpecified",
}
// Expect SELECT
if p.curTok.Type != TokenSelect {
return nil, fmt.Errorf("expected SELECT, got %s", p.curTok.Literal)
}
p.nextToken()
// Check for ALL or DISTINCT
if p.curTok.Type == TokenAll {
qs.UniqueRowFilter = "All"
p.nextToken()
} else if p.curTok.Type == TokenDistinct {
qs.UniqueRowFilter = "Distinct"
p.nextToken()
}
// Check for TOP clause
if p.curTok.Type == TokenTop {
top, err := p.parseTopRowFilter()
if err != nil {
return nil, err
}
qs.TopRowFilter = top
}
// Parse select elements
elements, err := p.parseSelectElements()
if err != nil {
return nil, err
}
qs.SelectElements = elements
return qs, nil
}
func (p *Parser) parseTopRowFilter() (*ast.TopRowFilter, error) {
// Consume TOP
p.nextToken()
top := &ast.TopRowFilter{}
// Check for parenthesized expression
if p.curTok.Type == TokenLParen {
p.nextToken() // consume (
expr, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
top.Expression = expr
if p.curTok.Type != TokenRParen {
return nil, fmt.Errorf("expected ), got %s", p.curTok.Literal)
}
p.nextToken() // consume )
} else {
// Parse literal expression
expr, err := p.parsePrimaryExpression()
if err != nil {
return nil, err
}
top.Expression = expr
}
// Check for PERCENT
if p.curTok.Type == TokenPercent {
top.Percent = true
p.nextToken()
}
// Check for WITH TIES
if p.curTok.Type == TokenWith {
p.nextToken() // consume WITH
if p.curTok.Type == TokenTies {
top.WithTies = true
p.nextToken()
}
}
return top, nil
}
func (p *Parser) parseSelectElements() ([]ast.SelectElement, error) {
var elements []ast.SelectElement
for {
elem, err := p.parseSelectElement()
if err != nil {
return nil, err
}
elements = append(elements, elem)
if p.curTok.Type != TokenComma {
break
}
p.nextToken() // consume comma
}
return elements, nil
}
func (p *Parser) parseSelectElement() (ast.SelectElement, error) {
// Check for *
if p.curTok.Type == TokenStar {
p.nextToken()
return &ast.SelectStarExpression{}, nil
}
// Check for variable assignment: @var = expr or @var ||= expr
if p.curTok.Type == TokenIdent && strings.HasPrefix(p.curTok.Literal, "@") {
varName := p.curTok.Literal
p.nextToken() // consume variable
// Check if this is an assignment
if p.isCompoundAssignment() {
ssv := &ast.SelectSetVariable{
Variable: &ast.VariableReference{Name: varName},
AssignmentKind: p.getAssignmentKind(),
}
p.nextToken() // consume assignment operator
expr, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
ssv.Expression = expr
return ssv, nil
}
// Not an assignment, treat as regular scalar expression starting with variable
// We need to "un-consume" the variable and let parseScalarExpression handle it
// Create the variable reference and use it as the expression
varRef := &ast.VariableReference{Name: varName}
sse := &ast.SelectScalarExpression{Expression: varRef}
// Check for column alias
if p.curTok.Type == TokenIdent && p.curTok.Literal[0] == '[' {
alias := p.parseIdentifier()
sse.ColumnName = &ast.IdentifierOrValueExpression{
Value: alias.Value,
Identifier: alias,
}
} else if p.curTok.Type == TokenAs {
p.nextToken()
alias := p.parseIdentifier()
sse.ColumnName = &ast.IdentifierOrValueExpression{
Value: alias.Value,
Identifier: alias,
}
} else if p.curTok.Type == TokenIdent {
upper := strings.ToUpper(p.curTok.Literal)
if upper != "FROM" && upper != "WHERE" && upper != "GROUP" && upper != "HAVING" && upper != "ORDER" && upper != "OPTION" && upper != "INTO" && upper != "UNION" && upper != "EXCEPT" && upper != "INTERSECT" && upper != "GO" {
alias := p.parseIdentifier()
sse.ColumnName = &ast.IdentifierOrValueExpression{
Value: alias.Value,
Identifier: alias,
}
}
}
return sse, nil
}
// Otherwise parse a scalar expression
expr, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
sse := &ast.SelectScalarExpression{Expression: expr}
// Check for column alias: [alias], AS alias, or just alias
if p.curTok.Type == TokenIdent && p.curTok.Literal[0] == '[' {
// Bracketed alias without AS
alias := p.parseIdentifier()
sse.ColumnName = &ast.IdentifierOrValueExpression{
Value: alias.Value,
Identifier: alias,
}
} else if p.curTok.Type == TokenAs {
p.nextToken() // consume AS
alias := p.parseIdentifier()
sse.ColumnName = &ast.IdentifierOrValueExpression{
Value: alias.Value,
Identifier: alias,
}
} else if p.curTok.Type == TokenIdent {
// Check if this is an alias (not a keyword that starts a new clause)
upper := strings.ToUpper(p.curTok.Literal)
if upper != "FROM" && upper != "WHERE" && upper != "GROUP" && upper != "HAVING" && upper != "ORDER" && upper != "OPTION" && upper != "INTO" && upper != "UNION" && upper != "EXCEPT" && upper != "INTERSECT" && upper != "GO" {
alias := p.parseIdentifier()
sse.ColumnName = &ast.IdentifierOrValueExpression{
Value: alias.Value,
Identifier: alias,
}
}
}
return sse, nil
}
func (p *Parser) parseIdentifier() *ast.Identifier {
literal := p.curTok.Literal
quoteType := "NotQuoted"
// Handle bracketed identifiers
if len(literal) >= 2 && literal[0] == '[' && literal[len(literal)-1] == ']' {
quoteType = "SquareBracket"
literal = literal[1 : len(literal)-1]
}
id := &ast.Identifier{
Value: literal,
QuoteType: quoteType,
}
p.nextToken()
return id
}
// isKeywordAsIdentifier returns true if the current token is a keyword that can be used as an identifier
func (p *Parser) isKeywordAsIdentifier() bool {
// In T-SQL, many keywords can be used as identifiers in the right context
// This includes database objects, table names, column names, etc.
switch p.curTok.Type {
case TokenMaster, TokenKey, TokenIndex, TokenLanguage,
TokenUser, TokenSchema, TokenDatabase, TokenTable,
TokenView, TokenProcedure, TokenFunction, TokenTrigger,
TokenDefault, TokenMessage, TokenCredential, TokenCertificate, TokenLogin,
TokenExternal, TokenSymmetric, TokenAsymmetric, TokenGroup,
TokenAdd, TokenGrant, TokenRevoke, TokenBackup, TokenRestore,
TokenQuery, TokenJob, TokenStats, TokenPassword, TokenTime, TokenDelay,
TokenTyp:
return true
default:
return false
}
}
func (p *Parser) parseScalarExpression() (ast.ScalarExpression, error) {
return p.parseShiftExpression()
}
func (p *Parser) parseShiftExpression() (ast.ScalarExpression, error) {
left, err := p.parseAdditiveExpression()
if err != nil {
return nil, err
}
for p.curTok.Type == TokenLeftShift || p.curTok.Type == TokenRightShift {
var opType string
if p.curTok.Type == TokenLeftShift {
opType = "LeftShift"
} else {
opType = "RightShift"
}
p.nextToken()
right, err := p.parseAdditiveExpression()
if err != nil {
return nil, err
}
left = &ast.BinaryExpression{
BinaryExpressionType: opType,
FirstExpression: left,
SecondExpression: right,
}
}
return left, nil
}
func (p *Parser) parseAdditiveExpression() (ast.ScalarExpression, error) {
left, err := p.parseMultiplicativeExpression()
if err != nil {
return nil, err
}
for p.curTok.Type == TokenPlus || p.curTok.Type == TokenMinus || p.curTok.Type == TokenDoublePipe {
var opType string
switch p.curTok.Type {
case TokenPlus:
opType = "Add"
case TokenMinus:
opType = "Subtract"
case TokenDoublePipe:
opType = "Concat"
}
p.nextToken()
right, err := p.parseMultiplicativeExpression()
if err != nil {
return nil, err
}
left = &ast.BinaryExpression{
BinaryExpressionType: opType,
FirstExpression: left,
SecondExpression: right,
}
}
return left, nil
}
func (p *Parser) parseMultiplicativeExpression() (ast.ScalarExpression, error) {
left, err := p.parsePrimaryExpression()
if err != nil {
return nil, err
}
for p.curTok.Type == TokenStar || p.curTok.Type == TokenSlash || p.curTok.Type == TokenModulo {
var opType string
switch p.curTok.Type {
case TokenStar:
opType = "Multiply"
case TokenSlash:
opType = "Divide"
case TokenModulo:
opType = "Modulo"
}
p.nextToken()
right, err := p.parsePrimaryExpression()
if err != nil {
return nil, err
}
left = &ast.BinaryExpression{
BinaryExpressionType: opType,
FirstExpression: left,
SecondExpression: right,
}
}
return left, nil
}
func (p *Parser) parsePrimaryExpression() (ast.ScalarExpression, error) {
switch p.curTok.Type {
case TokenNull:
val := p.curTok.Literal
p.nextToken()
return &ast.NullLiteral{LiteralType: "Null", Value: val}, nil
case TokenDefault:
val := p.curTok.Literal
p.nextToken()
return &ast.DefaultLiteral{LiteralType: "Default", Value: val}, nil
case TokenMinus:
p.nextToken()
expr, err := p.parsePrimaryExpression()
if err != nil {
return nil, err
}
return &ast.UnaryExpression{UnaryExpressionType: "Negative", Expression: expr}, nil
case TokenPlus:
p.nextToken()
expr, err := p.parsePrimaryExpression()
if err != nil {
return nil, err
}
return &ast.UnaryExpression{UnaryExpressionType: "Positive", Expression: expr}, nil
case TokenIdent:
// Check if it's a global variable reference (starts with @@)
if strings.HasPrefix(p.curTok.Literal, "@@") {
name := p.curTok.Literal
p.nextToken()
return &ast.GlobalVariableExpression{Name: name}, nil
}
// Check if it's a variable reference (starts with @)
if strings.HasPrefix(p.curTok.Literal, "@") {
name := p.curTok.Literal
p.nextToken()
return &ast.VariableReference{Name: name}, nil
}
// Check for N-prefixed national string (N'...')
if strings.ToUpper(p.curTok.Literal) == "N" && p.peekTok.Type == TokenString {
p.nextToken() // consume N
return p.parseNationalStringLiteral()
}
return p.parseColumnReferenceOrFunctionCall()
case TokenNumber:
val := p.curTok.Literal
p.nextToken()
// Check if it's a decimal number
if strings.Contains(val, ".") {
return &ast.NumericLiteral{LiteralType: "Numeric", Value: val}, nil
}
return &ast.IntegerLiteral{LiteralType: "Integer", Value: val}, nil
case TokenBinary:
val := p.curTok.Literal
p.nextToken()
return &ast.BinaryLiteral{LiteralType: "Binary", Value: val, IsLargeObject: false}, nil
case TokenString:
return p.parseStringLiteral()
case TokenNationalString:
return p.parseNationalStringFromToken()
case TokenLBrace:
return p.parseOdbcLiteral()
case TokenLParen:
// Parenthesized expression or scalar subquery
p.nextToken()
// Check if it's a scalar subquery (starts with SELECT)
if p.curTok.Type == TokenSelect {
qe, err := p.parseQueryExpression()
if err != nil {
return nil, err
}
if p.curTok.Type != TokenRParen {
return nil, fmt.Errorf("expected ), got %s", p.curTok.Literal)
}
p.nextToken()
return &ast.ScalarSubquery{QueryExpression: qe}, nil
}
expr, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
if p.curTok.Type != TokenRParen {
return nil, fmt.Errorf("expected ), got %s", p.curTok.Literal)
}
p.nextToken()
return &ast.ParenthesisExpression{Expression: expr}, nil
case TokenCase:
return p.parseCaseExpression()
default:
return nil, fmt.Errorf("unexpected token in expression: %s", p.curTok.Literal)
}
}
func (p *Parser) parseCaseExpression() (ast.ScalarExpression, error) {
p.nextToken() // consume CASE
// Check if it's a searched CASE (CASE WHEN ...) or simple CASE (CASE expr WHEN ...)
if p.curTok.Type == TokenWhen {
// Searched CASE expression
return p.parseSearchedCaseExpression()
}
// Simple CASE expression
return p.parseSimpleCaseExpression()
}
func (p *Parser) parseSearchedCaseExpression() (*ast.SearchedCaseExpression, error) {
expr := &ast.SearchedCaseExpression{}
for p.curTok.Type == TokenWhen {
p.nextToken() // consume WHEN
when, err := p.parseBooleanExpression()
if err != nil {
return nil, err
}
if p.curTok.Type != TokenThen {
return nil, fmt.Errorf("expected THEN in CASE, got %s", p.curTok.Literal)
}
p.nextToken() // consume THEN
then, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
expr.WhenClauses = append(expr.WhenClauses, &ast.SearchedWhenClause{
WhenExpression: when,
ThenExpression: then,
})
}
// Optional ELSE
if p.curTok.Type == TokenElse {
p.nextToken() // consume ELSE
elseExpr, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
expr.ElseExpression = elseExpr
}
if p.curTok.Type != TokenEnd {
return nil, fmt.Errorf("expected END in CASE, got %s", p.curTok.Literal)
}
p.nextToken() // consume END
return expr, nil
}
func (p *Parser) parseSimpleCaseExpression() (*ast.SimpleCaseExpression, error) {
expr := &ast.SimpleCaseExpression{}
// Parse input expression
input, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
expr.InputExpression = input
for p.curTok.Type == TokenWhen {
p.nextToken() // consume WHEN
when, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
if p.curTok.Type != TokenThen {
return nil, fmt.Errorf("expected THEN in CASE, got %s", p.curTok.Literal)
}
p.nextToken() // consume THEN
then, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
expr.WhenClauses = append(expr.WhenClauses, &ast.SimpleWhenClause{
WhenExpression: when,
ThenExpression: then,
})
}
// Optional ELSE
if p.curTok.Type == TokenElse {
p.nextToken() // consume ELSE
elseExpr, err := p.parseScalarExpression()
if err != nil {
return nil, err
}
expr.ElseExpression = elseExpr
}
if p.curTok.Type != TokenEnd {
return nil, fmt.Errorf("expected END in CASE, got %s", p.curTok.Literal)
}
p.nextToken() // consume END
return expr, nil
}
func (p *Parser) parseOdbcLiteral() (*ast.OdbcLiteral, error) {
// Consume {
p.nextToken()
// Expect "guid" identifier
if p.curTok.Type != TokenIdent || strings.ToLower(p.curTok.Literal) != "guid" {
return nil, fmt.Errorf("expected guid in ODBC literal, got %s", p.curTok.Literal)
}
p.nextToken()
// Check for national string (either separate N token or combined N'...' token)
isNational := false
var raw string
if p.curTok.Type == TokenNationalString {
// Combined N'...' token from lexer
isNational = true
raw = p.curTok.Literal
// Strip the N prefix
if len(raw) >= 3 && (raw[0] == 'N' || raw[0] == 'n') && raw[1] == '\'' {
raw = raw[1:] // Remove the N, keep the rest including quotes
}
p.nextToken()
} else {
// Check for separate N token followed by string
if p.curTok.Type == TokenIdent && strings.ToUpper(p.curTok.Literal) == "N" {
isNational = true
p.nextToken()
}
// Expect string literal
if p.curTok.Type != TokenString {
return nil, fmt.Errorf("expected string in ODBC literal, got %s", p.curTok.Literal)
}
raw = p.curTok.Literal
p.nextToken()
}
// Remove surrounding quotes
value := raw
if len(raw) >= 2 && raw[0] == '\'' && raw[len(raw)-1] == '\'' {
value = raw[1 : len(raw)-1]
}
// Consume }
if p.curTok.Type != TokenRBrace {
return nil, fmt.Errorf("expected } in ODBC literal, got %s", p.curTok.Literal)
}
p.nextToken()
return &ast.OdbcLiteral{
LiteralType: "Odbc",
OdbcLiteralType: "Guid",
IsNational: isNational,
Value: value,
}, nil
}
func (p *Parser) parseStringLiteral() (*ast.StringLiteral, error) {
raw := p.curTok.Literal
p.nextToken()
// Remove surrounding quotes and handle escaped quotes
if len(raw) >= 2 && raw[0] == '\'' && raw[len(raw)-1] == '\'' {
inner := raw[1 : len(raw)-1]
// Replace escaped quotes
value := strings.ReplaceAll(inner, "''", "'")
return &ast.StringLiteral{
LiteralType: "String",
IsNational: false,
IsLargeObject: false,
Value: value,
}, nil
}
return &ast.StringLiteral{
LiteralType: "String",
IsNational: false,
IsLargeObject: false,
Value: raw,
}, nil
}
func (p *Parser) parseNationalStringLiteral() (*ast.StringLiteral, error) {
raw := p.curTok.Literal
p.nextToken()
// Remove surrounding quotes and handle escaped quotes
if len(raw) >= 2 && raw[0] == '\'' && raw[len(raw)-1] == '\'' {
inner := raw[1 : len(raw)-1]
// Replace escaped quotes
value := strings.ReplaceAll(inner, "''", "'")
return &ast.StringLiteral{
LiteralType: "String",
IsNational: true,
IsLargeObject: false,
Value: value,
}, nil
}
return &ast.StringLiteral{
LiteralType: "String",
IsNational: true,
IsLargeObject: false,
Value: raw,
}, nil
}
func (p *Parser) parseNationalStringFromToken() (*ast.StringLiteral, error) {
// Token is N'...' combined - strip the N prefix and quotes
raw := p.curTok.Literal
p.nextToken()
// Raw is like N'value' or n'value'
if len(raw) >= 3 && (raw[0] == 'N' || raw[0] == 'n') && raw[1] == '\'' && raw[len(raw)-1] == '\'' {
inner := raw[2 : len(raw)-1]
// Replace escaped quotes
value := strings.ReplaceAll(inner, "''", "'")
return &ast.StringLiteral{
LiteralType: "String",
IsNational: true,
IsLargeObject: false,
Value: value,
}, nil
}
return &ast.StringLiteral{
LiteralType: "String",
IsNational: true,
IsLargeObject: false,
Value: raw,
}, nil
}
func (p *Parser) parseColumnReferenceOrFunctionCall() (ast.ScalarExpression, error) {
var identifiers []*ast.Identifier
for {
if p.curTok.Type != TokenIdent {
break
}
quoteType := "NotQuoted"
literal := p.curTok.Literal
// Handle bracketed identifiers
if len(literal) >= 2 && literal[0] == '[' && literal[len(literal)-1] == ']' {
quoteType = "SquareBracket"
literal = literal[1 : len(literal)-1]
}
id := &ast.Identifier{
Value: literal,
QuoteType: quoteType,
}
identifiers = append(identifiers, id)
p.nextToken()
if p.curTok.Type != TokenDot {
break
}
p.nextToken() // consume dot
}
// If followed by ( it's a function call
if p.curTok.Type == TokenLParen {
return p.parseFunctionCallFromIdentifiers(identifiers)
}
return &ast.ColumnReferenceExpression{
ColumnType: "Regular",
MultiPartIdentifier: &ast.MultiPartIdentifier{
Count: len(identifiers),
Identifiers: identifiers,
},
}, nil
}
func (p *Parser) parseColumnReference() (*ast.ColumnReferenceExpression, error) {
expr, err := p.parseColumnReferenceOrFunctionCall()
if err != nil {
return nil, err
}
if colRef, ok := expr.(*ast.ColumnReferenceExpression); ok {
return colRef, nil
}
// If we got a function call, wrap it in a column reference (shouldn't happen in this context)
return nil, fmt.Errorf("expected column reference, got function call")
}
func (p *Parser) parseFunctionCallFromIdentifiers(identifiers []*ast.Identifier) (*ast.FunctionCall, error) {
fc := &ast.FunctionCall{
UniqueRowFilter: "NotSpecified",
WithArrayWrapper: false,
}