/
query_parser.go
1499 lines (1362 loc) · 40.4 KB
/
query_parser.go
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
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package queryparser
import (
"fmt"
"math/big"
"strconv"
"strings"
"text/scanner"
"time"
"unicode/utf8"
ds "v.io/v23/query/engine/datasource"
"v.io/v23/query/pattern"
"v.io/v23/query/syncql"
"v.io/v23/vdl"
)
type TokenType int
const (
unexpectedFormat = "[%v]unexpected: %v"
unexpectedEndOfStatementFormat = "[%v]unexpected end of statement"
expectedFormat = "[%v]expected '%v'"
expectedIdentifierFormat = "[%v]expected identifier, found %v"
couldNotConvertFormat = "[%v]could not convert %v to %v"
expectedOperandFormat = "[%v]expected operand, found %v"
expectedOperatorFormat = "[%v]expected operator, found %v"
tooManyParamValuesFormat = "[%v]too many parameter values specified"
invalidIndexFieldFormat = "[%v]invalid index field %v returned by table %v"
)
const (
TokCHAR TokenType = 1 + iota
TokCOMMA
TokEOF
TokEQUAL
TokFLOAT
TokIDENT
TokINT
TokLEFTANGLEBRACKET
TokLEFTBRACKET
TokLEFTPAREN
TokMINUS
TokParameter // allowed only in prepared statements
TokPERIOD
TokRIGHTANGLEBRACKET
TokRIGHTBRACKET
TokRIGHTPAREN
TokSTRING
TokERROR
)
const (
MaxStatementLen = 10000
)
type Token struct {
Tok TokenType
Value string
Off int64
}
type Node struct {
Off int64
}
type Statement interface {
Offset() int64
String() string
CopyAndSubstitute(db ds.Database, paramValues []*vdl.Value) (Statement, error)
}
type Segment struct {
Value string
Keys []*Operand // Used as key(s) or index(es) to dereference map/set/array/list.
Node
}
type Field struct {
Segments []Segment
Node
}
type BinaryOperatorType int
const (
And BinaryOperatorType = 1 + iota
Equal
GreaterThan
GreaterThanOrEqual
Is
IsNot
LessThan
LessThanOrEqual
Like
NotEqual
NotLike
Or
)
type BinaryOperator struct {
Type BinaryOperatorType
Node
}
type OperandType int
const (
TypBigInt OperandType = 1 + iota // Only as a result of Resolve/Coerce Operand
TypBigRat // Only as a result of Resolve/Coerce Operand
TypBool
TypExpr
TypField
TypFloat
TypFunction
TypInt
TypNil
TypParameter
TypStr
TypTime
TypObject // Only as the result of a ResolveOperand
TypUint // Only as the result of a ResolveOperand
)
type Operand struct {
Type OperandType
BigInt *big.Int
BigRat *big.Rat
Bool bool
Column *Field
Float float64
Function *Function
Int int64
Str string
Time time.Time
Prefix string // Computed by checker for Like expressions
Pattern *pattern.Pattern // Computed by checker for Like expressions
Uint uint64
Expr *Expression
Object *vdl.Value
Node
}
type Function struct {
Name string
Args []*Operand
ArgTypes []OperandType // Filled in by checker.
RetType OperandType // Filled in by checker.
Computed bool // Checker sets to true and sets RetValue if function takes no args
RetValue *Operand
Node
}
type Expression struct {
Operand1 *Operand
Operator *BinaryOperator
Operand2 *Operand
Node
}
type SelectorType int
const (
TypSelField SelectorType = 1 + iota
TypSelFunc
)
// Selector: entries in the select clause.
// Entries can be functions for fields.
// The AS name, if present, will ONLY be used in the
// returned column header.
type Selector struct {
Type SelectorType
Field *Field
Function *Function
As *AsClause // If not nil, used in returned column header.
Node
}
type AsClause struct {
AltName Name
Node
}
type Name struct {
Value string
Node
}
type SelectClause struct {
Selectors []Selector
Node
}
type FromClause struct {
Table TableEntry
Node
}
type TableEntry struct {
Name string
DBTable ds.Table // Checker gets table from db and sets this.
Node
}
type WhereClause struct {
Expr *Expression
Node
}
type CharValue struct {
Value rune
Node
}
type Int64Value struct {
Value int64
Node
}
type EscapeClause struct {
EscapeChar *CharValue
Node
}
type LimitClause struct {
Limit *Int64Value
Node
}
type ResultsOffsetClause struct {
ResultsOffset *Int64Value
Node
}
type SelectStatement struct {
Select *SelectClause
From *FromClause
Where *WhereClause
Escape *EscapeClause
Limit *LimitClause
ResultsOffset *ResultsOffsetClause
Node
}
type DeleteStatement struct {
From *FromClause
Where *WhereClause
Escape *EscapeClause
Limit *LimitClause
Node
}
func scanToken(s *scanner.Scanner) *Token { //nolint:gocyclo
// TODO(jkline): Replace golang text/scanner.
var token Token
tok := s.Scan()
token.Value = s.TokenText()
token.Off = int64(s.Position.Offset)
if s.ErrorCount > 0 {
token.Tok = TokERROR
return &token
}
switch tok {
case '.':
token.Tok = TokPERIOD
case ',':
token.Tok = TokCOMMA
case '-':
token.Tok = TokMINUS
case '(':
token.Tok = TokLEFTPAREN
case ')':
token.Tok = TokRIGHTPAREN
case '=':
token.Tok = TokEQUAL
case '<':
token.Tok = TokLEFTANGLEBRACKET
case '>':
token.Tok = TokRIGHTANGLEBRACKET
case '[':
token.Tok = TokLEFTBRACKET
case ']':
token.Tok = TokRIGHTBRACKET
case '?':
token.Tok = TokParameter
case scanner.EOF:
token.Tok = TokEOF
case scanner.Ident:
token.Tok = TokIDENT
case scanner.Int:
token.Tok = TokINT
case scanner.Float:
token.Tok = TokFLOAT
case scanner.Char:
token.Tok = TokCHAR
token.Value = token.Value[1 : len(token.Value)-1]
case scanner.String:
token.Tok = TokSTRING
token.Value = token.Value[1 : len(token.Value)-1]
}
return &token
}
// Text/scanner reports errors to stderr that are not errors in the query language.
// For example, to get the value where the key is "\",
// One would write the string:
// "select v where k = \"\\\""
// This will result in the scanner spewing "literal not terminated" to stderr if we don't
// set the Error field in Scanner. As such, Error is set to the following function which
// eats errors. In the longer term, there is still a TODO to replace text/scanner with
// our own scanner.
func scannerError(s *scanner.Scanner, msg string) {
// Do nothing.
}
// Parse a statement. Return it or an error.
func Parse(db ds.Database, src string) (*Statement, error) {
if len(src) > MaxStatementLen {
return nil, syncql.ErrorfMaxStatementLenExceeded(db.GetContext(), "[%v]maximum length of statements is %v; found %v", int64(0), MaxStatementLen, int64(len(src)))
}
r := strings.NewReader(src)
var s scanner.Scanner
s.Init(r)
s.Error = scannerError
token := scanToken(&s) // eat the select
if token.Tok == TokEOF {
return nil, syncql.ErrorfNoStatementFound(db.GetContext(), "[%v]no statement found", token.Off)
}
if token.Tok != TokIDENT {
return nil, syncql.ErrorfExpectedIdentifier(db.GetContext(), expectedIdentifierFormat, token.Off, token.Value)
}
switch strings.ToLower(token.Value) {
case "select":
var st Statement
var err error
st, _, err = selectStatement(db, &s, token)
return &st, err
case "delete":
var st Statement
var err error
st, _, err = deleteStatement(db, &s, token)
return &st, err
default:
return nil, syncql.ErrorfUnknownIdentifier(db.GetContext(), "[%v]unknown identifier: %v", token.Off, token.Value)
}
}
// Parse select.
func selectStatement(db ds.Database, s *scanner.Scanner, token *Token) (Statement, *Token, error) {
var st SelectStatement
st.Off = token.Off
// parse SelectClause
var err error
st.Select, token, err = parseSelectClause(db, s, token)
if err != nil {
return nil, nil, err
}
st.From, token, err = parseFromClause(db, s, token)
if err != nil {
return nil, nil, err
}
st.Where, token, err = parseWhereClause(db, s, token)
if err != nil {
return nil, nil, err
}
st.Escape, st.Limit, st.ResultsOffset, token, err = parseEscapeLimitResultsOffsetClauses(db, s, token)
if err != nil {
return nil, nil, err
}
// There can be nothing remaining for the current statement
if token.Tok != TokEOF {
return nil, nil, syncql.ErrorfUnexpected(db.GetContext(), unexpectedFormat, token.Off, token.Value)
}
return st, token, nil
}
// Parse delete.
func deleteStatement(db ds.Database, s *scanner.Scanner, token *Token) (Statement, *Token, error) {
var st DeleteStatement
st.Off = token.Off
token = scanToken(s) // eat the delete
if token.Tok == TokEOF {
return nil, nil, syncql.ErrorfUnexpectedEndOfStatement(db.GetContext(), unexpectedEndOfStatementFormat, token.Off)
}
// parse FromClause
var err error
st.From, token, err = parseFromClause(db, s, token)
if err != nil {
return nil, nil, err
}
// parse WhereClause
st.Where, token, err = parseWhereClause(db, s, token)
if err != nil {
return nil, nil, err
}
st.Escape, st.Limit, token, err = parseEscapeLimitClauses(db, s, token)
if err != nil {
return nil, nil, err
}
// There can be nothing remaining for the current statement
if token.Tok != TokEOF {
return nil, nil, syncql.ErrorfUnexpected(db.GetContext(), unexpectedFormat, token.Off, token.Value)
}
return st, token, nil
}
// Parse the select clause (fields). Return *SelectClause, next token (or error).
func parseSelectClause(db ds.Database, s *scanner.Scanner, token *Token) (*SelectClause, *Token, error) {
// must be at least one selector or it is an error
// field seclectors may be in dot notation
// selectors are separated by commas
var selectClause SelectClause
selectClause.Off = token.Off
token = scanToken(s) // eat the select
if token.Tok == TokEOF {
return nil, nil, syncql.ErrorfUnexpectedEndOfStatement(db.GetContext(), unexpectedEndOfStatementFormat, token.Off)
}
var err error
// scan first selector
if token, err = parseSelector(db, s, &selectClause, token); err != nil {
return nil, nil, err
}
// More selectors?
for token.Tok == TokCOMMA {
token = scanToken(s)
if token, err = parseSelector(db, s, &selectClause, token); err != nil {
return nil, nil, err
}
}
return &selectClause, token, nil
}
// Parse a selector. Return next token (or error).
func parseSelector(db ds.Database, s *scanner.Scanner, selectClause *SelectClause, token *Token) (*Token, error) {
if token.Tok != TokIDENT {
return nil, syncql.ErrorfExpectedIdentifier(db.GetContext(), expectedIdentifierFormat, token.Off, token.Value)
}
var selector Selector
selector.Off = token.Off
selector.Type = TypSelField
var field Field
selector.Field = &field
selector.Field.Off = token.Off
selector.Field = &field
var segment *Segment
var err error
if segment, token, err = parseSegment(db, s, token); err != nil {
return nil, err
}
selector.Field.Segments = append(selector.Field.Segments, *segment)
// It might be a function.
if token.Tok == TokLEFTPAREN {
// Segments with a key(s) specified cannot be function calls.
if len(segment.Keys) != 0 {
return nil, syncql.ErrorfUnexpected(db.GetContext(), unexpectedFormat, token.Off, token.Value)
}
// switch selector to a function
selector.Type = TypSelFunc
var err error
if selector.Function, token, err = parseFunction(db, s, segment.Value, segment.Off, token); err != nil {
return nil, err
}
selector.Field = nil
} else {
for token.Tok != TokEOF && token.Tok == TokPERIOD {
token = scanToken(s)
if token.Tok != TokIDENT {
return nil, syncql.ErrorfExpectedIdentifier(db.GetContext(), expectedIdentifierFormat, token.Off, token.Value)
}
if segment, token, err = parseSegment(db, s, token); err != nil {
return nil, err
}
selector.Field.Segments = append(selector.Field.Segments, *segment)
}
}
// Check for AS
if token.Tok == TokIDENT && strings.ToLower(token.Value) == "as" {
var asClause AsClause
asClause.Off = token.Off
token = scanToken(s)
if token.Tok != TokIDENT {
return nil, syncql.ErrorfExpectedIdentifier(db.GetContext(), expectedIdentifierFormat, token.Off, token.Value)
}
asClause.AltName.Value = token.Value
asClause.AltName.Off = token.Off
selector.As = &asClause
token = scanToken(s)
}
selectClause.Selectors = append(selectClause.Selectors, selector)
return token, nil
}
// Parse a segment. Return the segment and the next token (or error).
// Check for a key (i.e., [<key>] following the segment).
func parseSegment(db ds.Database, s *scanner.Scanner, token *Token) (*Segment, *Token, error) {
var segment Segment
segment.Value = token.Value
segment.Off = token.Off
token = scanToken(s)
for token.Tok == TokLEFTBRACKET {
// A key to the segment is specified.
token = scanToken(s)
var key *Operand
var err error
key, token, err = parseOperand(db, s, token)
if err != nil {
return nil, nil, err
}
segment.Keys = append(segment.Keys, key)
if token.Tok != TokRIGHTBRACKET {
return nil, nil, syncql.ErrorfExpected(db.GetContext(), expectedFormat, token.Off, "]")
}
token = scanToken(s)
}
return &segment, token, nil
}
// Parse the from clause, Return FromClause and next Token or error.
func parseFromClause(db ds.Database, s *scanner.Scanner, token *Token) (*FromClause, *Token, error) {
if strings.ToLower(token.Value) != "from" {
return nil, nil, syncql.ErrorfExpectedFrom(db.GetContext(), "[%v]expected 'from', found %v", token.Off, token.Value)
}
var fromClause FromClause
fromClause.Off = token.Off
token = scanToken(s) // eat from
// must be a table specified
if token.Tok == TokEOF {
return nil, nil, syncql.ErrorfUnexpectedEndOfStatement(db.GetContext(), unexpectedEndOfStatementFormat, token.Off)
}
if token.Tok != TokIDENT {
return nil, nil, syncql.ErrorfExpectedIdentifier(db.GetContext(), expectedIdentifierFormat, token.Off, token.Value)
}
fromClause.Table.Off = token.Off
fromClause.Table.Name = token.Value
token = scanToken(s)
return &fromClause, token, nil
}
// Parse the where clause (if any). Return WhereClause (could be nil) and and next Token or error.
func parseWhereClause(db ds.Database, s *scanner.Scanner, token *Token) (*WhereClause, *Token, error) {
// parse Optional where clause
if token.Tok != TokEOF {
if strings.ToLower(token.Value) != "where" {
return nil, token, nil
}
var where WhereClause
where.Off = token.Off
token = scanToken(s)
// parse expression
var err error
where.Expr, token, err = parseExpression(db, s, token)
if err != nil {
return nil, nil, err
}
return &where, token, nil
}
return nil, token, nil
}
// Parse a parenthesized expression. Return expression and next token (or error)
func parseParenthesizedExpression(db ds.Database, s *scanner.Scanner, _ *Token) (*Expression, *Token, error) {
// Only called when token == TokLEFTPAREN
token := scanToken(s) // eat '('
var expr *Expression
var err error
expr, token, err = parseExpression(db, s, token)
if err != nil {
return nil, nil, err
}
// Expect right paren
if token.Tok == TokEOF {
return nil, nil, syncql.ErrorfUnexpectedEndOfStatement(db.GetContext(), unexpectedEndOfStatementFormat, token.Off)
}
if token.Tok != TokRIGHTPAREN {
return nil, nil, syncql.ErrorfExpected(db.GetContext(), expectedFormat, token.Off, ")")
}
token = scanToken(s) // eat ')'
return expr, token, nil
}
// Parse an expression. Return expression and next token (or error)
func parseExpression(db ds.Database, s *scanner.Scanner, token *Token) (*Expression, *Token, error) {
if token.Tok == TokEOF {
return nil, nil, syncql.ErrorfUnexpectedEndOfStatement(db.GetContext(), unexpectedEndOfStatementFormat, token.Off)
}
var err error
var expr *Expression
if token.Tok == TokLEFTPAREN {
expr, token, err = parseParenthesizedExpression(db, s, token)
} else {
// We expect a like/equal expression
expr, token, err = parseLikeEqualExpression(db, s, token)
}
if err != nil {
return nil, nil, err
}
for token.Tok != TokEOF && token.Tok != TokRIGHTPAREN {
// There is more. If not 'and', 'or' or ')', the where is over.
if strings.ToLower(token.Value) != "and" && strings.ToLower(token.Value) != "or" {
return expr, token, nil
}
var newExpression Expression
var operand1 Operand
operand1.Type = TypExpr
operand1.Expr = expr
operand1.Off = operand1.Expr.Off
newExpression.Operand1 = &operand1
newExpression.Off = operand1.Off
newExpression.Operator, token, err = parseLogicalOperator(db, s, token)
if err != nil {
return nil, nil, err
}
expr = &newExpression
// Need to set operand2.
var operand2 Operand
expr.Operand2 = &operand2
if token.Tok == TokLEFTPAREN {
expr.Operand2.Type = TypExpr
expr.Operand2.Expr, token, err = parseParenthesizedExpression(db, s, token)
} else {
expr.Operand2.Type = TypExpr
expr.Operand2.Expr, token, err = parseLikeEqualExpression(db, s, token)
}
if err != nil {
return nil, nil, err
}
expr.Operand2.Off = expr.Operand2.Expr.Off
}
return expr, token, nil
}
// Parse a binary expression. Return expression and next token (or error)
func parseLikeEqualExpression(db ds.Database, s *scanner.Scanner, token *Token) (*Expression, *Token, error) {
var expression Expression
expression.Off = token.Off
// operand 1
var operand1 *Operand
var err error
operand1, token, err = parseOperand(db, s, token)
if err != nil {
return nil, nil, err
}
// operator
var operator *BinaryOperator
operator, token, err = parseBinaryOperator(db, s, token)
if err != nil {
return nil, nil, err
}
// operand 2
var operand2 *Operand
if token.Tok == TokEOF {
return nil, nil, syncql.ErrorfUnexpectedEndOfStatement(db.GetContext(), unexpectedEndOfStatementFormat, token.Off)
}
operand2, token, err = parseOperand(db, s, token)
if err != nil {
return nil, nil, err
}
expression.Operand1 = operand1
expression.Operator = operator
expression.Operand2 = operand2
return &expression, token, nil
}
func parseFunction(db ds.Database, s *scanner.Scanner, funcName string, funcOffset int64, _ *Token) (*Function, *Token, error) {
var function Function
function.Name = funcName
function.Off = funcOffset
token := scanToken(s) // eat left paren
for token.Tok != TokRIGHTPAREN {
if token.Tok == TokEOF {
return nil, nil, syncql.ErrorfExpected(db.GetContext(), expectedFormat, token.Off, ")")
}
var arg *Operand
var err error
arg, token, err = parseOperand(db, s, token)
if err != nil {
return nil, nil, err
}
function.Args = append(function.Args, arg)
// A comma or right paren is expected, but a right paren cannot come after a comma.
if token.Tok == TokCOMMA {
token = scanToken(s)
if token.Tok == TokRIGHTPAREN {
// right paren cannot come after a comma
return nil, nil, syncql.ErrorfExpectedOperand(db.GetContext(), expectedOperandFormat, token.Off, token.Value)
}
} else if token.Tok != TokRIGHTPAREN {
return nil, nil, syncql.ErrorfUnexpected(db.GetContext(), unexpectedFormat, token.Off, token.Value)
}
}
token = scanToken(s) // eat right paren
return &function, token, nil
}
// Parse an operand (field or literal) and return it and the next Token (or error)
func parseOperand(db ds.Database, s *scanner.Scanner, token *Token) (*Operand, *Token, error) { //nolint:gocyclo
if token.Tok == TokEOF {
return nil, nil, syncql.ErrorfUnexpectedEndOfStatement(db.GetContext(), unexpectedEndOfStatementFormat, token.Off)
}
var operand Operand
operand.Off = token.Off
switch token.Tok {
case TokIDENT:
operand.Type = TypField
var field Field
field.Off = token.Off
var segment *Segment
var err error
if segment, token, err = parseSegment(db, s, token); err != nil {
return nil, nil, err
}
field.Segments = append(field.Segments, *segment)
// If the next token is not a period, check for true/false/nil.
// If true/false or nil, change this operand to a bool or nil, respectively.
// Also, check for function call. If so, change to a function operand.
switch {
case token.Tok != TokPERIOD && (strings.ToLower(segment.Value) == "true" || strings.ToLower(segment.Value) == "false"):
operand.Type = TypBool
operand.Bool = strings.ToLower(segment.Value) == "true"
case token.Tok != TokPERIOD && strings.ToLower(segment.Value) == "nil":
operand.Type = TypNil
case token.Tok == TokLEFTPAREN:
// Segments with a key specified cannot be function calls.
if len(segment.Keys) != 0 {
return nil, nil, syncql.ErrorfUnexpected(db.GetContext(), unexpectedFormat, token.Off, token.Value)
}
operand.Type = TypFunction
var err error
if operand.Function, token, err = parseFunction(db, s, segment.Value, segment.Off, token); err != nil {
return nil, nil, err
}
default: // This is a field (column) operand.
// If the next token is a period, collect the rest of the segments in the column.
for token.Tok != TokEOF && token.Tok == TokPERIOD {
token = scanToken(s)
if token.Tok != TokIDENT {
return nil, nil, syncql.ErrorfExpectedIdentifier(db.GetContext(), expectedIdentifierFormat, token.Off, token.Value)
}
if segment, token, err = parseSegment(db, s, token); err != nil {
return nil, nil, err
}
field.Segments = append(field.Segments, *segment)
}
operand.Column = &field
}
case TokINT:
operand.Type = TypInt
i, err := strconv.ParseInt(token.Value, 0, 64)
if err != nil {
return nil, nil, syncql.ErrorfCouldNotConvert(db.GetContext(), couldNotConvertFormat, token.Off, token.Value, "int64")
}
operand.Int = i
token = scanToken(s)
case TokFLOAT:
operand.Type = TypFloat
f, err := strconv.ParseFloat(token.Value, 64)
if err != nil {
return nil, nil, syncql.ErrorfCouldNotConvert(db.GetContext(), couldNotConvertFormat, token.Off, token.Value, "float64")
}
operand.Float = f
token = scanToken(s)
case TokCHAR:
operand.Type = TypInt
ch, _ := utf8.DecodeRuneInString(token.Value)
operand.Int = int64(ch)
token = scanToken(s)
case TokSTRING:
operand.Type = TypStr
operand.Str = token.Value
token = scanToken(s)
case TokMINUS:
// Could be negative int or negative float
off := token.Off
token = scanToken(s)
switch token.Tok {
case TokINT:
operand.Type = TypInt
i, err := strconv.ParseInt("-"+token.Value, 0, 64)
if err != nil {
return nil, nil, syncql.ErrorfCouldNotConvert(db.GetContext(), couldNotConvertFormat, off, "-"+token.Value, "int64")
}
operand.Int = i
case TokFLOAT:
operand.Type = TypFloat
f, err := strconv.ParseFloat("-"+token.Value, 64)
if err != nil {
return nil, nil, syncql.ErrorfCouldNotConvert(db.GetContext(), couldNotConvertFormat, off, "-"+token.Value, "float64")
}
operand.Float = f
default:
return nil, nil, syncql.ErrorfExpected(db.GetContext(), expectedFormat, token.Off, "int or float")
}
token = scanToken(s)
case TokParameter:
operand.Type = TypParameter
token = scanToken(s)
default:
return nil, nil, syncql.ErrorfExpectedOperand(db.GetContext(), expectedOperandFormat, token.Off, token.Value)
}
return &operand, token, nil
}
// Parse binary operator and return it and the next Token (or error)
func parseBinaryOperator(db ds.Database, s *scanner.Scanner, token *Token) (*BinaryOperator, *Token, error) { //nolint:gocyclo
if token.Tok == TokEOF {
return nil, nil, syncql.ErrorfUnexpectedEndOfStatement(db.GetContext(), unexpectedEndOfStatementFormat, token.Off)
}
var operator BinaryOperator
operator.Off = token.Off
if token.Tok == TokIDENT {
switch strings.ToLower(token.Value) {
case "equal":
operator.Type = Equal
token = scanToken(s)
case "is":
operator.Type = Is
token = scanToken(s)
// if the next token is "not", change to IsNot
if token.Tok != TokEOF && strings.ToLower(token.Value) == "not" {
operator.Type = IsNot
token = scanToken(s)
}
case "like":
operator.Type = Like
token = scanToken(s)
case "not":
token = scanToken(s)
if token.Tok == TokEOF || (strings.ToLower(token.Value) != "equal" && strings.ToLower(token.Value) != "like") {
return nil, nil, syncql.ErrorfExpected(db.GetContext(), expectedFormat, token.Off, "'equal' or 'like'")
}
switch strings.ToLower(token.Value) {
case "equal":
operator.Type = NotEqual
default:
operator.Type = NotLike
}
token = scanToken(s)
default:
return nil, nil, syncql.ErrorfExpectedOperator(db.GetContext(), expectedOperatorFormat, token.Off, token.Value)
}
} else {
switch token.Tok {
case TokEQUAL:
operator.Type = Equal
token = scanToken(s)
case TokLEFTANGLEBRACKET:
// Can be '<', '<=', '<>'.
token = scanToken(s)
switch token.Tok {
case TokRIGHTANGLEBRACKET:
operator.Type = NotEqual
token = scanToken(s)
case TokEQUAL:
operator.Type = LessThanOrEqual
token = scanToken(s)
default:
operator.Type = LessThan
}
case TokRIGHTANGLEBRACKET:
// Can be '>', '>='
token = scanToken(s)
switch token.Tok {
case TokEQUAL:
operator.Type = GreaterThanOrEqual
token = scanToken(s)
default:
operator.Type = GreaterThan
}
default:
return nil, nil, syncql.ErrorfExpectedOperator(db.GetContext(), expectedOperatorFormat, token.Off, token.Value)
}
}
return &operator, token, nil
}
// Parse logical operator and return it and the next Token (or error)
func parseLogicalOperator(db ds.Database, s *scanner.Scanner, token *Token) (*BinaryOperator, *Token, error) {
if token.Tok == TokEOF {
return nil, nil, syncql.ErrorfUnexpectedEndOfStatement(db.GetContext(), unexpectedEndOfStatementFormat, token.Off)
}
var operator BinaryOperator
operator.Off = token.Off
switch strings.ToLower(token.Value) {
case "and":
operator.Type = And
case "or":
operator.Type = Or
default:
return nil, nil, syncql.ErrorfExpectedOperator(db.GetContext(), expectedOperatorFormat, token.Off, token.Value)
}
token = scanToken(s)
return &operator, token, nil
}
// Parse and return EscapeClause, LimitClause and ResultsOffsetClause (any or all can be nil) and next token (or error)
func parseEscapeLimitResultsOffsetClauses(db ds.Database, s *scanner.Scanner, token *Token) (*EscapeClause, *LimitClause, *ResultsOffsetClause, *Token, error) {
var err error
var ec *EscapeClause
var lc *LimitClause
var oc *ResultsOffsetClause
for token.Tok != TokEOF {
// Note: Can be in any order. If more than one, the last one wins
switch {
case token.Tok == TokIDENT && strings.ToLower(token.Value) == "escape":
ec, token, err = parseEscapeClause(db, s, token)
case token.Tok == TokIDENT && strings.ToLower(token.Value) == "limit":
lc, token, err = parseLimitClause(db, s, token)
case token.Tok == TokIDENT && strings.ToLower(token.Value) == "offset":
oc, token, err = parseResultsOffsetClause(db, s, token)
default:
return ec, lc, oc, token, nil
}
if err != nil {
return nil, nil, nil, nil, err
}
}
return ec, lc, oc, token, nil
}
// Parse and return the EscapeClause and LimitClause (any or all can be nil) and next token (or error)
func parseEscapeLimitClauses(db ds.Database, s *scanner.Scanner, token *Token) (*EscapeClause, *LimitClause, *Token, error) {
var err error
var ec *EscapeClause
var lc *LimitClause
for token.Tok != TokEOF {
// Note: Can be in any order. If more than one, the last one wins
switch {
case token.Tok == TokIDENT && strings.ToLower(token.Value) == "escape":
ec, token, err = parseEscapeClause(db, s, token)
case token.Tok == TokIDENT && strings.ToLower(token.Value) == "limit":
lc, token, err = parseLimitClause(db, s, token)
default:
return ec, lc, token, nil
}
if err != nil {
return nil, nil, nil, err
}
}
return ec, lc, token, nil
}
// Parse the escape clause. Return the EscapeClause and the next Token (or error).
func parseEscapeClause(db ds.Database, s *scanner.Scanner, token *Token) (*EscapeClause, *Token, error) {
var ec EscapeClause
ec.Off = token.Off
token = scanToken(s)
if token.Tok == TokEOF {
return nil, nil, syncql.ErrorfUnexpectedEndOfStatement(db.GetContext(), unexpectedEndOfStatementFormat, token.Off)
}
if token.Tok != TokCHAR {
return nil, nil, syncql.ErrorfExpected(db.GetContext(), expectedFormat, token.Off, "char literal")
}
var v CharValue
v.Off = token.Off
v.Value, _ = utf8.DecodeRuneInString(token.Value)
ec.EscapeChar = &v
token = scanToken(s)