forked from influxdata/influxql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
3127 lines (2670 loc) · 80.6 KB
/
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
package influxql
import (
"bytes"
"errors"
"fmt"
"io"
"math"
"regexp"
"strconv"
"strings"
"time"
)
const (
// DateFormat represents the format for date literals.
DateFormat = "2006-01-02"
// DateTimeFormat represents the format for date time literals.
DateTimeFormat = "2006-01-02 15:04:05.999999"
)
// Parser represents an InfluxQL parser.
type Parser struct {
s *bufScanner
params map[string]interface{}
}
// NewParser returns a new instance of Parser.
func NewParser(r io.Reader) *Parser {
return &Parser{s: newBufScanner(r)}
}
// SetParams sets the parameters that will be used for any bound parameter substitutions.
func (p *Parser) SetParams(params map[string]interface{}) {
p.params = params
}
// ParseQuery parses a query string and returns its AST representation.
func ParseQuery(s string) (*Query, error) { return NewParser(strings.NewReader(s)).ParseQuery() }
// ParseStatement parses a statement string and returns its AST representation.
func ParseStatement(s string) (Statement, error) {
return NewParser(strings.NewReader(s)).ParseStatement()
}
// MustParseStatement parses a statement string and returns its AST. Panic on error.
func MustParseStatement(s string) Statement {
stmt, err := ParseStatement(s)
if err != nil {
panic(err.Error())
}
return stmt
}
// ParseExpr parses an expression string and returns its AST representation.
func ParseExpr(s string) (Expr, error) { return NewParser(strings.NewReader(s)).ParseExpr() }
// MustParseExpr parses an expression string and returns its AST. Panic on error.
func MustParseExpr(s string) Expr {
expr, err := ParseExpr(s)
if err != nil {
panic(err.Error())
}
return expr
}
// ParseQuery parses an InfluxQL string and returns a Query AST object.
func (p *Parser) ParseQuery() (*Query, error) {
var statements Statements
semi := true
for {
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok == EOF {
return &Query{Statements: statements}, nil
} else if tok == SEMICOLON {
semi = true
} else {
if !semi {
return nil, newParseError(tokstr(tok, lit), []string{";"}, pos)
}
p.Unscan()
s, err := p.ParseStatement()
if err != nil {
return nil, err
}
statements = append(statements, s)
semi = false
}
}
}
// ParseStatement parses an InfluxQL string and returns a Statement AST object.
func (p *Parser) ParseStatement() (Statement, error) {
return Language.Parse(p)
}
// parseSetPasswordUserStatement parses a string and returns a set statement.
// This function assumes the SET token has already been consumed.
func (p *Parser) parseSetPasswordUserStatement() (*SetPasswordUserStatement, error) {
stmt := &SetPasswordUserStatement{}
// Parse username
ident, err := p.ParseIdent()
if err != nil {
return nil, err
}
stmt.Name = ident
// Consume the required = token.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != EQ {
return nil, newParseError(tokstr(tok, lit), []string{"="}, pos)
}
// Parse new user's password
if ident, err = p.parseString(); err != nil {
return nil, err
}
stmt.Password = ident
return stmt, nil
}
// parseKillQueryStatement parses a string and returns a kill statement.
// This function assumes the KILL token has already been consumed.
func (p *Parser) parseKillQueryStatement() (*KillQueryStatement, error) {
qid, err := p.ParseUInt64()
if err != nil {
return nil, err
}
var host string
if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON {
host, err = p.ParseIdent()
if err != nil {
return nil, err
}
} else {
p.Unscan()
}
return &KillQueryStatement{QueryID: qid, Host: host}, nil
}
// parseCreateSubscriptionStatement parses a string and returns a CreateSubscriptionStatement.
// This function assumes the "CREATE SUBSCRIPTION" tokens have already been consumed.
func (p *Parser) parseCreateSubscriptionStatement() (*CreateSubscriptionStatement, error) {
stmt := &CreateSubscriptionStatement{}
// Read the id of the subscription to create.
ident, err := p.ParseIdent()
if err != nil {
return nil, err
}
stmt.Name = ident
// Expect an "ON" keyword.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != ON {
return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos)
}
// Read the name of the database.
if ident, err = p.ParseIdent(); err != nil {
return nil, err
}
stmt.Database = ident
if tok, pos, lit := p.Scan(); tok != DOT {
return nil, newParseError(tokstr(tok, lit), []string{"."}, pos)
}
// Read the name of the retention policy.
if ident, err = p.ParseIdent(); err != nil {
return nil, err
}
stmt.RetentionPolicy = ident
// Expect a "DESTINATIONS" keyword.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != DESTINATIONS {
return nil, newParseError(tokstr(tok, lit), []string{"DESTINATIONS"}, pos)
}
// Expect one of "ANY ALL" keywords.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok == ALL || tok == ANY {
stmt.Mode = tokens[tok]
} else {
return nil, newParseError(tokstr(tok, lit), []string{"ALL", "ANY"}, pos)
}
// Read list of destinations.
var destinations []string
if destinations, err = p.parseStringList(); err != nil {
return nil, err
}
stmt.Destinations = destinations
return stmt, nil
}
// parseCreateRetentionPolicyStatement parses a string and returns a create retention policy statement.
// This function assumes the CREATE RETENTION POLICY tokens have already been consumed.
func (p *Parser) parseCreateRetentionPolicyStatement() (*CreateRetentionPolicyStatement, error) {
stmt := &CreateRetentionPolicyStatement{}
// Parse the retention policy name.
ident, err := p.ParseIdent()
if err != nil {
return nil, err
}
stmt.Name = ident
// Consume the required ON token.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != ON {
return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos)
}
// Parse the database name.
ident, err = p.ParseIdent()
if err != nil {
return nil, err
}
stmt.Database = ident
// Parse required DURATION token.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != DURATION {
return nil, newParseError(tokstr(tok, lit), []string{"DURATION"}, pos)
}
// Parse duration value
d, err := p.ParseDuration()
if err != nil {
return nil, err
}
stmt.Duration = d
// Parse required REPLICATION token.
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != REPLICATION {
return nil, newParseError(tokstr(tok, lit), []string{"REPLICATION"}, pos)
}
// Parse replication value.
n, err := p.ParseInt(1, math.MaxInt32)
if err != nil {
return nil, err
}
stmt.Replication = n
// Parse optional SHARD token.
if tok, _, _ := p.ScanIgnoreWhitespace(); tok == SHARD {
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != DURATION {
return nil, newParseError(tokstr(tok, lit), []string{"DURATION"}, pos)
}
// Check to see if they used the INF keyword
tok, pos, _ := p.ScanIgnoreWhitespace()
if tok == INF {
return nil, &ParseError{
Message: "invalid duration INF for shard duration",
Pos: pos,
}
}
p.Unscan()
d, err := p.ParseDuration()
if err != nil {
return nil, err
}
stmt.ShardGroupDuration = d
} else {
p.Unscan()
}
// Parse optional DEFAULT token.
if tok, _, _ := p.ScanIgnoreWhitespace(); tok == DEFAULT {
stmt.Default = true
} else {
p.Unscan()
}
return stmt, nil
}
// parseAlterRetentionPolicyStatement parses a string and returns an alter retention policy statement.
// This function assumes the ALTER RETENTION POLICY tokens have already been consumed.
func (p *Parser) parseAlterRetentionPolicyStatement() (*AlterRetentionPolicyStatement, error) {
stmt := &AlterRetentionPolicyStatement{}
// Parse the retention policy name.
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok == DEFAULT {
stmt.Name = "default"
} else if tok == IDENT {
stmt.Name = lit
} else {
return nil, newParseError(tokstr(tok, lit), []string{"identifier"}, pos)
}
// Consume the required ON token.
if tok, pos, lit = p.ScanIgnoreWhitespace(); tok != ON {
return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos)
}
// Parse the database name.
ident, err := p.ParseIdent()
if err != nil {
return nil, err
}
stmt.Database = ident
// Loop through option tokens (DURATION, REPLICATION, SHARD DURATION, DEFAULT, etc.).
found := make(map[Token]struct{})
Loop:
for {
tok, pos, lit := p.ScanIgnoreWhitespace()
if _, ok := found[tok]; ok {
return nil, &ParseError{
Message: fmt.Sprintf("found duplicate %s option", tok),
Pos: pos,
}
}
switch tok {
case DURATION:
d, err := p.ParseDuration()
if err != nil {
return nil, err
}
stmt.Duration = &d
case REPLICATION:
n, err := p.ParseInt(1, math.MaxInt32)
if err != nil {
return nil, err
}
stmt.Replication = &n
case SHARD:
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok == DURATION {
// Check to see if they used the INF keyword
tok, pos, _ := p.ScanIgnoreWhitespace()
if tok == INF {
return nil, &ParseError{
Message: "invalid duration INF for shard duration",
Pos: pos,
}
}
p.Unscan()
d, err := p.ParseDuration()
if err != nil {
return nil, err
}
stmt.ShardGroupDuration = &d
} else {
return nil, newParseError(tokstr(tok, lit), []string{"DURATION"}, pos)
}
case DEFAULT:
stmt.Default = true
default:
if len(found) == 0 {
return nil, newParseError(tokstr(tok, lit), []string{"DURATION", "REPLICATION", "SHARD", "DEFAULT"}, pos)
}
p.Unscan()
break Loop
}
found[tok] = struct{}{}
}
return stmt, nil
}
// ParseInt parses a string representing a base 10 integer and returns the number.
// It returns an error if the parsed number is outside the range [min, max].
func (p *Parser) ParseInt(min, max int) (int, error) {
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok != INTEGER {
return 0, newParseError(tokstr(tok, lit), []string{"integer"}, pos)
}
// Convert string to int.
n, err := strconv.Atoi(lit)
if err != nil {
return 0, &ParseError{Message: err.Error(), Pos: pos}
} else if min > n || n > max {
return 0, &ParseError{
Message: fmt.Sprintf("invalid value %d: must be %d <= n <= %d", n, min, max),
Pos: pos,
}
}
return n, nil
}
// ParseUInt64 parses a string and returns a 64-bit unsigned integer literal.
func (p *Parser) ParseUInt64() (uint64, error) {
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok != INTEGER {
return 0, newParseError(tokstr(tok, lit), []string{"integer"}, pos)
}
// Convert string to unsigned 64-bit integer
n, err := strconv.ParseUint(lit, 10, 64)
if err != nil {
return 0, &ParseError{Message: err.Error(), Pos: pos}
}
return uint64(n), nil
}
// ParseDuration parses a string and returns a duration literal.
// This function assumes the DURATION token has already been consumed.
func (p *Parser) ParseDuration() (time.Duration, error) {
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok != DURATIONVAL && tok != INF {
return 0, newParseError(tokstr(tok, lit), []string{"duration"}, pos)
}
if tok == INF {
return 0, nil
}
d, err := ParseDuration(lit)
if err != nil {
return 0, &ParseError{Message: err.Error(), Pos: pos}
}
return d, nil
}
// ParseIdent parses an identifier.
func (p *Parser) ParseIdent() (string, error) {
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok != IDENT {
return "", newParseError(tokstr(tok, lit), []string{"identifier"}, pos)
}
return lit, nil
}
// ParseIdentList parses a comma delimited list of identifiers.
func (p *Parser) ParseIdentList() ([]string, error) {
// Parse first (required) identifier.
ident, err := p.ParseIdent()
if err != nil {
return nil, err
}
idents := []string{ident}
// Parse remaining (optional) identifiers.
for {
if tok, _, _ := p.ScanIgnoreWhitespace(); tok != COMMA {
p.Unscan()
return idents, nil
}
if ident, err = p.ParseIdent(); err != nil {
return nil, err
}
idents = append(idents, ident)
}
}
// parseSegmentedIdents parses a segmented identifiers.
// e.g., "db"."rp".measurement or "db"..measurement
func (p *Parser) parseSegmentedIdents() ([]string, error) {
ident, err := p.ParseIdent()
if err != nil {
return nil, err
}
idents := []string{ident}
// Parse remaining (optional) identifiers.
for {
if tok, _, _ := p.Scan(); tok != DOT {
// No more segments so we're done.
p.Unscan()
break
}
if ch := p.peekRune(); ch == '/' {
// Next segment is a regex so we're done.
break
} else if ch == ':' {
// Next segment is context-specific so let caller handle it.
break
} else if ch == '.' {
// Add an empty identifier.
idents = append(idents, "")
continue
}
// Parse the next identifier.
if ident, err = p.ParseIdent(); err != nil {
return nil, err
}
idents = append(idents, ident)
}
if len(idents) > 3 {
msg := fmt.Sprintf("too many segments in %s", QuoteIdent(idents...))
return nil, &ParseError{Message: msg}
}
return idents, nil
}
// parseString parses a string.
func (p *Parser) parseString() (string, error) {
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok != STRING {
return "", newParseError(tokstr(tok, lit), []string{"string"}, pos)
}
return lit, nil
}
// parseStringList parses a list of strings separated by commas.
func (p *Parser) parseStringList() ([]string, error) {
// Parse first (required) string.
str, err := p.parseString()
if err != nil {
return nil, err
}
strs := []string{str}
// Parse remaining (optional) strings.
for {
if tok, _, _ := p.ScanIgnoreWhitespace(); tok != COMMA {
p.Unscan()
return strs, nil
}
if str, err = p.parseString(); err != nil {
return nil, err
}
strs = append(strs, str)
}
}
// parseRevokeStatement parses a string and returns a revoke statement.
// This function assumes the REVOKE token has already been consumed.
func (p *Parser) parseRevokeStatement() (Statement, error) {
// Parse the privilege to be revoked.
priv, err := p.parsePrivilege()
if err != nil {
return nil, err
}
// Check for ON or FROM clauses.
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok == ON {
stmt, err := p.parseRevokeOnStatement()
if err != nil {
return nil, err
}
stmt.Privilege = priv
return stmt, nil
} else if tok == FROM {
// Admin privilege is only revoked on ALL PRIVILEGES.
if priv != AllPrivileges {
return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos)
}
return p.parseRevokeAdminStatement()
}
// Only ON or FROM clauses are allowed after privilege.
if priv == AllPrivileges {
return nil, newParseError(tokstr(tok, lit), []string{"ON", "FROM"}, pos)
}
return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos)
}
// parseRevokeOnStatement parses a string and returns a revoke statement.
// This function assumes the [PRIVILEGE] ON tokens have already been consumed.
func (p *Parser) parseRevokeOnStatement() (*RevokeStatement, error) {
stmt := &RevokeStatement{}
// Parse the name of the database.
lit, err := p.ParseIdent()
if err != nil {
return nil, err
}
stmt.On = lit
// Parse FROM clause.
tok, pos, lit := p.ScanIgnoreWhitespace()
// Check for required FROM token.
if tok != FROM {
return nil, newParseError(tokstr(tok, lit), []string{"FROM"}, pos)
}
// Parse the name of the user.
lit, err = p.ParseIdent()
if err != nil {
return nil, err
}
stmt.User = lit
return stmt, nil
}
// parseRevokeAdminStatement parses a string and returns a revoke admin statement.
// This function assumes the ALL [PRVILEGES] FROM token has already been consumed.
func (p *Parser) parseRevokeAdminStatement() (*RevokeAdminStatement, error) {
// Admin privilege is always false when revoke admin clause is called.
stmt := &RevokeAdminStatement{}
// Parse the name of the user.
lit, err := p.ParseIdent()
if err != nil {
return nil, err
}
stmt.User = lit
return stmt, nil
}
// parseGrantStatement parses a string and returns a grant statement.
// This function assumes the GRANT token has already been consumed.
func (p *Parser) parseGrantStatement() (Statement, error) {
// Parse the privilege to be granted.
priv, err := p.parsePrivilege()
if err != nil {
return nil, err
}
// Check for ON or TO clauses.
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok == ON {
stmt, err := p.parseGrantOnStatement()
if err != nil {
return nil, err
}
stmt.Privilege = priv
return stmt, nil
} else if tok == TO {
// Admin privilege is only granted on ALL PRIVILEGES.
if priv != AllPrivileges {
return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos)
}
return p.parseGrantAdminStatement()
}
// Only ON or TO clauses are allowed after privilege.
if priv == AllPrivileges {
return nil, newParseError(tokstr(tok, lit), []string{"ON", "TO"}, pos)
}
return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos)
}
// parseGrantOnStatement parses a string and returns a grant statement.
// This function assumes the [PRIVILEGE] ON tokens have already been consumed.
func (p *Parser) parseGrantOnStatement() (*GrantStatement, error) {
stmt := &GrantStatement{}
// Parse the name of the database.
lit, err := p.ParseIdent()
if err != nil {
return nil, err
}
stmt.On = lit
// Parse TO clause.
tok, pos, lit := p.ScanIgnoreWhitespace()
// Check for required TO token.
if tok != TO {
return nil, newParseError(tokstr(tok, lit), []string{"TO"}, pos)
}
// Parse the name of the user.
lit, err = p.ParseIdent()
if err != nil {
return nil, err
}
stmt.User = lit
return stmt, nil
}
// parseGrantAdminStatement parses a string and returns a grant admin statement.
// This function assumes the ALL [PRVILEGES] TO tokens have already been consumed.
func (p *Parser) parseGrantAdminStatement() (*GrantAdminStatement, error) {
// Admin privilege is always true when grant admin clause is called.
stmt := &GrantAdminStatement{}
// Parse the name of the user.
lit, err := p.ParseIdent()
if err != nil {
return nil, err
}
stmt.User = lit
return stmt, nil
}
// parsePrivilege parses a string and returns a Privilege.
func (p *Parser) parsePrivilege() (Privilege, error) {
tok, pos, lit := p.ScanIgnoreWhitespace()
switch tok {
case READ:
return ReadPrivilege, nil
case WRITE:
return WritePrivilege, nil
case ALL:
// Consume optional PRIVILEGES token
tok, pos, lit = p.ScanIgnoreWhitespace()
if tok != PRIVILEGES {
p.Unscan()
}
return AllPrivileges, nil
}
return 0, newParseError(tokstr(tok, lit), []string{"READ", "WRITE", "ALL [PRIVILEGES]"}, pos)
}
// parseSelectStatement parses a select string and returns a Statement AST object.
// This function assumes the SELECT token has already been consumed.
func (p *Parser) parseSelectStatement(tr targetRequirement) (*SelectStatement, error) {
stmt := &SelectStatement{}
var err error
// Parse fields: "FIELD+".
if stmt.Fields, err = p.parseFields(); err != nil {
return nil, err
}
// Parse target: "INTO"
if stmt.Target, err = p.parseTarget(tr); err != nil {
return nil, err
}
// Parse source: "FROM".
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != FROM {
return nil, newParseError(tokstr(tok, lit), []string{"FROM"}, pos)
}
if stmt.Sources, err = p.parseSources(true); err != nil {
return nil, err
}
// Parse condition: "WHERE EXPR".
if stmt.Condition, err = p.parseCondition(); err != nil {
return nil, err
}
// Parse dimensions: "GROUP BY DIMENSION+".
if stmt.Dimensions, err = p.parseDimensions(); err != nil {
return nil, err
}
// Parse fill options: "fill(<option>)"
if stmt.Fill, stmt.FillValue, err = p.parseFill(); err != nil {
return nil, err
}
// Parse sort: "ORDER BY FIELD+".
if stmt.SortFields, err = p.parseOrderBy(); err != nil {
return nil, err
}
// Parse limit: "LIMIT <n>".
if stmt.Limit, err = p.ParseOptionalTokenAndInt(LIMIT); err != nil {
return nil, err
}
// Parse offset: "OFFSET <n>".
if stmt.Offset, err = p.ParseOptionalTokenAndInt(OFFSET); err != nil {
return nil, err
}
// Parse series limit: "SLIMIT <n>".
if stmt.SLimit, err = p.ParseOptionalTokenAndInt(SLIMIT); err != nil {
return nil, err
}
// Parse series offset: "SOFFSET <n>".
if stmt.SOffset, err = p.ParseOptionalTokenAndInt(SOFFSET); err != nil {
return nil, err
}
// Parse timezone: "TZ(<timezone>)".
if stmt.Location, err = p.parseLocation(); err != nil {
return nil, err
}
// Set if the query is a raw data query or one with an aggregate
stmt.IsRawQuery = true
WalkFunc(stmt.Fields, func(n Node) {
if _, ok := n.(*Call); ok {
stmt.IsRawQuery = false
}
})
return stmt, nil
}
// targetRequirement specifies whether or not a target clause is required.
type targetRequirement int
const (
targetRequired targetRequirement = iota
targetNotRequired
targetSubquery
)
// parseTarget parses a string and returns a Target.
func (p *Parser) parseTarget(tr targetRequirement) (*Target, error) {
if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != INTO {
if tr == targetRequired {
return nil, newParseError(tokstr(tok, lit), []string{"INTO"}, pos)
}
p.Unscan()
return nil, nil
}
// db, rp, and / or measurement
idents, err := p.parseSegmentedIdents()
if err != nil {
return nil, err
}
if len(idents) < 3 {
// Check for source measurement reference.
if ch := p.peekRune(); ch == ':' {
if err := p.parseTokens([]Token{COLON, MEASUREMENT}); err != nil {
return nil, err
}
// Append empty measurement name.
idents = append(idents, "")
}
}
t := &Target{Measurement: &Measurement{IsTarget: true}}
switch len(idents) {
case 1:
t.Measurement.Name = idents[0]
case 2:
t.Measurement.RetentionPolicy = idents[0]
t.Measurement.Name = idents[1]
case 3:
t.Measurement.Database = idents[0]
t.Measurement.RetentionPolicy = idents[1]
t.Measurement.Name = idents[2]
}
return t, nil
}
// parseDeleteStatement parses a string and returns a delete statement.
// This function assumes the DELETE token has already been consumed.
func (p *Parser) parseDeleteStatement() (Statement, error) {
stmt := &DeleteSeriesStatement{}
var err error
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok == FROM {
// Parse source.
if stmt.Sources, err = p.parseSources(false); err != nil {
return nil, err
}
var err error
WalkFunc(stmt.Sources, func(n Node) {
if t, ok := n.(*Measurement); ok {
// Don't allow database or retention policy in from clause for delete
// statement. They apply to the selected database across all retention
// policies.
if t.Database != "" {
err = &ParseError{Message: "database not supported"}
}
if t.RetentionPolicy != "" {
err = &ParseError{Message: "retention policy not supported"}
}
}
})
if err != nil {
return nil, err
}
} else {
p.Unscan()
}
// Parse condition: "WHERE EXPR".
if stmt.Condition, err = p.parseCondition(); err != nil {
return nil, err
}
// If they didn't provide a FROM or a WHERE, this query is invalid
if stmt.Condition == nil && stmt.Sources == nil {
return nil, newParseError(tokstr(tok, lit), []string{"FROM", "WHERE"}, pos)
}
return stmt, nil
}
// parseShowSeriesStatement parses a string and returns a Statement.
// This function assumes the "SHOW SERIES" tokens have already been consumed.
func (p *Parser) parseShowSeriesStatement() (Statement, error) {
var exactCardinality bool
if tok, _, _ := p.ScanIgnoreWhitespace(); tok == EXACT {
exactCardinality = true
} else {
p.Unscan()
}
if tok, _, _ := p.ScanIgnoreWhitespace(); tok == CARDINALITY {
return p.parseShowSeriesCardinalityStatement(exactCardinality)
}
p.Unscan()
// Handle SHOW SERIES statments.
stmt := &ShowSeriesStatement{}
var err error
// Parse optional ON clause.
if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON {
// Parse the database.
stmt.Database, err = p.ParseIdent()
if err != nil {
return nil, err
}
} else {
p.Unscan()
}
// Parse optional FROM.
if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FROM {
if stmt.Sources, err = p.parseSources(false); err != nil {
return nil, err
}
} else {
p.Unscan()
}
// Parse condition: "WHERE EXPR".
if stmt.Condition, err = p.parseCondition(); err != nil {
return nil, err
}
// Parse sort: "ORDER BY FIELD+".
if stmt.SortFields, err = p.parseOrderBy(); err != nil {
return nil, err
}
// Parse limit: "LIMIT <n>".
if stmt.Limit, err = p.ParseOptionalTokenAndInt(LIMIT); err != nil {
return nil, err
}
// Parse offset: "OFFSET <n>".
if stmt.Offset, err = p.ParseOptionalTokenAndInt(OFFSET); err != nil {
return nil, err
}
return stmt, nil
}
// This function assumes the "SHOW SERIES EXACT CARDINALITY" or the
// "SHOW SERIES CARDINALITY" tokens have already been consumed.
func (p *Parser) parseShowSeriesCardinalityStatement(exact bool) (Statement, error) {
var err error
stmt := &ShowSeriesCardinalityStatement{Exact: exact}
// Parse optional ON clause.
if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON {
if stmt.Database, err = p.ParseIdent(); err != nil {
return nil, err
}
} else {
p.Unscan()
}
// Parse optional FROM.
if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FROM {
if stmt.Sources, err = p.parseSources(false); err != nil {
return nil, err
}
} else {
p.Unscan()
}
// Parse condition: "WHERE EXPR".
if stmt.Condition, err = p.parseCondition(); err != nil {
return nil, err
}
// Parse dimensions: "GROUP BY DIMENSION+".
if stmt.Dimensions, err = p.parseDimensions(); err != nil {
return nil, err
}
// Parse limit & offset: "LIMIT <n>", "OFFSET <n>".
if stmt.Limit, err = p.ParseOptionalTokenAndInt(LIMIT); err != nil {
return nil, err
} else if stmt.Offset, err = p.ParseOptionalTokenAndInt(OFFSET); err != nil {
return nil, err