forked from ssoroka/sql-ast
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
1288 lines (1234 loc) · 35.4 KB
/
parser.go
File metadata and controls
1288 lines (1234 loc) · 35.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 sqlast
import (
"fmt"
"io"
"os"
"runtime/debug"
"strconv"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
// Parser represents a parser.
type Parser struct {
s *Scanner
itemBuf []Item
lastItem Item
}
func init() {
log.SetOutput(os.Stdout)
}
// NewParser returns a new instance of Parser.
func NewParser(r io.Reader) *Parser {
return &Parser{s: NewScanner(r)}
}
// scan returns the next token from the underlying scanner.
// If a token has been unscanned then read that instead.
func (p *Parser) scan() Item {
// If we have a token on the buffer, then return it.
if len(p.itemBuf) > 0 {
item := p.itemBuf[0]
p.itemBuf = p.itemBuf[1:]
return item
}
// Otherwise read the next token from the scanner.
item := p.s.Scan()
// Save it to the buffer in case we unscan later.
p.lastItem = item
return item
}
// unscan pushes the previously read token back onto the buffer.
func (p *Parser) unscan() {
p.itemBuf = append([]Item{p.lastItem}, p.itemBuf...)
}
// nextItem scans the next non-whitespace token.
func (p *Parser) nextItem() Item {
item := p.scan()
if item.Token == Whitespace {
item = p.scan()
}
return item
}
// detect if alias is found and whether it has AS before alias
func (p *Parser) DetectFieldAlias(result *SelectStatement, item Item) (bool, bool) {
var nextItem Item
var FoundAlias bool
detectAliasLoop:
for {
nextItem = p.nextItem()
if nextItem.Token != Whitespace {
break detectAliasLoop
}
}
switch nextItem.Token {
case Comma:
p.unscan()
return FoundAlias, false
case Identifier, As: // we found indication of alias
hasAs := false
if nextItem.Token == Identifier {
FoundAlias = true
hasAs = false
newAlias := SelectAlias{item.Val, nextItem.Val}
result.SelectAl = append(result.SelectAl, newAlias)
} else {
identifierLookup:
for {
ii := p.nextItem()
switch ii.Token {
case Whitespace:
continue
case Identifier:
FoundAlias = true
newAlias := SelectAlias{item.Val, ii.Val}
hasAs = true
result.SelectAl = append(result.SelectAl, newAlias)
break identifierLookup
default:
p.unscan()
break identifierLookup
}
}
}
return FoundAlias, hasAs
default:
p.unscan()
return FoundAlias, false
}
//return FoundAlias
}
// detect if alias is found and whether it has AS before alias
func (p *Parser) DetectTableAlias(result *SelectStatement, item Item) (bool, bool) {
var nextItem Item
detectAliasLoop:
for {
nextItem = p.nextItem()
if nextItem.Token != Whitespace {
break detectAliasLoop
}
}
switch nextItem.Token {
case Identifier, As: // we found indication of alias
if nextItem.Token == Identifier {
newAlias := TableAlias{item.Val, nextItem.Val}
result.TableAl = append(result.TableAl, newAlias)
return true, false
} else {
identifierLookup:
for {
ii := p.nextItem()
switch ii.Token {
case Whitespace:
continue
case Identifier:
newAlias := TableAlias{item.Val, ii.Val}
result.TableAl = append(result.TableAl, newAlias)
return true, true
//break identifierLookup
default:
p.unscan()
break identifierLookup
}
}
}
return false, false
default:
p.unscan()
return false, false
}
//return false
}
func (p *Parser) ParseCase(result *SelectStatement, alias string) error {
var newCase *CaseField
var newWhen *WhenCond
for {
item := p.nextItem()
switch item.Token {
case Whitespace:
continue
case End:
newCase.WhenCond = append(newCase.WhenCond, *newWhen)
newWhen = nil
//newCase.WhenCond = append(newCase.WhenCond, *newWhen)
newCase.Alias = alias
newComplexSelect := ComplexSelect{}
newComplexSelect.CaseStatement = newCase
if alias != "" {
newComplexSelect.Alias = alias
}
result.CaseFields = append(result.CaseFields, *newCase)
result.ComplexSelects = append(result.ComplexSelects, newComplexSelect)
return nil
case Identifier:
newCase.FieldIdentifier = item.Val
case Case:
if newCase != nil {
result.CaseFields = append(result.CaseFields, *newCase)
}
newCase = &CaseField{}
case When:
if newWhen != nil {
newCase.WhenCond = append(newCase.WhenCond, *newWhen)
}
newWhen = &WhenCond{}
e := p.ParseExpression(&(newWhen.WhenCond))
if e != nil {
return e
}
case Then, Else:
if newWhen == nil {
return errors.New("Then found without preceeding When <condition>")
}
var thenItem Item
thenItems := []Item{}
thenLookup:
for {
thenItem = p.nextItem()
switch thenItem.Token {
case Whitespace:
continue
case Else, When, End, From:
p.unscan()
break thenLookup
default:
thenItems = append(thenItems, thenItem)
}
}
if item.Token == Then {
if len(thenItems) == 1 {
le := LiteralExpression{thenItems[0].Token, thenItems[0].Val}
newWhen.ThenCond = le.String()
} else {
var expression Expression
e := parseSubExpression(&expression, thenItems)
if e != nil {
return e
}
newWhen.ThenCond = expression.String()
}
} else { // ELSE statement
if len(thenItems) == 1 {
le := LiteralExpression{thenItems[0].Token, thenItems[0].Val}
newCase.ElseCond = le.String()
} else {
var expression Expression
e := parseSubExpression(&expression, thenItems)
if e != nil {
return e
}
newCase.ElseCond = expression.String()
}
}
default:
return errors.New("Unknown Token " + item.String() + " Expected WHEN,ELSE, or THEN")
}
}
}
type SubParser struct {
items []Item
curIndex int
}
func (s *SubParser) nextItem() Item {
i := s.items[s.curIndex]
s.curIndex++
return i
}
func (s *SubParser) unScan() {
if s.curIndex > 0 {
s.curIndex--
}
}
// Parse parses the tokens provided by a scanner (lexer) into an AST
func (p *Parser) Parse(result *Statement) (errRet error) {
defer func() {
if r := recover(); r != nil {
fmt.Println("PANIC", r)
fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
errRet = errors.New("Invalid statement while parsing")
}
}()
statement := &SelectStatement{}
_ = "breakpoint"
parentCountSub := 0
isASubQuery := false
if item := p.nextItem(); item.Token == ParenOpen {
parentCountSub++
isASubQuery = true
} else {
p.unscan()
}
if item := p.nextItem(); item.Token != Select {
return fmt.Errorf("found %v, expected SELECT", item.Inspect())
}
for {
// Read a field.
item := p.nextItem()
//fmt.Println("item", item)
switch item.Token {
case ParenOpen:
if isASubQuery {
parentCountSub++
}
case ParenClose:
if isASubQuery {
parentCountSub--
if parentCountSub == 0 {
*result = Statement(statement)
return nil
}
}
case Identifier, Asterisk, Number:
statement.Fields = append(statement.Fields, item.Val)
newComplexSelect := ComplexSelect{}
newComplexSelect.FieldName = item.Val
//fmt.Println("FoundIdentifier", item.Val)
var detected, hasAs bool
if detected, hasAs = p.DetectFieldAlias(statement, item); detected {
newComplexSelect.Alias = statement.SelectAl[len(statement.SelectAl)-1].Alias
newComplexSelect.HasAs = hasAs
}
//test if there are dot
isDot := p.nextItem()
//fmt.Println(">>>", isDot.Token)
if isDot.Token == Multiply {
newComplexSelect.FieldName += "*"
} else {
p.unscan()
}
statement.ComplexSelects = append(statement.ComplexSelects, newComplexSelect)
case Multiply: // special case for now.
statement.Fields = append(statement.Fields, "*")
newComplexSelect := ComplexSelect{}
newComplexSelect.FieldName = "*"
statement.ComplexSelects = append(statement.ComplexSelects, newComplexSelect)
// this is parsing functions
case Count, Avg, Min, Max, Sum, Concat, RowNum, Nvl, Trim, From_unixtime, ToDate,
Year, Quarter, Month, Hour, Minute, LastDay, DateSub, Trunc, CurrentDate, Upper, Lower, Split, Substr, RegexReplace,
Lpad, DateDiff, Explode, Length, COALESCE, Cast, Rank, DenseRank:
p.unscan()
//fmt.Println(">>>>", item)
ag := Aggregate{}
e := p.ParseAggregate(&ag)
if e != nil {
return e
}
if item.Token == RowNum {
nextToken := p.nextItem()
if nextToken.Token == Over {
ag.Params = append(ag.Params, nextToken)
RowNumOverLoop:
for {
nextToken = p.nextItem()
switch nextToken.Token {
case ParenClose:
ag.Params = append(ag.Params, nextToken)
break RowNumOverLoop
default:
ag.Params = append(ag.Params, nextToken)
}
}
} else {
p.unscan()
}
}
// pp := p.nextItem()
// fmt.Println("PP", pp.String())
//fmt.Println(len(ag.Params), ag.Params)
statement.Aggregates = append(statement.Aggregates, ag)
statement.Fields = append(statement.Fields, ag.String())
pItem := Item{item.Token, ag.String()}
newComplexSelect := ComplexSelect{}
newComplexSelect.AggregateField = &ag
var detected, hasAs bool
if detected, hasAs = p.DetectFieldAlias(statement, pItem); detected {
newComplexSelect.Alias = statement.SelectAl[len(statement.SelectAl)-1].Alias
newComplexSelect.HasAs = hasAs
}
statement.ComplexSelects = append(statement.ComplexSelects, newComplexSelect)
case QuotedString, SinglQuotedString:
// check the following non Whitespace token
statement.Fields = append(statement.Fields, strconv.QuoteToASCII(item.Val))
var nextItem Item
CaseWhenLoop1:
for {
nextItem = p.nextItem()
//fmt.Println("NextItem", nextItem)
switch nextItem.Token {
case Whitespace:
continue
case Equals: //we found case...when...then...end
e := p.ParseCase(statement, item.Val)
//fmt.Println("Parse Case Done")
if e != nil {
return e
}
break CaseWhenLoop1
case Case:
//fmt.Println(statement)
return errors.New("Need = before Case in select field")
case As, Identifier: //WeFoundAlias
//fmt.Println("Alias Detected")
p.unscan()
newComplexSelect := ComplexSelect{}
le := LiteralExpression{item.Token, item.Val}
newComplexSelect.StaticValue = le.String()
var detected, hasAs bool
if detected, hasAs = p.DetectFieldAlias(statement, item); detected {
//fmt.Println("Alias Found")
newComplexSelect.Alias = statement.SelectAl[len(statement.SelectAl)-1].Alias
newComplexSelect.HasAs = hasAs
}
statement.ComplexSelects = append(statement.ComplexSelects, newComplexSelect)
break CaseWhenLoop1
default:
newComplexSelect := ComplexSelect{}
le := LiteralExpression{item.Token, item.Val}
newComplexSelect.StaticValue = le.String()
statement.ComplexSelects = append(statement.ComplexSelects, newComplexSelect)
p.unscan()
break CaseWhenLoop1
}
}
case Case:
p.unscan()
e := p.ParseCase(statement, "")
if e != nil {
return e
}
//fmt.Println("Parse Case Done")
detectCaseAlias:
for {
nitem := p.nextItem()
switch nitem.Token {
case Whitespace:
case Identifier, As:
if nitem.Token == Identifier {
statement.CaseFields[len(statement.CaseFields)-1].Alias = nitem.Val
statement.ComplexSelects[len(statement.ComplexSelects)-1].Alias = nitem.Val
statement.ComplexSelects[len(statement.ComplexSelects)-1].HasAs = false
} else {
detectAlias:
for {
n2 := p.nextItem()
switch n2.Token {
case Identifier:
statement.CaseFields[len(statement.CaseFields)-1].Alias = n2.Val
statement.ComplexSelects[len(statement.ComplexSelects)-1].Alias = n2.Val
statement.ComplexSelects[len(statement.ComplexSelects)-1].HasAs = true
break detectAlias
default:
p.unscan()
return errors.New("Syntax Error, Expecting Identifier after AS, got " + n2.String() + " instead")
}
}
}
statement.Fields = append(statement.Fields, statement.CaseFields[len(statement.CaseFields)-1].Alias)
default:
p.unscan()
break detectCaseAlias
}
}
default:
return fmt.Errorf("found %v, expected field", item.Inspect())
}
// If the next token is not a comma then break the loop.
if item := p.nextItem(); item.Token != Comma {
//fmt.Println(item)
p.unscan()
break
}
}
// Next we should see the "FROM" keyword.
if item := p.nextItem(); item.Token != From {
return fmt.Errorf("found %v, expected FROM", item.Inspect())
}
item := p.nextItem()
if item.Token == Identifier {
statement.TableName = item.Val
pTable := Item{}
pTable.Token = Identifier
pTable.Val = item.Val
complexTable := ComplexTable{}
var detected, hasAs bool
if detected, hasAs = p.DetectTableAlias(statement, pTable); detected {
complexTable.Alias = statement.TableAl[len(statement.TableAl)-1].Alias
complexTable.UseAs = hasAs
}
complexTable.TableName = item.Val
statement.ComplexFrom = complexTable
} else if item.Token == ParenOpen { //complexTable Found
p.unscan()
var newSubStatement Statement
e := p.Parse(&newSubStatement)
if e != nil {
return e
}
pTable := Item{}
pTable.Token = Identifier
complexTable := ComplexTable{}
var detected, hasAs bool
if detected, hasAs = p.DetectTableAlias(statement, pTable); detected {
complexTable.Alias = statement.TableAl[len(statement.TableAl)-1].Alias
complexTable.UseAs = hasAs
}
complexTable.SubSelect = (newSubStatement.(*SelectStatement))
statement.ComplexFrom = complexTable
} else {
return fmt.Errorf("found %v, expected table name", item.Inspect())
}
if item := p.nextItem(); item.Token == ParenClose {
if isASubQuery {
parentCountSub--
if parentCountSub == 0 {
*result = Statement(statement)
//fmt.Println(statement)
//fmt.Println("Return after Selecting Table")
return nil
}
}
} else {
p.unscan()
}
if item := p.nextItem(); item.Token == Join || item.Token == LeftJoin || item.Token == RightJoin || item.Token == InnerJoin ||
item.Token == RightOuterJoin || item.Token == LeftOuterJoin || item.Token == Comma || item.Token == FullOuterJoin || item.Token == FullInnerJoin {
//fmt.Println("Join Found")
p.unscan()
ll := 0
JoinLoop:
for {
ll++
if ll == 30 {
break
}
item := p.nextItem()
switch item.Token {
case Where, EOF:
//fmt.Println("Found", item.Inspect())
p.unscan()
break JoinLoop
case Join, LeftJoin, RightJoin, InnerJoin, Comma, RightOuterJoin, LeftOuterJoin, FullInnerJoin, FullOuterJoin:
newJoinStatement := &JoinTables{}
newJoinStatement.JoinType = item.Val
e := p.parseJoin(newJoinStatement, statement)
if e != nil {
log.Debug(e)
return e
}
if newJoinStatement.TableName != "" || newJoinStatement.SubSelect != nil {
statement.Joins = append(statement.Joins, *newJoinStatement)
}
}
}
} else {
p.unscan()
}
item2 := p.nextItem()
if item2.Token == ParenClose {
if isASubQuery {
parentCountSub--
if parentCountSub == 0 {
*result = Statement(statement)
return nil
}
}
} else if item2.Token == EOF {
p.unscan()
*result = Statement(statement)
return nil
} else {
//fmt.Println(item2.Inspect())
p.unscan()
}
var err error
if err = p.parseConditional(&statement.Where); err != nil {
return err
}
if item := p.nextItem(); item.Token == ParenClose {
if isASubQuery {
parentCountSub--
if parentCountSub == 0 {
*result = Statement(statement)
return nil
}
}
} else {
p.unscan()
}
nextOption:
for {
item := p.nextItem()
//fmt.Println(item)
switch item.Token {
case Whitespace:
continue
case GroupBy:
p.parseGroupBy(&(statement.GroupBy))
case Having:
p.ParseExpression(&statement.Having)
case OrderBy:
p.parseOrderBy(&statement.OrderBy)
case ParenClose:
if isASubQuery {
parentCountSub--
if parentCountSub == 0 {
*result = Statement(statement)
return nil
}
}
case Union:
//fmt.Println("FoundUNION")
union := UnionStatement{}
nextItem := p.nextItem()
if nextItem.Token == All {
union.Union = "all"
} else {
p.unscan()
}
var unionStatement Statement
e := p.Parse(&unionStatement)
if e != nil {
fmt.Println(e.Error())
return e
}
union.Statement = *(unionStatement.(*SelectStatement))
//fmt.Println(union.Statement.String())
statement.Unions = append(statement.Unions, union)
case EOF:
break nextOption
}
}
*result = Statement(statement)
return nil
}
func (p *Parser) parseOrderBy(result *[]SortField) error {
var curField SortField
//fmt.Println("Parse Orderby")
for {
item := p.nextItem()
//fmt.Println(item)
switch item.Token {
case Whitespace:
continue
case Limit, EOF:
return nil
case Identifier:
if curField.Field != "" {
return errors.New("Sort order not found after " + curField.Field)
}
curField.Field = item.Val
case Asc, Desc:
if curField.Sort != "" {
return errors.New("Sort order duplicateFound, expected comma")
}
curField.Sort = item.Val
*result = append(*result, curField)
case Comma:
curField = SortField{}
}
}
}
func (p *Parser) parseGroupBy(result *[]string) error {
for {
v := p.nextItem()
switch v.Token {
case Whitespace:
continue
case Identifier:
*result = append(*result, v.Val)
case OrderBy, Having, EOF:
p.unscan()
return nil
}
}
}
// parse aggregate AVG,SUM,MAX,MIN,COUNT
func (p *Parser) ParseAggregate(result *Aggregate) error {
// retrieve aggregate function
aggrFunc := p.nextItem()
result.AggregateType = aggrFunc.Val
parentOpenFound := false
parentOpenNum := 0
//parentCloseFound := false
AggrLoop:
for {
item := p.nextItem()
switch item.Token {
case Whitespace:
continue
case ParenOpen:
//fmt.Println("Found ParentOpen")
parentOpenFound = true
parentOpenNum++
result.Params = append(result.Params, item)
case ParenClose:
// fmt.Println("Found ParentClose")
if !parentOpenFound {
return errors.New("Closing parenthesis found befor open parenthesis")
}
parentOpenNum--
// parentCloseFound = true
if parentOpenNum == 0 {
result.Params = append(result.Params, item)
break AggrLoop
}
result.Params = append(result.Params, item)
case Identifier, Multiply, Asterisk:
if !parentOpenFound {
return errors.New("Identifier found befor open parenthesis")
}
if (item.Token == Multiply || item.Token == Asterisk) && aggrFunc.Token != Count {
return errors.New("Identifier * Can only be used on Count")
}
result.FieldName = item.Val
result.Params = append(result.Params, item)
case Comma:
result.Params = append(result.Params, item)
default:
result.Params = append(result.Params, item)
}
}
item := p.nextItem()
if item.Token == Over {
//fmt.Println("Found OVER", result.String())
newOverStatement := OverStatement{}
e := p.parseOver(&newOverStatement)
if e != nil {
fmt.Println("Error Found on Processing OVER", e.Error())
return e
}
//tt := p.nextItem()
//fmt.Println("TT", tt.String())
//p.unscan()
result.Over = newOverStatement
} else {
p.unscan()
}
if parentOpenNum != 0 {
return errors.New("NO matching bracket")
}
// parOpen := p.nextItem()
// if parOpen.Token != ParenOpen {
// return errors.New(fmt.Sprintf("Expected '(' but found %s instead after %s", parOpen.Val, aggrFunc.Val))
// }
// result.AggregateType = aggrFunc.Val
// fieldVal := p.nextItem()
// if fieldVal.Token != Identifier && fieldVal.Token != Multiply { // we compare Multiply to allow count(*)
// return errors.New(fmt.Sprintf("Expected Field Name but found %s instead after %s", parOpen.Val, aggrFunc.Val))
// }
// if fieldVal.Token != Multiply && aggrFunc.Token != Count {
// return errors.New(fmt.Sprintf("Only Count allowed to use * as parameter"))
// }
// result.FieldName = fieldVal.Val
// parenClose := p.nextItem()
// fmt.Println("parenClose", parenClose)
// if parOpen.Token != ParenOpen {
// return errors.New(fmt.Sprintf("Expected ')' but found %s instead after %s", parenClose.Val, fieldVal.Val))
// }
return nil
}
func (p *Parser) parseOver(result *OverStatement) error {
parentCount := 0
parentOpenFound := false
mainLoop:
for true {
item := p.nextItem()
// fmt.Println(item.String())
if item.Token == EOF {
return errors.New("Unexpected End of line")
}
switch item.Token {
case ParenOpen:
parentOpenFound = true
parentCount++
case ParenClose:
if !parentOpenFound {
return errors.New("Closing parenthesis found befor open parenthesis")
}
parentCount--
// fmt.Println("Found ParentCLose", parentCount)
if parentCount == 0 {
return nil
}
case PartitionBy:
for true {
KK := p.nextItem()
//fmt.Println("Partition By", KK)
switch KK.Token {
case Identifier:
result.PartitionBy = append(result.PartitionBy, KK.Val)
case Comma:
continue
default:
p.unscan()
//break
continue mainLoop
}
}
case OrderBy:
for true {
KK := p.nextItem()
//fmt.Println("Order By", KK)
switch KK.Token {
case Identifier:
result.OrderBy = append(result.OrderBy, KK.Val)
case Comma:
continue
default:
//fmt.Println(KK)
p.unscan()
continue mainLoop
}
}
}
}
return nil
}
// parseJoin detects the "JOIN" clause and processes it, if any.
func (p *Parser) parseJoin(result *JoinTables, statement *SelectStatement) error {
// retrieve table name
var e error
tableName := p.nextItem()
if tableName.Token == Identifier {
pTable := Item{}
pTable.Token = Identifier
pTable.Val = tableName.Val
var detected, hasAs bool
if detected, hasAs = p.DetectTableAlias(statement, pTable); detected {
result.Alias = statement.TableAl[len(statement.TableAl)-1].Alias
result.HasAs = hasAs
}
log.Debug(tableName.Val)
result.TableName = tableName.Val
if result.JoinType == "," {
return nil
}
// retrieve on field
onCond := p.nextItem()
// fmt.Println("TableName", result.TableName, onCond.Val)
hasOn := true
if onCond.Token != On {
fmt.Errorf("Expected on, but found %s instead", onCond)
p.unscan()
hasOn = false
//return nil//errors.New(fmt.Sprintf("found %v, expected field", onCond.Inspect())) //fmt.Errorf("found %v, expected field", item.Inspect())
} else {
p.unscan()
}
//fmt.Println("Parsing Expression")
// ok, we have a where statement.
if hasOn {
adad := &(result.OnCondition)
e = p.ParseExpression(adad)
}
} else if tableName.Token == ParenOpen {
// fmt.Println("Complex Join Found")
p.unscan()
var subStatement Statement
e = p.Parse(&subStatement)
if e != nil {
return e
}
pTable := Item{}
pTable.Token = Identifier
pTable.Val = tableName.Val
var detected, hasAs bool
if detected, hasAs = p.DetectTableAlias(statement, pTable); detected {
result.Alias = statement.TableAl[len(statement.TableAl)-1].Alias
result.HasAs = hasAs
}
result.SubSelect = subStatement.(*SelectStatement)
if result.JoinType == "," {
return nil
}
adad := &(result.OnCondition)
e = p.ParseExpression(adad)
} else {
fmt.Errorf("Expected table name, but found %s instead", tableName.Inspect())
p.unscan()
return errors.New(fmt.Sprintf("found %v, expected field", tableName.Inspect())) //fmt.Errorf("found %v, expected field", item.Inspect())
}
return e
}
// parseConditional detects the "where" or "on" clause and processes it, if any.
func (p *Parser) parseConditional(result *Expression) error {
if item := p.nextItem(); item.Token != Where && item.Token != On {
//fmt.Println("Where or On not found", item)
p.unscan()
return nil
}
// ok, we have a where statement.
return p.ParseExpression(result)
}
func (p *Parser) ParseExpression(result *Expression) error {
log.Debug("Parsing Expression")
items := []Item{}
done := false
// depth := 0
parentCount := 0 //parenthesis count
for !done {
// see if we're done and we hit a border token.
item := p.scan()
//fmt.Println("item", item)
switch item.Token {
// case ParenClose
// case ParenOpen:
// case Select:
// case From:
// case Where:
case Illegal:
if len(items) > 0 {
return errors.New("Error, unexpected token " + item.Inspect() + " after " + items[len(items)-1].Inspect())
} else {
return errors.New("Error, unexpected token " + item.Inspect() + " after WHERE")
}
case GroupBy, Having, OrderBy, Limit, ForUpdate, EOF, Where, Join, LeftJoin, RightJoin, InnerJoin, Then,
LeftOuterJoin, RightOuterJoin, FullInnerJoin, FullOuterJoin, Union:
p.unscan()
done = true
break
case On:
continue
case Whitespace:
case ParenOpen:
parentCount++
case ParenClose:
parentCount--
if parentCount < 0 {
p.unscan()
done = true
break
}
default:
//fmt.Println("Parser Warning: Unhandled token", item.Inspect())
}
if item.Token != Where && item.Token != On && item.Token != Join &&
item.Token != LeftJoin && item.Token != RightJoin && item.Token != RightOuterJoin && item.Token != LeftOuterJoin && item.Token != Having &&
item.Token != InnerJoin && item.Token != FullInnerJoin && item.Token != FullOuterJoin && item.Token != OrderBy && item.Token != GroupBy && item.Token != Then && item.Token != Union && !(item.Token == ParenClose && parentCount < 0) {
items = append(items, item)
}
}
// fmt.Println(items)
//todo: write expression
if len(items) > 0 {
//fmt.Println(items)
if err := parseSubExpression(result, items); err != nil {
return errors.Wrap(err, "Error parsing expression: "+itemsString(items))
}
}
return nil
// switch item.Token {
// case LeftParen:
// p.State.Push(LeftParen)
// p.parseExpression()
// case Identifier, Number, Date, Time, Boolean, QuotedString:
// return item, nil
// }
// literal
// | identifier
// | function_call
// | simple_expr COLLATE collation_name
// | param_marker
// | variable
// | simple_expr || simple_expr
// | + simple_expr
// | - simple_expr
// | ~ simple_expr
// | ! simple_expr
// | BINARY simple_expr
// | (expr [, expr] ...)
// | ROW (expr, expr [, expr] ...)
// | (subquery)
// | EXISTS (subquery)
// | {identifier expr}
// | match_expr
// | case_expr
// | interval_expr
}
func ContainsBetween(items []Item) (bool, int) {
for idx, val := range items {
if val.Token == Between || val.Token == NotBetween {
return true, idx
}
}
return false, -1
}
// parseSubExpression is called when we know we have an expression.
func parseSubExpression(result *Expression, items []Item) error {