github.com/influxdata/influxql@v1.1.0/parser.go (about) 1 package influxql 2 3 import ( 4 "bytes" 5 "errors" 6 "fmt" 7 "io" 8 "math" 9 "regexp" 10 "strconv" 11 "strings" 12 "time" 13 ) 14 15 const ( 16 // DateFormat represents the format for date literals. 17 DateFormat = "2006-01-02" 18 19 // DateTimeFormat represents the format for date time literals. 20 DateTimeFormat = "2006-01-02 15:04:05.999999" 21 ) 22 23 // Parser represents an InfluxQL parser. 24 type Parser struct { 25 s *bufScanner 26 params map[string]Value 27 } 28 29 // NewParser returns a new instance of Parser. 30 func NewParser(r io.Reader) *Parser { 31 return &Parser{s: newBufScanner(r)} 32 } 33 34 // SetParams sets the parameters that will be used for any bound parameter substitutions. 35 func (p *Parser) SetParams(params map[string]interface{}) { 36 p.params = make(map[string]Value, len(params)) 37 for name, param := range params { 38 p.params[name] = BindValue(param) 39 } 40 } 41 42 // ParseQuery parses a query string and returns its AST representation. 43 func ParseQuery(s string) (*Query, error) { return NewParser(strings.NewReader(s)).ParseQuery() } 44 45 // ParseStatement parses a statement string and returns its AST representation. 46 func ParseStatement(s string) (Statement, error) { 47 return NewParser(strings.NewReader(s)).ParseStatement() 48 } 49 50 // MustParseStatement parses a statement string and returns its AST. Panic on error. 51 func MustParseStatement(s string) Statement { 52 stmt, err := ParseStatement(s) 53 if err != nil { 54 panic(err.Error()) 55 } 56 return stmt 57 } 58 59 // ParseExpr parses an expression string and returns its AST representation. 60 func ParseExpr(s string) (Expr, error) { return NewParser(strings.NewReader(s)).ParseExpr() } 61 62 // MustParseExpr parses an expression string and returns its AST. Panic on error. 63 func MustParseExpr(s string) Expr { 64 expr, err := ParseExpr(s) 65 if err != nil { 66 panic(err.Error()) 67 } 68 return expr 69 } 70 71 // ParseQuery parses an InfluxQL string and returns a Query AST object. 72 func (p *Parser) ParseQuery() (*Query, error) { 73 var statements Statements 74 semi := true 75 76 for { 77 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok == EOF { 78 return &Query{Statements: statements}, nil 79 } else if tok == SEMICOLON { 80 semi = true 81 } else { 82 if !semi { 83 return nil, newParseError(tokstr(tok, lit), []string{";"}, pos) 84 } 85 p.Unscan() 86 s, err := p.ParseStatement() 87 if err != nil { 88 return nil, err 89 } 90 statements = append(statements, s) 91 semi = false 92 } 93 } 94 } 95 96 // ParseStatement parses an InfluxQL string and returns a Statement AST object. 97 func (p *Parser) ParseStatement() (Statement, error) { 98 return Language.Parse(p) 99 } 100 101 // parseSetPasswordUserStatement parses a string and returns a set statement. 102 // This function assumes the SET token has already been consumed. 103 func (p *Parser) parseSetPasswordUserStatement() (*SetPasswordUserStatement, error) { 104 stmt := &SetPasswordUserStatement{} 105 106 // Parse username 107 ident, err := p.ParseIdent() 108 109 if err != nil { 110 return nil, err 111 } 112 stmt.Name = ident 113 114 // Consume the required = token. 115 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != EQ { 116 return nil, newParseError(tokstr(tok, lit), []string{"="}, pos) 117 } 118 119 // Parse new user's password 120 if ident, err = p.parseString(); err != nil { 121 return nil, err 122 } 123 stmt.Password = ident 124 125 return stmt, nil 126 } 127 128 // parseKillQueryStatement parses a string and returns a kill statement. 129 // This function assumes the KILL token has already been consumed. 130 func (p *Parser) parseKillQueryStatement() (*KillQueryStatement, error) { 131 qid, err := p.ParseUInt64() 132 if err != nil { 133 return nil, err 134 } 135 136 var host string 137 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON { 138 host, err = p.ParseIdent() 139 if err != nil { 140 return nil, err 141 } 142 } else { 143 p.Unscan() 144 } 145 return &KillQueryStatement{QueryID: qid, Host: host}, nil 146 } 147 148 // parseCreateSubscriptionStatement parses a string and returns a CreateSubscriptionStatement. 149 // This function assumes the "CREATE SUBSCRIPTION" tokens have already been consumed. 150 func (p *Parser) parseCreateSubscriptionStatement() (*CreateSubscriptionStatement, error) { 151 stmt := &CreateSubscriptionStatement{} 152 153 // Read the id of the subscription to create. 154 ident, err := p.ParseIdent() 155 if err != nil { 156 return nil, err 157 } 158 stmt.Name = ident 159 160 // Expect an "ON" keyword. 161 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != ON { 162 return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos) 163 } 164 165 // Read the name of the database. 166 if ident, err = p.ParseIdent(); err != nil { 167 return nil, err 168 } 169 stmt.Database = ident 170 171 if tok, pos, lit := p.Scan(); tok != DOT { 172 return nil, newParseError(tokstr(tok, lit), []string{"."}, pos) 173 } 174 175 // Read the name of the retention policy. 176 if ident, err = p.ParseIdent(); err != nil { 177 return nil, err 178 } 179 stmt.RetentionPolicy = ident 180 181 // Expect a "DESTINATIONS" keyword. 182 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != DESTINATIONS { 183 return nil, newParseError(tokstr(tok, lit), []string{"DESTINATIONS"}, pos) 184 } 185 186 // Expect one of "ANY ALL" keywords. 187 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok == ALL || tok == ANY { 188 stmt.Mode = tokens[tok] 189 } else { 190 return nil, newParseError(tokstr(tok, lit), []string{"ALL", "ANY"}, pos) 191 } 192 193 // Read list of destinations. 194 var destinations []string 195 if destinations, err = p.parseStringList(); err != nil { 196 return nil, err 197 } 198 stmt.Destinations = destinations 199 200 return stmt, nil 201 } 202 203 // parseCreateRetentionPolicyStatement parses a string and returns a create retention policy statement. 204 // This function assumes the CREATE RETENTION POLICY tokens have already been consumed. 205 func (p *Parser) parseCreateRetentionPolicyStatement() (*CreateRetentionPolicyStatement, error) { 206 stmt := &CreateRetentionPolicyStatement{} 207 208 // Parse the retention policy name. 209 ident, err := p.ParseIdent() 210 if err != nil { 211 return nil, err 212 } 213 stmt.Name = ident 214 215 // Consume the required ON token. 216 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != ON { 217 return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos) 218 } 219 220 // Parse the database name. 221 ident, err = p.ParseIdent() 222 if err != nil { 223 return nil, err 224 } 225 stmt.Database = ident 226 227 // Parse required DURATION token. 228 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != DURATION { 229 return nil, newParseError(tokstr(tok, lit), []string{"DURATION"}, pos) 230 } 231 232 // Parse duration value 233 d, err := p.ParseDuration() 234 if err != nil { 235 return nil, err 236 } 237 stmt.Duration = d 238 239 // Parse required REPLICATION token. 240 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != REPLICATION { 241 return nil, newParseError(tokstr(tok, lit), []string{"REPLICATION"}, pos) 242 } 243 244 // Parse replication value. 245 n, err := p.ParseInt(1, math.MaxInt32) 246 if err != nil { 247 return nil, err 248 } 249 stmt.Replication = n 250 251 // Parse optional SHARD token. 252 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == SHARD { 253 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != DURATION { 254 return nil, newParseError(tokstr(tok, lit), []string{"DURATION"}, pos) 255 } 256 257 // Check to see if they used the INF keyword 258 tok, pos, _ := p.ScanIgnoreWhitespace() 259 if tok == INF { 260 return nil, &ParseError{ 261 Message: "invalid duration INF for shard duration", 262 Pos: pos, 263 } 264 } 265 p.Unscan() 266 267 d, err := p.ParseDuration() 268 if err != nil { 269 return nil, err 270 } 271 stmt.ShardGroupDuration = d 272 } else { 273 p.Unscan() 274 } 275 276 // Parse optional DEFAULT token. 277 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == DEFAULT { 278 stmt.Default = true 279 } else { 280 p.Unscan() 281 } 282 283 return stmt, nil 284 } 285 286 // parseAlterRetentionPolicyStatement parses a string and returns an alter retention policy statement. 287 // This function assumes the ALTER RETENTION POLICY tokens have already been consumed. 288 func (p *Parser) parseAlterRetentionPolicyStatement() (*AlterRetentionPolicyStatement, error) { 289 stmt := &AlterRetentionPolicyStatement{} 290 291 // Parse the retention policy name. 292 tok, pos, lit := p.ScanIgnoreWhitespace() 293 if tok == DEFAULT { 294 stmt.Name = "default" 295 } else if tok == IDENT { 296 stmt.Name = lit 297 } else { 298 return nil, newParseError(tokstr(tok, lit), []string{"identifier"}, pos) 299 } 300 301 // Consume the required ON token. 302 if tok, pos, lit = p.ScanIgnoreWhitespace(); tok != ON { 303 return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos) 304 } 305 306 // Parse the database name. 307 ident, err := p.ParseIdent() 308 if err != nil { 309 return nil, err 310 } 311 stmt.Database = ident 312 313 // Loop through option tokens (DURATION, REPLICATION, SHARD DURATION, DEFAULT, etc.). 314 found := make(map[Token]struct{}) 315 Loop: 316 for { 317 tok, pos, lit := p.ScanIgnoreWhitespace() 318 if _, ok := found[tok]; ok { 319 return nil, &ParseError{ 320 Message: fmt.Sprintf("found duplicate %s option", tok), 321 Pos: pos, 322 } 323 } 324 325 switch tok { 326 case DURATION: 327 d, err := p.ParseDuration() 328 if err != nil { 329 return nil, err 330 } 331 stmt.Duration = &d 332 case REPLICATION: 333 n, err := p.ParseInt(1, math.MaxInt32) 334 if err != nil { 335 return nil, err 336 } 337 stmt.Replication = &n 338 case SHARD: 339 tok, pos, lit := p.ScanIgnoreWhitespace() 340 if tok == DURATION { 341 // Check to see if they used the INF keyword 342 tok, pos, _ := p.ScanIgnoreWhitespace() 343 if tok == INF { 344 return nil, &ParseError{ 345 Message: "invalid duration INF for shard duration", 346 Pos: pos, 347 } 348 } 349 p.Unscan() 350 351 d, err := p.ParseDuration() 352 if err != nil { 353 return nil, err 354 } 355 stmt.ShardGroupDuration = &d 356 } else { 357 return nil, newParseError(tokstr(tok, lit), []string{"DURATION"}, pos) 358 } 359 case DEFAULT: 360 stmt.Default = true 361 default: 362 if len(found) == 0 { 363 return nil, newParseError(tokstr(tok, lit), []string{"DURATION", "REPLICATION", "SHARD", "DEFAULT"}, pos) 364 } 365 p.Unscan() 366 break Loop 367 } 368 found[tok] = struct{}{} 369 } 370 371 return stmt, nil 372 } 373 374 // ParseInt parses a string representing a base 10 integer and returns the number. 375 // It returns an error if the parsed number is outside the range [min, max]. 376 func (p *Parser) ParseInt(min, max int) (int, error) { 377 tok, pos, lit := p.ScanIgnoreWhitespace() 378 if tok != INTEGER { 379 return 0, newParseError(tokstr(tok, lit), []string{"integer"}, pos) 380 } 381 382 // Convert string to int. 383 n, err := strconv.Atoi(lit) 384 if err != nil { 385 return 0, &ParseError{Message: err.Error(), Pos: pos} 386 } else if min > n || n > max { 387 return 0, &ParseError{ 388 Message: fmt.Sprintf("invalid value %d: must be %d <= n <= %d", n, min, max), 389 Pos: pos, 390 } 391 } 392 393 return n, nil 394 } 395 396 // ParseUInt64 parses a string and returns a 64-bit unsigned integer literal. 397 func (p *Parser) ParseUInt64() (uint64, error) { 398 tok, pos, lit := p.ScanIgnoreWhitespace() 399 if tok != INTEGER { 400 return 0, newParseError(tokstr(tok, lit), []string{"integer"}, pos) 401 } 402 403 // Convert string to unsigned 64-bit integer 404 n, err := strconv.ParseUint(lit, 10, 64) 405 if err != nil { 406 return 0, &ParseError{Message: err.Error(), Pos: pos} 407 } 408 409 return uint64(n), nil 410 } 411 412 // ParseDuration parses a string and returns a duration literal. 413 // This function assumes the DURATION token has already been consumed. 414 func (p *Parser) ParseDuration() (time.Duration, error) { 415 tok, pos, lit := p.ScanIgnoreWhitespace() 416 if tok != DURATIONVAL && tok != INF { 417 return 0, newParseError(tokstr(tok, lit), []string{"duration"}, pos) 418 } 419 420 if tok == INF { 421 return 0, nil 422 } 423 424 d, err := ParseDuration(lit) 425 if err != nil { 426 return 0, &ParseError{Message: err.Error(), Pos: pos} 427 } 428 429 return d, nil 430 } 431 432 // ParseIdent parses an identifier. 433 func (p *Parser) ParseIdent() (string, error) { 434 tok, pos, lit := p.ScanIgnoreWhitespace() 435 if tok != IDENT { 436 return "", newParseError(tokstr(tok, lit), []string{"identifier"}, pos) 437 } 438 return lit, nil 439 } 440 441 // ParseIdentList parses a comma delimited list of identifiers. 442 func (p *Parser) ParseIdentList() ([]string, error) { 443 // Parse first (required) identifier. 444 ident, err := p.ParseIdent() 445 if err != nil { 446 return nil, err 447 } 448 idents := []string{ident} 449 450 // Parse remaining (optional) identifiers. 451 for { 452 if tok, _, _ := p.ScanIgnoreWhitespace(); tok != COMMA { 453 p.Unscan() 454 return idents, nil 455 } 456 457 if ident, err = p.ParseIdent(); err != nil { 458 return nil, err 459 } 460 461 idents = append(idents, ident) 462 } 463 } 464 465 // parseSegmentedIdents parses a segmented identifiers. 466 // e.g., "db"."rp".measurement or "db"..measurement 467 func (p *Parser) parseSegmentedIdents() ([]string, error) { 468 ident, err := p.ParseIdent() 469 if err != nil { 470 return nil, err 471 } 472 idents := []string{ident} 473 474 // Parse remaining (optional) identifiers. 475 for { 476 if tok, _, _ := p.Scan(); tok != DOT { 477 // No more segments so we're done. 478 p.Unscan() 479 break 480 } 481 482 if ch := p.peekRune(); ch == '/' { 483 // Next segment is a regex so we're done. 484 break 485 } else if ch == ':' { 486 // Next segment is context-specific so let caller handle it. 487 break 488 } else if ch == '.' { 489 // Add an empty identifier. 490 idents = append(idents, "") 491 continue 492 } 493 494 // Parse the next identifier. 495 if ident, err = p.ParseIdent(); err != nil { 496 return nil, err 497 } 498 499 idents = append(idents, ident) 500 } 501 502 if len(idents) > 3 { 503 msg := fmt.Sprintf("too many segments in %s", QuoteIdent(idents...)) 504 return nil, &ParseError{Message: msg} 505 } 506 507 return idents, nil 508 } 509 510 // parseString parses a string. 511 func (p *Parser) parseString() (string, error) { 512 tok, pos, lit := p.ScanIgnoreWhitespace() 513 if tok != STRING { 514 return "", newParseError(tokstr(tok, lit), []string{"string"}, pos) 515 } 516 return lit, nil 517 } 518 519 // parseStringList parses a list of strings separated by commas. 520 func (p *Parser) parseStringList() ([]string, error) { 521 // Parse first (required) string. 522 str, err := p.parseString() 523 if err != nil { 524 return nil, err 525 } 526 strs := []string{str} 527 528 // Parse remaining (optional) strings. 529 for { 530 if tok, _, _ := p.ScanIgnoreWhitespace(); tok != COMMA { 531 p.Unscan() 532 return strs, nil 533 } 534 535 if str, err = p.parseString(); err != nil { 536 return nil, err 537 } 538 539 strs = append(strs, str) 540 } 541 } 542 543 // parseRevokeStatement parses a string and returns a revoke statement. 544 // This function assumes the REVOKE token has already been consumed. 545 func (p *Parser) parseRevokeStatement() (Statement, error) { 546 // Parse the privilege to be revoked. 547 priv, err := p.parsePrivilege() 548 if err != nil { 549 return nil, err 550 } 551 552 // Check for ON or FROM clauses. 553 tok, pos, lit := p.ScanIgnoreWhitespace() 554 if tok == ON { 555 stmt, err := p.parseRevokeOnStatement() 556 if err != nil { 557 return nil, err 558 } 559 stmt.Privilege = priv 560 return stmt, nil 561 } else if tok == FROM { 562 // Admin privilege is only revoked on ALL PRIVILEGES. 563 if priv != AllPrivileges { 564 return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos) 565 } 566 return p.parseRevokeAdminStatement() 567 } 568 569 // Only ON or FROM clauses are allowed after privilege. 570 if priv == AllPrivileges { 571 return nil, newParseError(tokstr(tok, lit), []string{"ON", "FROM"}, pos) 572 } 573 return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos) 574 } 575 576 // parseRevokeOnStatement parses a string and returns a revoke statement. 577 // This function assumes the [PRIVILEGE] ON tokens have already been consumed. 578 func (p *Parser) parseRevokeOnStatement() (*RevokeStatement, error) { 579 stmt := &RevokeStatement{} 580 581 // Parse the name of the database. 582 lit, err := p.ParseIdent() 583 if err != nil { 584 return nil, err 585 } 586 stmt.On = lit 587 588 // Parse FROM clause. 589 tok, pos, lit := p.ScanIgnoreWhitespace() 590 591 // Check for required FROM token. 592 if tok != FROM { 593 return nil, newParseError(tokstr(tok, lit), []string{"FROM"}, pos) 594 } 595 596 // Parse the name of the user. 597 lit, err = p.ParseIdent() 598 if err != nil { 599 return nil, err 600 } 601 stmt.User = lit 602 603 return stmt, nil 604 } 605 606 // parseRevokeAdminStatement parses a string and returns a revoke admin statement. 607 // This function assumes the ALL [PRVILEGES] FROM token has already been consumed. 608 func (p *Parser) parseRevokeAdminStatement() (*RevokeAdminStatement, error) { 609 // Admin privilege is always false when revoke admin clause is called. 610 stmt := &RevokeAdminStatement{} 611 612 // Parse the name of the user. 613 lit, err := p.ParseIdent() 614 if err != nil { 615 return nil, err 616 } 617 stmt.User = lit 618 619 return stmt, nil 620 } 621 622 // parseGrantStatement parses a string and returns a grant statement. 623 // This function assumes the GRANT token has already been consumed. 624 func (p *Parser) parseGrantStatement() (Statement, error) { 625 // Parse the privilege to be granted. 626 priv, err := p.parsePrivilege() 627 if err != nil { 628 return nil, err 629 } 630 631 // Check for ON or TO clauses. 632 tok, pos, lit := p.ScanIgnoreWhitespace() 633 if tok == ON { 634 stmt, err := p.parseGrantOnStatement() 635 if err != nil { 636 return nil, err 637 } 638 stmt.Privilege = priv 639 return stmt, nil 640 } else if tok == TO { 641 // Admin privilege is only granted on ALL PRIVILEGES. 642 if priv != AllPrivileges { 643 return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos) 644 } 645 return p.parseGrantAdminStatement() 646 } 647 648 // Only ON or TO clauses are allowed after privilege. 649 if priv == AllPrivileges { 650 return nil, newParseError(tokstr(tok, lit), []string{"ON", "TO"}, pos) 651 } 652 return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos) 653 } 654 655 // parseGrantOnStatement parses a string and returns a grant statement. 656 // This function assumes the [PRIVILEGE] ON tokens have already been consumed. 657 func (p *Parser) parseGrantOnStatement() (*GrantStatement, error) { 658 stmt := &GrantStatement{} 659 660 // Parse the name of the database. 661 lit, err := p.ParseIdent() 662 if err != nil { 663 return nil, err 664 } 665 stmt.On = lit 666 667 // Parse TO clause. 668 tok, pos, lit := p.ScanIgnoreWhitespace() 669 670 // Check for required TO token. 671 if tok != TO { 672 return nil, newParseError(tokstr(tok, lit), []string{"TO"}, pos) 673 } 674 675 // Parse the name of the user. 676 lit, err = p.ParseIdent() 677 if err != nil { 678 return nil, err 679 } 680 stmt.User = lit 681 682 return stmt, nil 683 } 684 685 // parseGrantAdminStatement parses a string and returns a grant admin statement. 686 // This function assumes the ALL [PRVILEGES] TO tokens have already been consumed. 687 func (p *Parser) parseGrantAdminStatement() (*GrantAdminStatement, error) { 688 // Admin privilege is always true when grant admin clause is called. 689 stmt := &GrantAdminStatement{} 690 691 // Parse the name of the user. 692 lit, err := p.ParseIdent() 693 if err != nil { 694 return nil, err 695 } 696 stmt.User = lit 697 698 return stmt, nil 699 } 700 701 // parsePrivilege parses a string and returns a Privilege. 702 func (p *Parser) parsePrivilege() (Privilege, error) { 703 tok, pos, lit := p.ScanIgnoreWhitespace() 704 switch tok { 705 case READ: 706 return ReadPrivilege, nil 707 case WRITE: 708 return WritePrivilege, nil 709 case ALL: 710 // Consume optional PRIVILEGES token 711 tok, pos, lit = p.ScanIgnoreWhitespace() 712 if tok != PRIVILEGES { 713 p.Unscan() 714 } 715 return AllPrivileges, nil 716 } 717 return 0, newParseError(tokstr(tok, lit), []string{"READ", "WRITE", "ALL [PRIVILEGES]"}, pos) 718 } 719 720 // parseSelectStatement parses a select string and returns a Statement AST object. 721 // This function assumes the SELECT token has already been consumed. 722 func (p *Parser) parseSelectStatement(tr targetRequirement) (*SelectStatement, error) { 723 stmt := &SelectStatement{} 724 var err error 725 726 // Parse fields: "FIELD+". 727 if stmt.Fields, err = p.parseFields(); err != nil { 728 return nil, err 729 } 730 731 // Parse target: "INTO" 732 if stmt.Target, err = p.parseTarget(tr); err != nil { 733 return nil, err 734 } 735 736 // Parse source: "FROM". 737 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != FROM { 738 return nil, newParseError(tokstr(tok, lit), []string{"FROM"}, pos) 739 } 740 if stmt.Sources, err = p.parseSources(true); err != nil { 741 return nil, err 742 } 743 744 // Parse condition: "WHERE EXPR". 745 if stmt.Condition, err = p.parseCondition(); err != nil { 746 return nil, err 747 } 748 749 // Parse dimensions: "GROUP BY DIMENSION+". 750 if stmt.Dimensions, err = p.parseDimensions(); err != nil { 751 return nil, err 752 } 753 754 // Parse fill options: "fill(<option>)" 755 if stmt.Fill, stmt.FillValue, err = p.parseFill(); err != nil { 756 return nil, err 757 } 758 759 // Parse sort: "ORDER BY FIELD+". 760 if stmt.SortFields, err = p.parseOrderBy(); err != nil { 761 return nil, err 762 } 763 764 // Parse limit: "LIMIT <n>". 765 if stmt.Limit, err = p.ParseOptionalTokenAndInt(LIMIT); err != nil { 766 return nil, err 767 } 768 769 // Parse offset: "OFFSET <n>". 770 if stmt.Offset, err = p.ParseOptionalTokenAndInt(OFFSET); err != nil { 771 return nil, err 772 } 773 774 // Parse series limit: "SLIMIT <n>". 775 if stmt.SLimit, err = p.ParseOptionalTokenAndInt(SLIMIT); err != nil { 776 return nil, err 777 } 778 779 // Parse series offset: "SOFFSET <n>". 780 if stmt.SOffset, err = p.ParseOptionalTokenAndInt(SOFFSET); err != nil { 781 return nil, err 782 } 783 784 // Parse timezone: "TZ(<timezone>)". 785 if stmt.Location, err = p.parseLocation(); err != nil { 786 return nil, err 787 } 788 789 // Set if the query is a raw data query or one with an aggregate 790 stmt.IsRawQuery = true 791 WalkFunc(stmt.Fields, func(n Node) { 792 if _, ok := n.(*Call); ok { 793 stmt.IsRawQuery = false 794 } 795 }) 796 797 return stmt, nil 798 } 799 800 // targetRequirement specifies whether or not a target clause is required. 801 type targetRequirement int 802 803 const ( 804 targetRequired targetRequirement = iota 805 targetNotRequired 806 targetSubquery 807 ) 808 809 // parseTarget parses a string and returns a Target. 810 func (p *Parser) parseTarget(tr targetRequirement) (*Target, error) { 811 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != INTO { 812 if tr == targetRequired { 813 return nil, newParseError(tokstr(tok, lit), []string{"INTO"}, pos) 814 } 815 p.Unscan() 816 return nil, nil 817 } 818 819 // db, rp, and / or measurement 820 idents, err := p.parseSegmentedIdents() 821 if err != nil { 822 return nil, err 823 } 824 825 if len(idents) < 3 { 826 // Check for source measurement reference. 827 if ch := p.peekRune(); ch == ':' { 828 if err := p.parseTokens([]Token{COLON, MEASUREMENT}); err != nil { 829 return nil, err 830 } 831 // Append empty measurement name. 832 idents = append(idents, "") 833 } 834 } 835 836 t := &Target{Measurement: &Measurement{IsTarget: true}} 837 838 switch len(idents) { 839 case 1: 840 t.Measurement.Name = idents[0] 841 case 2: 842 t.Measurement.RetentionPolicy = idents[0] 843 t.Measurement.Name = idents[1] 844 case 3: 845 t.Measurement.Database = idents[0] 846 t.Measurement.RetentionPolicy = idents[1] 847 t.Measurement.Name = idents[2] 848 } 849 850 return t, nil 851 } 852 853 // parseDeleteStatement parses a string and returns a delete statement. 854 // This function assumes the DELETE token has already been consumed. 855 func (p *Parser) parseDeleteStatement() (Statement, error) { 856 stmt := &DeleteSeriesStatement{} 857 var err error 858 859 tok, pos, lit := p.ScanIgnoreWhitespace() 860 861 if tok == FROM { 862 // Parse source. 863 if stmt.Sources, err = p.parseSources(false); err != nil { 864 return nil, err 865 } 866 867 var err error 868 WalkFunc(stmt.Sources, func(n Node) { 869 if t, ok := n.(*Measurement); ok { 870 // Don't allow database or retention policy in from clause for delete 871 // statement. They apply to the selected database across all retention 872 // policies. 873 if t.Database != "" { 874 err = &ParseError{Message: "database not supported"} 875 } 876 if t.RetentionPolicy != "" { 877 err = &ParseError{Message: "retention policy not supported"} 878 } 879 } 880 }) 881 if err != nil { 882 return nil, err 883 } 884 885 } else { 886 p.Unscan() 887 } 888 889 // Parse condition: "WHERE EXPR". 890 if stmt.Condition, err = p.parseCondition(); err != nil { 891 return nil, err 892 } 893 894 // If they didn't provide a FROM or a WHERE, this query is invalid 895 if stmt.Condition == nil && stmt.Sources == nil { 896 return nil, newParseError(tokstr(tok, lit), []string{"FROM", "WHERE"}, pos) 897 } 898 899 return stmt, nil 900 } 901 902 // parseShowSeriesStatement parses a string and returns a Statement. 903 // This function assumes the "SHOW SERIES" tokens have already been consumed. 904 func (p *Parser) parseShowSeriesStatement() (Statement, error) { 905 var exactCardinality bool 906 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == EXACT { 907 exactCardinality = true 908 } else { 909 p.Unscan() 910 } 911 912 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == CARDINALITY { 913 return p.parseShowSeriesCardinalityStatement(exactCardinality) 914 } 915 p.Unscan() 916 917 // Handle SHOW SERIES statments. 918 919 stmt := &ShowSeriesStatement{} 920 var err error 921 922 // Parse optional ON clause. 923 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON { 924 // Parse the database. 925 stmt.Database, err = p.ParseIdent() 926 if err != nil { 927 return nil, err 928 } 929 } else { 930 p.Unscan() 931 } 932 933 // Parse optional FROM. 934 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FROM { 935 if stmt.Sources, err = p.parseSources(false); err != nil { 936 return nil, err 937 } 938 } else { 939 p.Unscan() 940 } 941 942 // Parse condition: "WHERE EXPR". 943 if stmt.Condition, err = p.parseCondition(); err != nil { 944 return nil, err 945 } 946 947 // Parse sort: "ORDER BY FIELD+". 948 if stmt.SortFields, err = p.parseOrderBy(); err != nil { 949 return nil, err 950 } 951 952 // Parse limit: "LIMIT <n>". 953 if stmt.Limit, err = p.ParseOptionalTokenAndInt(LIMIT); err != nil { 954 return nil, err 955 } 956 957 // Parse offset: "OFFSET <n>". 958 if stmt.Offset, err = p.ParseOptionalTokenAndInt(OFFSET); err != nil { 959 return nil, err 960 } 961 962 return stmt, nil 963 } 964 965 // This function assumes the "SHOW SERIES EXACT CARDINALITY" or the 966 // "SHOW SERIES CARDINALITY" tokens have already been consumed. 967 func (p *Parser) parseShowSeriesCardinalityStatement(exact bool) (Statement, error) { 968 var err error 969 stmt := &ShowSeriesCardinalityStatement{Exact: exact} 970 971 // Parse optional ON clause. 972 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON { 973 if stmt.Database, err = p.ParseIdent(); err != nil { 974 return nil, err 975 } 976 } else { 977 p.Unscan() 978 } 979 980 // Parse optional FROM. 981 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FROM { 982 if stmt.Sources, err = p.parseSources(false); err != nil { 983 return nil, err 984 } 985 } else { 986 p.Unscan() 987 } 988 989 // Parse condition: "WHERE EXPR". 990 if stmt.Condition, err = p.parseCondition(); err != nil { 991 return nil, err 992 } 993 994 // Parse dimensions: "GROUP BY DIMENSION+". 995 if stmt.Dimensions, err = p.parseDimensions(); err != nil { 996 return nil, err 997 } 998 999 // Parse limit & offset: "LIMIT <n>", "OFFSET <n>". 1000 if stmt.Limit, err = p.ParseOptionalTokenAndInt(LIMIT); err != nil { 1001 return nil, err 1002 } else if stmt.Offset, err = p.ParseOptionalTokenAndInt(OFFSET); err != nil { 1003 return nil, err 1004 } 1005 1006 return stmt, nil 1007 } 1008 1009 // This function assumes the "SHOW MEASUREMENT" tokens have already been consumed. 1010 func (p *Parser) parseShowMeasurementCardinalityStatement(exact bool) (Statement, error) { 1011 stmt := &ShowMeasurementCardinalityStatement{Exact: exact} 1012 1013 if stmt.Exact { 1014 // Parse remaining CARDINALITY token 1015 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != CARDINALITY { 1016 return nil, newParseError(tokstr(tok, lit), []string{"CARDINALITY"}, pos) 1017 } 1018 } 1019 1020 // Parse optional ON clause. 1021 var err error 1022 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON { 1023 if stmt.Database, err = p.ParseIdent(); err != nil { 1024 return nil, err 1025 } 1026 } else { 1027 p.Unscan() 1028 } 1029 1030 // Parse optional FROM. 1031 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FROM { 1032 if stmt.Sources, err = p.parseSources(false); err != nil { 1033 return nil, err 1034 } 1035 } else { 1036 p.Unscan() 1037 } 1038 1039 // Parse condition: "WHERE EXPR". 1040 if stmt.Condition, err = p.parseCondition(); err != nil { 1041 return nil, err 1042 } 1043 1044 // Parse dimensions: "GROUP BY DIMENSION+". 1045 if stmt.Dimensions, err = p.parseDimensions(); err != nil { 1046 return nil, err 1047 } 1048 1049 // Parse limit & offset: "LIMIT <n>", "OFFSET <n>". 1050 if stmt.Limit, err = p.ParseOptionalTokenAndInt(LIMIT); err != nil { 1051 return nil, err 1052 } else if stmt.Offset, err = p.ParseOptionalTokenAndInt(OFFSET); err != nil { 1053 return nil, err 1054 } 1055 1056 return stmt, nil 1057 } 1058 1059 // parseShowMeasurementsStatement parses a string and returns a Statement. 1060 // This function assumes the "SHOW MEASUREMENTS" tokens have already been consumed. 1061 func (p *Parser) parseShowMeasurementsStatement() (*ShowMeasurementsStatement, error) { 1062 stmt := &ShowMeasurementsStatement{} 1063 var err error 1064 1065 // Parse optional ON clause. 1066 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON { 1067 // Parse the database. 1068 stmt.Database, err = p.ParseIdent() 1069 if err != nil { 1070 return nil, err 1071 } 1072 } else { 1073 p.Unscan() 1074 } 1075 1076 // Parse optional WITH clause. 1077 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == WITH { 1078 // Parse required MEASUREMENT token. 1079 if err := p.parseTokens([]Token{MEASUREMENT}); err != nil { 1080 return nil, err 1081 } 1082 1083 // Parse required operator: = or =~. 1084 tok, pos, lit := p.ScanIgnoreWhitespace() 1085 switch tok { 1086 case EQ, EQREGEX: 1087 // Parse required source (measurement name or regex). 1088 if stmt.Source, err = p.parseSource(false); err != nil { 1089 return nil, err 1090 } 1091 default: 1092 return nil, newParseError(tokstr(tok, lit), []string{"=", "=~"}, pos) 1093 } 1094 } else { 1095 // Not a WITH clause so put the token back. 1096 p.Unscan() 1097 } 1098 1099 // Parse condition: "WHERE EXPR". 1100 if stmt.Condition, err = p.parseCondition(); err != nil { 1101 return nil, err 1102 } 1103 1104 // Parse sort: "ORDER BY FIELD+". 1105 if stmt.SortFields, err = p.parseOrderBy(); err != nil { 1106 return nil, err 1107 } 1108 1109 // Parse limit: "LIMIT <n>". 1110 if stmt.Limit, err = p.ParseOptionalTokenAndInt(LIMIT); err != nil { 1111 return nil, err 1112 } 1113 1114 // Parse offset: "OFFSET <n>". 1115 if stmt.Offset, err = p.ParseOptionalTokenAndInt(OFFSET); err != nil { 1116 return nil, err 1117 } 1118 1119 return stmt, nil 1120 } 1121 1122 // parseShowQueriesStatement parses a string and returns a ShowQueriesStatement. 1123 // This function assumes the "SHOW QUERIES" tokens have been consumed. 1124 func (p *Parser) parseShowQueriesStatement() (*ShowQueriesStatement, error) { 1125 return &ShowQueriesStatement{}, nil 1126 } 1127 1128 // parseShowRetentionPoliciesStatement parses a string and returns a ShowRetentionPoliciesStatement. 1129 // This function assumes the "SHOW RETENTION POLICIES" tokens have been consumed. 1130 func (p *Parser) parseShowRetentionPoliciesStatement() (*ShowRetentionPoliciesStatement, error) { 1131 stmt := &ShowRetentionPoliciesStatement{} 1132 1133 // Expect an "ON" keyword. 1134 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON { 1135 // Parse the database. 1136 ident, err := p.ParseIdent() 1137 if err != nil { 1138 return nil, err 1139 } 1140 stmt.Database = ident 1141 } else { 1142 p.Unscan() 1143 } 1144 1145 return stmt, nil 1146 } 1147 1148 // This function assumes the "SHOW TAG KEY" tokens have already been consumed. 1149 func (p *Parser) parseShowTagKeyCardinalityStatement() (Statement, error) { 1150 var err error 1151 var exactCardinality bool 1152 requiredTokens := []string{"EXACT", "CARDINALITY"} 1153 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == EXACT { 1154 exactCardinality = true 1155 requiredTokens = requiredTokens[1:] 1156 } else { 1157 p.Unscan() 1158 } 1159 1160 stmt := &ShowTagKeyCardinalityStatement{Exact: exactCardinality} 1161 1162 // Parse remaining CARDINALITY token 1163 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != CARDINALITY { 1164 return nil, newParseError(tokstr(tok, lit), requiredTokens, pos) 1165 } 1166 1167 // Parse optional ON clause. 1168 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON { 1169 if stmt.Database, err = p.ParseIdent(); err != nil { 1170 return nil, err 1171 } 1172 } else { 1173 p.Unscan() 1174 } 1175 1176 // Parse optional FROM. 1177 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FROM { 1178 if stmt.Sources, err = p.parseSources(false); err != nil { 1179 return nil, err 1180 } 1181 } else { 1182 p.Unscan() 1183 } 1184 1185 // Parse condition: "WHERE EXPR". 1186 if stmt.Condition, err = p.parseCondition(); err != nil { 1187 return nil, err 1188 } 1189 1190 // Parse dimensions: "GROUP BY DIMENSION+". 1191 if stmt.Dimensions, err = p.parseDimensions(); err != nil { 1192 return nil, err 1193 } 1194 1195 // Parse limit & offset: "LIMIT <n>", "OFFSET <n>". 1196 if stmt.Limit, err = p.ParseOptionalTokenAndInt(LIMIT); err != nil { 1197 return nil, err 1198 } else if stmt.Offset, err = p.ParseOptionalTokenAndInt(OFFSET); err != nil { 1199 return nil, err 1200 } 1201 1202 return stmt, nil 1203 } 1204 1205 // parseShowTagKeysStatement parses a string and returns a Statement. 1206 // This function assumes the "SHOW TAG KEYS" tokens have already been consumed. 1207 func (p *Parser) parseShowTagKeysStatement() (*ShowTagKeysStatement, error) { 1208 stmt := &ShowTagKeysStatement{} 1209 var err error 1210 1211 // Parse optional ON clause. 1212 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON { 1213 // Parse the database. 1214 stmt.Database, err = p.ParseIdent() 1215 if err != nil { 1216 return nil, err 1217 } 1218 } else { 1219 p.Unscan() 1220 } 1221 1222 // Parse optional source. 1223 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FROM { 1224 if stmt.Sources, err = p.parseSources(false); err != nil { 1225 return nil, err 1226 } 1227 } else { 1228 p.Unscan() 1229 } 1230 1231 // Parse condition: "WHERE EXPR". 1232 if stmt.Condition, err = p.parseCondition(); err != nil { 1233 return nil, err 1234 } 1235 1236 // Parse sort: "ORDER BY FIELD+". 1237 if stmt.SortFields, err = p.parseOrderBy(); err != nil { 1238 return nil, err 1239 } 1240 1241 // Parse limit: "LIMIT <n>". 1242 if stmt.Limit, err = p.ParseOptionalTokenAndInt(LIMIT); err != nil { 1243 return nil, err 1244 } 1245 1246 // Parse offset: "OFFSET <n>". 1247 if stmt.Offset, err = p.ParseOptionalTokenAndInt(OFFSET); err != nil { 1248 return nil, err 1249 } 1250 1251 // Parse series limit: "SLIMIT <n>". 1252 if stmt.SLimit, err = p.ParseOptionalTokenAndInt(SLIMIT); err != nil { 1253 return nil, err 1254 } 1255 1256 // Parse series offset: "SOFFSET <n>". 1257 if stmt.SOffset, err = p.ParseOptionalTokenAndInt(SOFFSET); err != nil { 1258 return nil, err 1259 } 1260 1261 return stmt, nil 1262 } 1263 1264 // parseShowTagValuesStatement parses a string and returns a Statement. 1265 // This function assumes the "SHOW TAG VALUES" tokens have already been consumed. 1266 func (p *Parser) parseShowTagValuesStatement() (Statement, error) { 1267 stmt := &ShowTagValuesStatement{} 1268 var err error 1269 1270 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == EXACT { 1271 return p.parseShowTagValuesCardinalityStatement(true) 1272 } else if tok == CARDINALITY { 1273 return p.parseShowTagValuesCardinalityStatement(false) 1274 } 1275 p.Unscan() 1276 1277 // Parse optional ON clause. 1278 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON { 1279 // Parse the database. 1280 stmt.Database, err = p.ParseIdent() 1281 if err != nil { 1282 return nil, err 1283 } 1284 } else { 1285 p.Unscan() 1286 } 1287 1288 // Parse optional source. 1289 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FROM { 1290 if stmt.Sources, err = p.parseSources(false); err != nil { 1291 return nil, err 1292 } 1293 } else { 1294 p.Unscan() 1295 } 1296 1297 // Parse required WITH KEY. 1298 if stmt.Op, stmt.TagKeyExpr, err = p.parseTagKeyExpr(); err != nil { 1299 return nil, err 1300 } 1301 1302 // Parse condition: "WHERE EXPR". 1303 if stmt.Condition, err = p.parseCondition(); err != nil { 1304 return nil, err 1305 } 1306 1307 // Parse sort: "ORDER BY FIELD+". 1308 if stmt.SortFields, err = p.parseOrderBy(); err != nil { 1309 return nil, err 1310 } 1311 1312 // Parse limit: "LIMIT <n>". 1313 if stmt.Limit, err = p.ParseOptionalTokenAndInt(LIMIT); err != nil { 1314 return nil, err 1315 } 1316 1317 // Parse offset: "OFFSET <n>". 1318 if stmt.Offset, err = p.ParseOptionalTokenAndInt(OFFSET); err != nil { 1319 return nil, err 1320 } 1321 1322 return stmt, nil 1323 } 1324 1325 // This function assumes the "SHOW TAG VALUES" tokens have already been consumed. 1326 func (p *Parser) parseShowTagValuesCardinalityStatement(exact bool) (Statement, error) { 1327 var err error 1328 stmt := &ShowTagValuesCardinalityStatement{Exact: exact} 1329 1330 if stmt.Exact { 1331 // Parse remaining CARDINALITY token 1332 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != CARDINALITY { 1333 return nil, newParseError(tokstr(tok, lit), []string{"CARDINALITY"}, pos) 1334 } 1335 } 1336 1337 // Parse optional ON clause. 1338 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON { 1339 if stmt.Database, err = p.ParseIdent(); err != nil { 1340 return nil, err 1341 } 1342 } else { 1343 p.Unscan() 1344 } 1345 1346 // Parse optional FROM. 1347 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FROM { 1348 if stmt.Sources, err = p.parseSources(false); err != nil { 1349 return nil, err 1350 } 1351 } else { 1352 p.Unscan() 1353 } 1354 1355 // Parse required WITH KEY. 1356 if stmt.Op, stmt.TagKeyExpr, err = p.parseTagKeyExpr(); err != nil { 1357 return nil, err 1358 } 1359 1360 // Parse condition: "WHERE EXPR". 1361 if stmt.Condition, err = p.parseCondition(); err != nil { 1362 return nil, err 1363 } 1364 1365 // Parse dimensions: "GROUP BY DIMENSION+". 1366 if stmt.Dimensions, err = p.parseDimensions(); err != nil { 1367 return nil, err 1368 } 1369 1370 // Parse limit & offset: "LIMIT <n>", "OFFSET <n>". 1371 if stmt.Limit, err = p.ParseOptionalTokenAndInt(LIMIT); err != nil { 1372 return nil, err 1373 } else if stmt.Offset, err = p.ParseOptionalTokenAndInt(OFFSET); err != nil { 1374 return nil, err 1375 } 1376 1377 return stmt, nil 1378 } 1379 1380 // parseTagKeys parses a string and returns a list of tag keys. 1381 func (p *Parser) parseTagKeyExpr() (Token, Literal, error) { 1382 var err error 1383 1384 // Parse required WITH KEY tokens. 1385 if err := p.parseTokens([]Token{WITH, KEY}); err != nil { 1386 return 0, nil, err 1387 } 1388 1389 // Parse required IN, EQ, or EQREGEX token. 1390 tok, pos, lit := p.ScanIgnoreWhitespace() 1391 if tok == IN { 1392 // Parse required ( token. 1393 if tok, pos, lit = p.ScanIgnoreWhitespace(); tok != LPAREN { 1394 return 0, nil, newParseError(tokstr(tok, lit), []string{"("}, pos) 1395 } 1396 1397 // Parse tag key list. 1398 var tagKeys []string 1399 if tagKeys, err = p.ParseIdentList(); err != nil { 1400 return 0, nil, err 1401 } 1402 1403 // Parse required ) token. 1404 if tok, pos, lit = p.ScanIgnoreWhitespace(); tok != RPAREN { 1405 return 0, nil, newParseError(tokstr(tok, lit), []string{")"}, pos) 1406 } 1407 return IN, &ListLiteral{Vals: tagKeys}, nil 1408 } else if tok == EQ || tok == NEQ { 1409 // Parse required tag key. 1410 ident, err := p.ParseIdent() 1411 if err != nil { 1412 return 0, nil, err 1413 } 1414 return tok, &StringLiteral{Val: ident}, nil 1415 } else if tok == EQREGEX || tok == NEQREGEX { 1416 re, err := p.parseRegex() 1417 if err != nil { 1418 return 0, nil, err 1419 } else if re == nil { 1420 // parseRegex can return an empty type, but we need it to be present 1421 tok, pos, lit := p.ScanIgnoreWhitespace() 1422 return 0, nil, newParseError(tokstr(tok, lit), []string{"regex"}, pos) 1423 } 1424 return tok, re, nil 1425 } 1426 return 0, nil, newParseError(tokstr(tok, lit), []string{"IN", "=", "=~"}, pos) 1427 } 1428 1429 // parseShowUsersStatement parses a string and returns a ShowUsersStatement. 1430 // This function assumes the "SHOW USERS" tokens have been consumed. 1431 func (p *Parser) parseShowUsersStatement() (*ShowUsersStatement, error) { 1432 return &ShowUsersStatement{}, nil 1433 } 1434 1435 // parseShowSubscriptionsStatement parses a string and returns a ShowSubscriptionsStatement 1436 // This function assumes the "SHOW SUBSCRIPTIONS" tokens have been consumed. 1437 func (p *Parser) parseShowSubscriptionsStatement() (*ShowSubscriptionsStatement, error) { 1438 stmt := &ShowSubscriptionsStatement{} 1439 return stmt, nil 1440 } 1441 1442 // This function assumes the "SHOW FIELD KEY" tokens have already been consumed. 1443 func (p *Parser) parseShowFieldKeyCardinalityStatement() (Statement, error) { 1444 var err error 1445 var exactCardinality bool 1446 requiredTokens := []string{"EXACT", "CARDINALITY"} 1447 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == EXACT { 1448 exactCardinality = true 1449 requiredTokens = requiredTokens[1:] 1450 } else { 1451 p.Unscan() 1452 } 1453 1454 stmt := &ShowFieldKeyCardinalityStatement{Exact: exactCardinality} 1455 1456 // Parse remaining CARDINALITY token 1457 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != CARDINALITY { 1458 return nil, newParseError(tokstr(tok, lit), requiredTokens, pos) 1459 } 1460 1461 // Parse optional ON clause. 1462 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON { 1463 if stmt.Database, err = p.ParseIdent(); err != nil { 1464 return nil, err 1465 } 1466 } else { 1467 p.Unscan() 1468 } 1469 1470 // Parse optional FROM. 1471 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FROM { 1472 if stmt.Sources, err = p.parseSources(false); err != nil { 1473 return nil, err 1474 } 1475 } else { 1476 p.Unscan() 1477 } 1478 1479 // Parse condition: "WHERE EXPR". 1480 if stmt.Condition, err = p.parseCondition(); err != nil { 1481 return nil, err 1482 } 1483 1484 // Parse dimensions: "GROUP BY DIMENSION+". 1485 if stmt.Dimensions, err = p.parseDimensions(); err != nil { 1486 return nil, err 1487 } 1488 1489 // Parse limit & offset: "LIMIT <n>", "OFFSET <n>". 1490 if stmt.Limit, err = p.ParseOptionalTokenAndInt(LIMIT); err != nil { 1491 return nil, err 1492 } else if stmt.Offset, err = p.ParseOptionalTokenAndInt(OFFSET); err != nil { 1493 return nil, err 1494 } 1495 1496 return stmt, nil 1497 } 1498 1499 // parseShowFieldKeysStatement parses a string and returns a Statement. 1500 // This function assumes the "SHOW FIELD KEYS" tokens have already been consumed. 1501 func (p *Parser) parseShowFieldKeysStatement() (*ShowFieldKeysStatement, error) { 1502 stmt := &ShowFieldKeysStatement{} 1503 var err error 1504 1505 // Parse optional ON clause. 1506 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ON { 1507 // Parse the database. 1508 stmt.Database, err = p.ParseIdent() 1509 if err != nil { 1510 return nil, err 1511 } 1512 } else { 1513 p.Unscan() 1514 } 1515 1516 // Parse optional source. 1517 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FROM { 1518 if stmt.Sources, err = p.parseSources(false); err != nil { 1519 return nil, err 1520 } 1521 } else { 1522 p.Unscan() 1523 } 1524 1525 // Parse sort: "ORDER BY FIELD+". 1526 if stmt.SortFields, err = p.parseOrderBy(); err != nil { 1527 return nil, err 1528 } 1529 1530 // Parse limit: "LIMIT <n>". 1531 if stmt.Limit, err = p.ParseOptionalTokenAndInt(LIMIT); err != nil { 1532 return nil, err 1533 } 1534 1535 // Parse offset: "OFFSET <n>". 1536 if stmt.Offset, err = p.ParseOptionalTokenAndInt(OFFSET); err != nil { 1537 return nil, err 1538 } 1539 1540 return stmt, nil 1541 } 1542 1543 // parseDropMeasurementStatement parses a string and returns a DropMeasurementStatement. 1544 // This function assumes the "DROP MEASUREMENT" tokens have already been consumed. 1545 func (p *Parser) parseDropMeasurementStatement() (*DropMeasurementStatement, error) { 1546 stmt := &DropMeasurementStatement{} 1547 1548 // Parse the name of the measurement to be dropped. 1549 lit, err := p.ParseIdent() 1550 if err != nil { 1551 return nil, err 1552 } 1553 stmt.Name = lit 1554 1555 return stmt, nil 1556 } 1557 1558 // parseDropSeriesStatement parses a string and returns a DropSeriesStatement. 1559 // This function assumes the "DROP SERIES" tokens have already been consumed. 1560 func (p *Parser) parseDropSeriesStatement() (*DropSeriesStatement, error) { 1561 stmt := &DropSeriesStatement{} 1562 var err error 1563 1564 tok, pos, lit := p.ScanIgnoreWhitespace() 1565 1566 if tok == FROM { 1567 // Parse source. 1568 if stmt.Sources, err = p.parseSources(false); err != nil { 1569 return nil, err 1570 } 1571 1572 var err error 1573 WalkFunc(stmt.Sources, func(n Node) { 1574 if t, ok := n.(*Measurement); ok { 1575 // Don't allow database or retention policy in from clause for delete 1576 // statement. They apply to the selected database across all retention 1577 // policies. 1578 if t.Database != "" { 1579 err = &ParseError{Message: "database not supported"} 1580 } 1581 if t.RetentionPolicy != "" { 1582 err = &ParseError{Message: "retention policy not supported"} 1583 } 1584 } 1585 }) 1586 if err != nil { 1587 return nil, err 1588 } 1589 } else { 1590 p.Unscan() 1591 } 1592 1593 // Parse condition: "WHERE EXPR". 1594 if stmt.Condition, err = p.parseCondition(); err != nil { 1595 return nil, err 1596 } 1597 1598 // If they didn't provide a FROM or a WHERE, this query is invalid 1599 if stmt.Condition == nil && stmt.Sources == nil { 1600 return nil, newParseError(tokstr(tok, lit), []string{"FROM", "WHERE"}, pos) 1601 } 1602 1603 return stmt, nil 1604 } 1605 1606 // parseDropShardStatement parses a string and returns a 1607 // DropShardStatement. This function assumes the "DROP SHARD" tokens 1608 // have already been consumed. 1609 func (p *Parser) parseDropShardStatement() (*DropShardStatement, error) { 1610 var err error 1611 stmt := &DropShardStatement{} 1612 1613 // Parse the ID of the shard to be dropped. 1614 if stmt.ID, err = p.ParseUInt64(); err != nil { 1615 return nil, err 1616 } 1617 return stmt, nil 1618 } 1619 1620 // parseShowContinuousQueriesStatement parses a string and returns a ShowContinuousQueriesStatement. 1621 // This function assumes the "SHOW CONTINUOUS" tokens have already been consumed. 1622 func (p *Parser) parseShowContinuousQueriesStatement() (*ShowContinuousQueriesStatement, error) { 1623 return &ShowContinuousQueriesStatement{}, nil 1624 } 1625 1626 // parseGrantsForUserStatement parses a string and returns a ShowGrantsForUserStatement. 1627 // This function assumes the "SHOW GRANTS" tokens have already been consumed. 1628 func (p *Parser) parseGrantsForUserStatement() (*ShowGrantsForUserStatement, error) { 1629 stmt := &ShowGrantsForUserStatement{} 1630 1631 // Parse the name of the user to be displayed. 1632 lit, err := p.ParseIdent() 1633 if err != nil { 1634 return nil, err 1635 } 1636 stmt.Name = lit 1637 1638 return stmt, nil 1639 } 1640 1641 // parseShowDatabasesStatement parses a string and returns a ShowDatabasesStatement. 1642 // This function assumes the "SHOW DATABASE" tokens have already been consumed. 1643 func (p *Parser) parseShowDatabasesStatement() (*ShowDatabasesStatement, error) { 1644 return &ShowDatabasesStatement{}, nil 1645 } 1646 1647 // parseCreateContinuousQueriesStatement parses a string and returns a CreateContinuousQueryStatement. 1648 // This function assumes the "CREATE CONTINUOUS" tokens have already been consumed. 1649 func (p *Parser) parseCreateContinuousQueryStatement() (*CreateContinuousQueryStatement, error) { 1650 stmt := &CreateContinuousQueryStatement{} 1651 1652 // Read the id of the query to create. 1653 ident, err := p.ParseIdent() 1654 if err != nil { 1655 return nil, err 1656 } 1657 stmt.Name = ident 1658 1659 // Expect an "ON" keyword. 1660 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != ON { 1661 return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos) 1662 } 1663 1664 // Read the name of the database to create the query on. 1665 if ident, err = p.ParseIdent(); err != nil { 1666 return nil, err 1667 } 1668 stmt.Database = ident 1669 1670 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == RESAMPLE { 1671 stmt.ResampleEvery, stmt.ResampleFor, err = p.parseResample() 1672 if err != nil { 1673 return nil, err 1674 } 1675 } else { 1676 p.Unscan() 1677 } 1678 1679 // Expect a "BEGIN SELECT" tokens. 1680 if err := p.parseTokens([]Token{BEGIN, SELECT}); err != nil { 1681 return nil, err 1682 } 1683 1684 // Read the select statement to be used as the source. 1685 source, err := p.parseSelectStatement(targetRequired) 1686 if err != nil { 1687 return nil, err 1688 } 1689 stmt.Source = source 1690 1691 // validate that the statement has a non-zero group by interval if it is aggregated 1692 if !source.IsRawQuery { 1693 d, err := source.GroupByInterval() 1694 if d == 0 || err != nil { 1695 // rewind so we can output an error with some info 1696 p.Unscan() // Unscan the whitespace 1697 p.Unscan() // Unscan the last token 1698 tok, pos, lit := p.ScanIgnoreWhitespace() 1699 expected := []string{"GROUP BY time(...)"} 1700 if err != nil { 1701 expected = append(expected, err.Error()) 1702 } 1703 return nil, newParseError(tokstr(tok, lit), expected, pos) 1704 } 1705 } 1706 1707 // Expect a "END" keyword. 1708 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != END { 1709 return nil, newParseError(tokstr(tok, lit), []string{"END"}, pos) 1710 } 1711 1712 if err := stmt.validate(); err != nil { 1713 return nil, err 1714 } 1715 1716 return stmt, nil 1717 } 1718 1719 // parseCreateDatabaseStatement parses a string and returns a CreateDatabaseStatement. 1720 // This function assumes the "CREATE DATABASE" tokens have already been consumed. 1721 func (p *Parser) parseCreateDatabaseStatement() (*CreateDatabaseStatement, error) { 1722 stmt := &CreateDatabaseStatement{} 1723 1724 // Parse the name of the database to be created. 1725 lit, err := p.ParseIdent() 1726 if err != nil { 1727 return nil, err 1728 } 1729 stmt.Name = lit 1730 1731 // Look for "WITH" 1732 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == WITH { 1733 // validate that at least one of DURATION, NAME, REPLICATION or SHARD is provided 1734 tok, pos, lit := p.ScanIgnoreWhitespace() 1735 if tok != DURATION && tok != NAME && tok != REPLICATION && tok != SHARD { 1736 return nil, newParseError(tokstr(tok, lit), []string{"DURATION", "NAME", "REPLICATION", "SHARD"}, pos) 1737 } 1738 // rewind 1739 p.Unscan() 1740 1741 // mark statement as having a RetentionPolicyInfo defined 1742 stmt.RetentionPolicyCreate = true 1743 1744 // Look for "DURATION" 1745 if err := p.parseTokens([]Token{DURATION}); err != nil { 1746 p.Unscan() 1747 } else { 1748 rpDuration, err := p.ParseDuration() 1749 if err != nil { 1750 return nil, err 1751 } 1752 stmt.RetentionPolicyDuration = &rpDuration 1753 } 1754 1755 // Look for "REPLICATION" 1756 if err := p.parseTokens([]Token{REPLICATION}); err != nil { 1757 p.Unscan() 1758 } else { 1759 rpReplication, err := p.ParseInt(1, math.MaxInt32) 1760 if err != nil { 1761 return nil, err 1762 } 1763 stmt.RetentionPolicyReplication = &rpReplication 1764 } 1765 1766 // Look for "SHARD" 1767 if err := p.parseTokens([]Token{SHARD}); err != nil { 1768 p.Unscan() 1769 } else { 1770 // Look for "DURATION" 1771 tok, pos, lit := p.ScanIgnoreWhitespace() 1772 if tok != DURATION { 1773 return nil, newParseError(tokstr(tok, lit), []string{"DURATION"}, pos) 1774 } 1775 stmt.RetentionPolicyShardGroupDuration, err = p.ParseDuration() 1776 if err != nil { 1777 return nil, err 1778 } 1779 } 1780 1781 // Look for "NAME" 1782 if err := p.parseTokens([]Token{NAME}); err != nil { 1783 p.Unscan() 1784 } else { 1785 stmt.RetentionPolicyName, err = p.ParseIdent() 1786 if err != nil { 1787 return nil, err 1788 } 1789 } 1790 } else { 1791 p.Unscan() 1792 } 1793 return stmt, nil 1794 } 1795 1796 // parseDropDatabaseStatement parses a string and returns a DropDatabaseStatement. 1797 // This function assumes the DROP DATABASE tokens have already been consumed. 1798 func (p *Parser) parseDropDatabaseStatement() (*DropDatabaseStatement, error) { 1799 stmt := &DropDatabaseStatement{} 1800 1801 // Parse the name of the database to be dropped. 1802 lit, err := p.ParseIdent() 1803 if err != nil { 1804 return nil, err 1805 } 1806 stmt.Name = lit 1807 1808 return stmt, nil 1809 } 1810 1811 // parseDropSubscriptionStatement parses a string and returns a DropSubscriptionStatement. 1812 // This function assumes the "DROP SUBSCRIPTION" tokens have already been consumed. 1813 func (p *Parser) parseDropSubscriptionStatement() (*DropSubscriptionStatement, error) { 1814 stmt := &DropSubscriptionStatement{} 1815 1816 // Read the id of the subscription to drop. 1817 ident, err := p.ParseIdent() 1818 if err != nil { 1819 return nil, err 1820 } 1821 stmt.Name = ident 1822 1823 // Expect an "ON" keyword. 1824 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != ON { 1825 return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos) 1826 } 1827 1828 // Read the name of the database. 1829 if ident, err = p.ParseIdent(); err != nil { 1830 return nil, err 1831 } 1832 stmt.Database = ident 1833 1834 if tok, pos, lit := p.Scan(); tok != DOT { 1835 return nil, newParseError(tokstr(tok, lit), []string{"."}, pos) 1836 } 1837 1838 // Read the name of the retention policy. 1839 if ident, err = p.ParseIdent(); err != nil { 1840 return nil, err 1841 } 1842 stmt.RetentionPolicy = ident 1843 1844 return stmt, nil 1845 } 1846 1847 // parseDropRetentionPolicyStatement parses a string and returns a DropRetentionPolicyStatement. 1848 // This function assumes the DROP RETENTION POLICY tokens have been consumed. 1849 func (p *Parser) parseDropRetentionPolicyStatement() (*DropRetentionPolicyStatement, error) { 1850 stmt := &DropRetentionPolicyStatement{} 1851 1852 // Parse the policy name. 1853 ident, err := p.ParseIdent() 1854 if err != nil { 1855 return nil, err 1856 } 1857 stmt.Name = ident 1858 1859 // Consume the required ON token. 1860 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != ON { 1861 return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos) 1862 } 1863 1864 // Parse the database name. 1865 if stmt.Database, err = p.ParseIdent(); err != nil { 1866 return nil, err 1867 } 1868 1869 return stmt, nil 1870 } 1871 1872 // parseCreateUserStatement parses a string and returns a CreateUserStatement. 1873 // This function assumes the "CREATE USER" tokens have already been consumed. 1874 func (p *Parser) parseCreateUserStatement() (*CreateUserStatement, error) { 1875 stmt := &CreateUserStatement{} 1876 1877 // Parse name of the user to be created. 1878 ident, err := p.ParseIdent() 1879 if err != nil { 1880 return nil, err 1881 } 1882 stmt.Name = ident 1883 1884 // Consume "WITH PASSWORD" tokens 1885 if err := p.parseTokens([]Token{WITH, PASSWORD}); err != nil { 1886 return nil, err 1887 } 1888 1889 // Parse new user's password 1890 if ident, err = p.parseString(); err != nil { 1891 return nil, err 1892 } 1893 stmt.Password = ident 1894 1895 // Check for option WITH clause. 1896 if tok, _, _ := p.ScanIgnoreWhitespace(); tok != WITH { 1897 p.Unscan() 1898 return stmt, nil 1899 } 1900 1901 // "WITH ALL PRIVILEGES" grants the new user admin privilege. 1902 // Only admin privilege can be set on user creation. 1903 if err := p.parseTokens([]Token{ALL, PRIVILEGES}); err != nil { 1904 return nil, err 1905 } 1906 stmt.Admin = true 1907 1908 return stmt, nil 1909 } 1910 1911 // parseDropUserStatement parses a string and returns a DropUserStatement. 1912 // This function assumes the DROP USER tokens have already been consumed. 1913 func (p *Parser) parseDropUserStatement() (*DropUserStatement, error) { 1914 stmt := &DropUserStatement{} 1915 1916 // Parse the name of the user to be dropped. 1917 lit, err := p.ParseIdent() 1918 if err != nil { 1919 return nil, err 1920 } 1921 stmt.Name = lit 1922 1923 return stmt, nil 1924 } 1925 1926 // parseExplainStatement parses a string and return an ExplainStatement. 1927 // This function assumes the EXPLAIN token has already been consumed. 1928 func (p *Parser) parseExplainStatement() (*ExplainStatement, error) { 1929 stmt := &ExplainStatement{} 1930 1931 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == ANALYZE { 1932 stmt.Analyze = true 1933 } else { 1934 p.Unscan() 1935 } 1936 1937 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != SELECT { 1938 return nil, newParseError(tokstr(tok, lit), []string{"SELECT"}, pos) 1939 } 1940 1941 s, err := p.parseSelectStatement(targetNotRequired) 1942 if err != nil { 1943 return nil, err 1944 } 1945 stmt.Statement = s 1946 return stmt, nil 1947 } 1948 1949 // parseShowShardGroupsStatement parses a string for "SHOW SHARD GROUPS" statement. 1950 // This function assumes the "SHOW SHARD GROUPS" tokens have already been consumed. 1951 func (p *Parser) parseShowShardGroupsStatement() (*ShowShardGroupsStatement, error) { 1952 return &ShowShardGroupsStatement{}, nil 1953 } 1954 1955 // parseShowShardsStatement parses a string for "SHOW SHARDS" statement. 1956 // This function assumes the "SHOW SHARDS" tokens have already been consumed. 1957 func (p *Parser) parseShowShardsStatement() (*ShowShardsStatement, error) { 1958 return &ShowShardsStatement{}, nil 1959 } 1960 1961 // parseShowStatsStatement parses a string and returns a ShowStatsStatement. 1962 // This function assumes the "SHOW STATS" tokens have already been consumed. 1963 func (p *Parser) parseShowStatsStatement() (*ShowStatsStatement, error) { 1964 stmt := &ShowStatsStatement{} 1965 var err error 1966 1967 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FOR { 1968 stmt.Module, err = p.parseString() 1969 } else { 1970 p.Unscan() 1971 } 1972 1973 return stmt, err 1974 } 1975 1976 // parseShowDiagnostics parses a string and returns a ShowDiagnosticsStatement. 1977 func (p *Parser) parseShowDiagnosticsStatement() (*ShowDiagnosticsStatement, error) { 1978 stmt := &ShowDiagnosticsStatement{} 1979 var err error 1980 1981 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FOR { 1982 stmt.Module, err = p.parseString() 1983 } else { 1984 p.Unscan() 1985 } 1986 1987 return stmt, err 1988 } 1989 1990 // parseDropContinuousQueriesStatement parses a string and returns a DropContinuousQueryStatement. 1991 // This function assumes the "DROP CONTINUOUS" tokens have already been consumed. 1992 func (p *Parser) parseDropContinuousQueryStatement() (*DropContinuousQueryStatement, error) { 1993 stmt := &DropContinuousQueryStatement{} 1994 1995 // Read the id of the query to drop. 1996 ident, err := p.ParseIdent() 1997 if err != nil { 1998 return nil, err 1999 } 2000 stmt.Name = ident 2001 2002 // Expect an "ON" keyword. 2003 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != ON { 2004 return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos) 2005 } 2006 2007 // Read the name of the database to remove the query from. 2008 if ident, err = p.ParseIdent(); err != nil { 2009 return nil, err 2010 } 2011 stmt.Database = ident 2012 2013 return stmt, nil 2014 } 2015 2016 // parseFields parses a list of one or more fields. 2017 func (p *Parser) parseFields() (Fields, error) { 2018 var fields Fields 2019 2020 for { 2021 // Parse the field. 2022 f, err := p.parseField() 2023 if err != nil { 2024 return nil, err 2025 } 2026 2027 // Add new field. 2028 fields = append(fields, f) 2029 2030 // If there's not a comma next then stop parsing fields. 2031 if tok, _, _ := p.Scan(); tok != COMMA { 2032 p.Unscan() 2033 break 2034 } 2035 } 2036 return fields, nil 2037 } 2038 2039 // parseField parses a single field. 2040 func (p *Parser) parseField() (*Field, error) { 2041 f := &Field{} 2042 2043 // Attempt to parse a regex. 2044 re, err := p.parseRegex() 2045 if err != nil { 2046 return nil, err 2047 } else if re != nil { 2048 f.Expr = re 2049 } else { 2050 _, pos, _ := p.ScanIgnoreWhitespace() 2051 p.Unscan() 2052 // Parse the expression first. 2053 expr, err := p.ParseExpr() 2054 if err != nil { 2055 return nil, err 2056 } 2057 var c validateField 2058 Walk(&c, expr) 2059 if c.foundInvalid { 2060 return nil, fmt.Errorf("invalid operator %s in SELECT clause at line %d, char %d; operator is intended for WHERE clause", c.badToken, pos.Line+1, pos.Char+1) 2061 } 2062 f.Expr = expr 2063 } 2064 2065 // Parse the alias if the current and next tokens are "WS AS". 2066 alias, err := p.parseAlias() 2067 if err != nil { 2068 return nil, err 2069 } 2070 f.Alias = alias 2071 2072 // Consume all trailing whitespace. 2073 p.consumeWhitespace() 2074 2075 return f, nil 2076 } 2077 2078 // validateField checks if the Expr is a valid field. We disallow all binary expression 2079 // that return a boolean. 2080 type validateField struct { 2081 foundInvalid bool 2082 badToken Token 2083 } 2084 2085 func (c *validateField) Visit(n Node) Visitor { 2086 e, ok := n.(*BinaryExpr) 2087 if !ok { 2088 return c 2089 } 2090 2091 switch e.Op { 2092 case EQ, NEQ, EQREGEX, 2093 NEQREGEX, LT, LTE, GT, GTE, 2094 AND, OR: 2095 c.foundInvalid = true 2096 c.badToken = e.Op 2097 return nil 2098 } 2099 return c 2100 } 2101 2102 // parseAlias parses the "AS IDENT" alias for fields and dimensions. 2103 func (p *Parser) parseAlias() (string, error) { 2104 // Check if the next token is "AS". If not, then Unscan and exit. 2105 if tok, _, _ := p.ScanIgnoreWhitespace(); tok != AS { 2106 p.Unscan() 2107 return "", nil 2108 } 2109 2110 // Then we should have the alias identifier. 2111 lit, err := p.ParseIdent() 2112 if err != nil { 2113 return "", err 2114 } 2115 return lit, nil 2116 } 2117 2118 // parseSources parses a comma delimited list of sources. 2119 func (p *Parser) parseSources(subqueries bool) (Sources, error) { 2120 var sources Sources 2121 2122 for { 2123 s, err := p.parseSource(subqueries) 2124 if err != nil { 2125 return nil, err 2126 } 2127 sources = append(sources, s) 2128 2129 if tok, _, _ := p.ScanIgnoreWhitespace(); tok != COMMA { 2130 p.Unscan() 2131 break 2132 } 2133 } 2134 2135 return sources, nil 2136 } 2137 2138 // peekRune returns the next rune that would be read by the scanner. 2139 func (p *Parser) peekRune() rune { 2140 r, _, _ := p.s.s.r.ReadRune() 2141 if r != eof { 2142 _ = p.s.s.r.UnreadRune() 2143 } 2144 2145 return r 2146 } 2147 2148 func (p *Parser) parseSource(subqueries bool) (Source, error) { 2149 m := &Measurement{} 2150 2151 // Attempt to parse a regex. 2152 re, err := p.parseRegex() 2153 if err != nil { 2154 return nil, err 2155 } else if re != nil { 2156 m.Regex = re 2157 // Regex is always last so we're done. 2158 return m, nil 2159 } 2160 2161 // If there is no regular expression, this might be a subquery. 2162 // Parse the subquery if we are in a query that allows them as a source. 2163 if m.Regex == nil && subqueries { 2164 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == LPAREN { 2165 if err := p.parseTokens([]Token{SELECT}); err != nil { 2166 return nil, err 2167 } 2168 2169 stmt, err := p.parseSelectStatement(targetSubquery) 2170 if err != nil { 2171 return nil, err 2172 } 2173 2174 if err := p.parseTokens([]Token{RPAREN}); err != nil { 2175 return nil, err 2176 } 2177 return &SubQuery{Statement: stmt}, nil 2178 } else { 2179 p.Unscan() 2180 } 2181 } 2182 2183 // Didn't find a regex so parse segmented identifiers. 2184 idents, err := p.parseSegmentedIdents() 2185 if err != nil { 2186 return nil, err 2187 } 2188 2189 // If we already have the max allowed idents, we're done. 2190 if len(idents) == 3 { 2191 m.Database, m.RetentionPolicy, m.Name = idents[0], idents[1], idents[2] 2192 return m, nil 2193 } 2194 // Check again for regex. 2195 re, err = p.parseRegex() 2196 if err != nil { 2197 return nil, err 2198 } else if re != nil { 2199 m.Regex = re 2200 } 2201 2202 // Assign identifiers to their proper locations. 2203 switch len(idents) { 2204 case 1: 2205 if re != nil { 2206 m.RetentionPolicy = idents[0] 2207 } else { 2208 m.Name = idents[0] 2209 } 2210 case 2: 2211 if re != nil { 2212 m.Database, m.RetentionPolicy = idents[0], idents[1] 2213 } else { 2214 m.RetentionPolicy, m.Name = idents[0], idents[1] 2215 } 2216 } 2217 2218 return m, nil 2219 } 2220 2221 // parseCondition parses the "WHERE" clause of the query, if it exists. 2222 func (p *Parser) parseCondition() (Expr, error) { 2223 // Check if the WHERE token exists. 2224 if tok, _, _ := p.ScanIgnoreWhitespace(); tok != WHERE { 2225 p.Unscan() 2226 return nil, nil 2227 } 2228 2229 // Scan the identifier for the source. 2230 expr, err := p.ParseExpr() 2231 if err != nil { 2232 return nil, err 2233 } 2234 2235 return expr, nil 2236 } 2237 2238 // parseDimensions parses the "GROUP BY" clause of the query, if it exists. 2239 func (p *Parser) parseDimensions() (Dimensions, error) { 2240 // If the next token is not GROUP then exit. 2241 if tok, _, _ := p.ScanIgnoreWhitespace(); tok != GROUP { 2242 p.Unscan() 2243 return nil, nil 2244 } 2245 2246 // Now the next token should be "BY". 2247 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != BY { 2248 return nil, newParseError(tokstr(tok, lit), []string{"BY"}, pos) 2249 } 2250 2251 var dimensions Dimensions 2252 for { 2253 // Parse the dimension. 2254 d, err := p.parseDimension() 2255 if err != nil { 2256 return nil, err 2257 } 2258 2259 // Add new dimension. 2260 dimensions = append(dimensions, d) 2261 2262 // If there's not a comma next then stop parsing dimensions. 2263 if tok, _, _ := p.Scan(); tok != COMMA { 2264 p.Unscan() 2265 break 2266 } 2267 } 2268 return dimensions, nil 2269 } 2270 2271 // parseDimension parses a single dimension. 2272 func (p *Parser) parseDimension() (*Dimension, error) { 2273 re, err := p.parseRegex() 2274 if err != nil { 2275 return nil, err 2276 } else if re != nil { 2277 return &Dimension{Expr: re}, nil 2278 } 2279 2280 // Parse the expression first. 2281 expr, err := p.ParseExpr() 2282 if err != nil { 2283 return nil, err 2284 } 2285 2286 // Consume all trailing whitespace. 2287 p.consumeWhitespace() 2288 2289 return &Dimension{Expr: expr}, nil 2290 } 2291 2292 // parseFill parses the fill call and its options. 2293 func (p *Parser) parseFill() (FillOption, interface{}, error) { 2294 // Parse the expression first. 2295 tok, _, lit := p.ScanIgnoreWhitespace() 2296 p.Unscan() 2297 if tok != IDENT || strings.ToLower(lit) != "fill" { 2298 return NullFill, nil, nil 2299 } 2300 2301 expr, err := p.ParseExpr() 2302 if err != nil { 2303 return NullFill, nil, err 2304 } 2305 fill, ok := expr.(*Call) 2306 if !ok { 2307 return NullFill, nil, errors.New("fill must be a function call") 2308 } else if len(fill.Args) != 1 { 2309 return NullFill, nil, errors.New("fill requires an argument, e.g.: 0, null, none, previous, linear") 2310 } 2311 switch fill.Args[0].String() { 2312 case "null": 2313 return NullFill, nil, nil 2314 case "none": 2315 return NoFill, nil, nil 2316 case "previous": 2317 return PreviousFill, nil, nil 2318 case "linear": 2319 return LinearFill, nil, nil 2320 default: 2321 switch num := fill.Args[0].(type) { 2322 case *IntegerLiteral: 2323 return NumberFill, num.Val, nil 2324 case *NumberLiteral: 2325 return NumberFill, num.Val, nil 2326 default: 2327 return NullFill, nil, fmt.Errorf("expected number argument in fill()") 2328 } 2329 } 2330 } 2331 2332 // parseLocation parses the timezone call and its arguments. 2333 func (p *Parser) parseLocation() (*time.Location, error) { 2334 // Parse the expression first. 2335 tok, _, lit := p.ScanIgnoreWhitespace() 2336 p.Unscan() 2337 if tok != IDENT || strings.ToLower(lit) != "tz" { 2338 return nil, nil 2339 } 2340 2341 expr, err := p.ParseExpr() 2342 if err != nil { 2343 return nil, err 2344 } 2345 tz, ok := expr.(*Call) 2346 if !ok { 2347 return nil, errors.New("tz must be a function call") 2348 } else if len(tz.Args) != 1 { 2349 return nil, errors.New("tz requires exactly one argument") 2350 } 2351 2352 tzname, ok := tz.Args[0].(*StringLiteral) 2353 if !ok { 2354 return nil, errors.New("expected string argument in tz()") 2355 } 2356 2357 loc, err := time.LoadLocation(tzname.Val) 2358 if err != nil { 2359 // Do not pass the same error message as the error may contain sensitive pathnames. 2360 return nil, fmt.Errorf("unable to find time zone %s", tzname.Val) 2361 } 2362 return loc, nil 2363 } 2364 2365 // ParseOptionalTokenAndInt parses the specified token followed 2366 // by an int, if it exists. 2367 func (p *Parser) ParseOptionalTokenAndInt(t Token) (int, error) { 2368 // Check if the token exists. 2369 if tok, _, _ := p.ScanIgnoreWhitespace(); tok != t { 2370 p.Unscan() 2371 return 0, nil 2372 } 2373 2374 // Scan the number. 2375 tok, pos, lit := p.ScanIgnoreWhitespace() 2376 if tok != INTEGER { 2377 return 0, newParseError(tokstr(tok, lit), []string{"integer"}, pos) 2378 } 2379 2380 // Parse number. 2381 n, _ := strconv.ParseInt(lit, 10, 64) 2382 if n < 0 { 2383 msg := fmt.Sprintf("%s must be >= 0", t.String()) 2384 return 0, &ParseError{Message: msg, Pos: pos} 2385 } 2386 2387 return int(n), nil 2388 } 2389 2390 // parseOrderBy parses the "ORDER BY" clause of a query, if it exists. 2391 func (p *Parser) parseOrderBy() (SortFields, error) { 2392 // Return nil result and nil error if no ORDER token at this position. 2393 if tok, _, _ := p.ScanIgnoreWhitespace(); tok != ORDER { 2394 p.Unscan() 2395 return nil, nil 2396 } 2397 2398 // Parse the required BY token. 2399 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != BY { 2400 return nil, newParseError(tokstr(tok, lit), []string{"BY"}, pos) 2401 } 2402 2403 // Parse the ORDER BY fields. 2404 fields, err := p.parseSortFields() 2405 if err != nil { 2406 return nil, err 2407 } 2408 2409 return fields, nil 2410 } 2411 2412 // parseSortFields parses the sort fields for an ORDER BY clause. 2413 func (p *Parser) parseSortFields() (SortFields, error) { 2414 var fields SortFields 2415 2416 tok, pos, lit := p.ScanIgnoreWhitespace() 2417 2418 switch tok { 2419 // The first field after an order by may not have a field name (e.g. ORDER BY ASC) 2420 case ASC, DESC: 2421 fields = append(fields, &SortField{Ascending: (tok == ASC)}) 2422 // If it's a token, parse it as a sort field. At least one is required. 2423 case IDENT: 2424 p.Unscan() 2425 field, err := p.parseSortField() 2426 if err != nil { 2427 return nil, err 2428 } 2429 2430 if lit != "time" { 2431 return nil, errors.New("only ORDER BY time supported at this time") 2432 } 2433 2434 fields = append(fields, field) 2435 // Parse error... 2436 default: 2437 return nil, newParseError(tokstr(tok, lit), []string{"identifier", "ASC", "DESC"}, pos) 2438 } 2439 2440 // Parse additional fields. 2441 for { 2442 tok, _, _ := p.ScanIgnoreWhitespace() 2443 2444 if tok != COMMA { 2445 p.Unscan() 2446 break 2447 } 2448 2449 field, err := p.parseSortField() 2450 if err != nil { 2451 return nil, err 2452 } 2453 2454 fields = append(fields, field) 2455 } 2456 2457 if len(fields) > 1 { 2458 return nil, errors.New("only ORDER BY time supported at this time") 2459 } 2460 2461 return fields, nil 2462 } 2463 2464 // parseSortField parses one field of an ORDER BY clause. 2465 func (p *Parser) parseSortField() (*SortField, error) { 2466 field := &SortField{} 2467 2468 // Parse sort field name. 2469 ident, err := p.ParseIdent() 2470 if err != nil { 2471 return nil, err 2472 } 2473 field.Name = ident 2474 2475 // Check for optional ASC or DESC clause. Default is ASC. 2476 tok, _, _ := p.ScanIgnoreWhitespace() 2477 if tok != ASC && tok != DESC { 2478 p.Unscan() 2479 tok = ASC 2480 } 2481 field.Ascending = (tok == ASC) 2482 2483 return field, nil 2484 } 2485 2486 // ParseVarRef parses a reference to a measurement or field. 2487 func (p *Parser) ParseVarRef() (*VarRef, error) { 2488 // Parse the segments of the variable ref. 2489 segments, err := p.parseSegmentedIdents() 2490 if err != nil { 2491 return nil, err 2492 } 2493 2494 var dtype DataType 2495 if tok, _, _ := p.Scan(); tok == DOUBLECOLON { 2496 tok, pos, lit := p.Scan() 2497 switch tok { 2498 case IDENT: 2499 switch strings.ToLower(lit) { 2500 case "float": 2501 dtype = Float 2502 case "integer": 2503 dtype = Integer 2504 case "unsigned": 2505 dtype = Unsigned 2506 case "string": 2507 dtype = String 2508 case "boolean": 2509 dtype = Boolean 2510 default: 2511 return nil, newParseError(tokstr(tok, lit), []string{"float", "integer", "unsigned", "string", "boolean", "field", "tag"}, pos) 2512 } 2513 case FIELD: 2514 dtype = AnyField 2515 case TAG: 2516 dtype = Tag 2517 default: 2518 return nil, newParseError(tokstr(tok, lit), []string{"float", "integer", "string", "boolean", "field", "tag"}, pos) 2519 } 2520 } else { 2521 p.Unscan() 2522 } 2523 2524 vr := &VarRef{Val: strings.Join(segments, "."), Type: dtype} 2525 2526 return vr, nil 2527 } 2528 2529 // ParseExpr parses an expression. 2530 func (p *Parser) ParseExpr() (Expr, error) { 2531 var err error 2532 // Dummy root node. 2533 root := &BinaryExpr{} 2534 2535 // Parse a non-binary expression type to start. 2536 // This variable will always be the root of the expression tree. 2537 root.RHS, err = p.parseUnaryExpr() 2538 if err != nil { 2539 return nil, err 2540 } 2541 2542 // Loop over operations and unary exprs and build a tree based on precendence. 2543 for { 2544 // If the next token is NOT an operator then return the expression. 2545 op, _, _ := p.ScanIgnoreWhitespace() 2546 if !op.isOperator() { 2547 p.Unscan() 2548 return root.RHS, nil 2549 } 2550 2551 // Otherwise parse the next expression. 2552 var rhs Expr 2553 if IsRegexOp(op) { 2554 // RHS of a regex operator must be a regular expression. 2555 if rhs, err = p.parseRegex(); err != nil { 2556 return nil, err 2557 } 2558 // parseRegex can return an empty type, but we need it to be present 2559 if rhs.(*RegexLiteral) == nil { 2560 tok, pos, lit := p.ScanIgnoreWhitespace() 2561 return nil, newParseError(tokstr(tok, lit), []string{"regex"}, pos) 2562 } 2563 } else { 2564 if rhs, err = p.parseUnaryExpr(); err != nil { 2565 return nil, err 2566 } 2567 } 2568 2569 // Find the right spot in the tree to add the new expression by 2570 // descending the RHS of the expression tree until we reach the last 2571 // BinaryExpr or a BinaryExpr whose RHS has an operator with 2572 // precedence >= the operator being added. 2573 for node := root; ; { 2574 r, ok := node.RHS.(*BinaryExpr) 2575 if !ok || r.Op.Precedence() >= op.Precedence() { 2576 // Add the new expression here and break. 2577 node.RHS = &BinaryExpr{LHS: node.RHS, RHS: rhs, Op: op} 2578 break 2579 } 2580 node = r 2581 } 2582 } 2583 } 2584 2585 // parseUnaryExpr parses an non-binary expression. 2586 func (p *Parser) parseUnaryExpr() (Expr, error) { 2587 // If the first token is a LPAREN then parse it as its own grouped expression. 2588 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == LPAREN { 2589 expr, err := p.ParseExpr() 2590 if err != nil { 2591 return nil, err 2592 } 2593 2594 // Expect an RPAREN at the end. 2595 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != RPAREN { 2596 return nil, newParseError(tokstr(tok, lit), []string{")"}, pos) 2597 } 2598 2599 return &ParenExpr{Expr: expr}, nil 2600 } 2601 p.Unscan() 2602 2603 // Read next token. 2604 tok, pos, lit := p.ScanIgnoreWhitespace() 2605 switch tok { 2606 case IDENT: 2607 // If the next immediate token is a left parentheses, parse as function call. 2608 // Otherwise parse as a variable reference. 2609 if tok0, _, _ := p.Scan(); tok0 == LPAREN { 2610 return p.parseCall(lit) 2611 } 2612 2613 p.Unscan() // Unscan the last token (wasn't an LPAREN) 2614 p.Unscan() // Unscan the IDENT token 2615 2616 // Parse it as a VarRef. 2617 return p.ParseVarRef() 2618 case DISTINCT: 2619 // If the next immediate token is a left parentheses, parse as function call. 2620 // Otherwise parse as a Distinct expression. 2621 tok0, pos, lit := p.Scan() 2622 if tok0 == LPAREN { 2623 return p.parseCall("distinct") 2624 } else if tok0 == WS { 2625 tok1, pos, lit := p.ScanIgnoreWhitespace() 2626 if tok1 != IDENT { 2627 return nil, newParseError(tokstr(tok1, lit), []string{"identifier"}, pos) 2628 } 2629 return &Distinct{Val: lit}, nil 2630 } 2631 2632 return nil, newParseError(tokstr(tok0, lit), []string{"(", "identifier"}, pos) 2633 case STRING: 2634 return &StringLiteral{Val: lit}, nil 2635 case NUMBER: 2636 v, err := strconv.ParseFloat(lit, 64) 2637 if err != nil { 2638 return nil, &ParseError{Message: "unable to parse number", Pos: pos} 2639 } 2640 return &NumberLiteral{Val: v}, nil 2641 case INTEGER: 2642 v, err := strconv.ParseInt(lit, 10, 64) 2643 if err != nil { 2644 // The literal may be too large to fit into an int64. If it is, use an unsigned integer. 2645 // The check for negative numbers is handled somewhere else so this should always be a positive number. 2646 if v, err := strconv.ParseUint(lit, 10, 64); err == nil { 2647 return &UnsignedLiteral{Val: v}, nil 2648 } 2649 return nil, &ParseError{Message: "unable to parse integer", Pos: pos} 2650 } 2651 return &IntegerLiteral{Val: v}, nil 2652 case TRUE, FALSE: 2653 return &BooleanLiteral{Val: tok == TRUE}, nil 2654 case DURATIONVAL: 2655 v, err := ParseDuration(lit) 2656 if err != nil { 2657 return nil, err 2658 } 2659 return &DurationLiteral{Val: v}, nil 2660 case MUL: 2661 wc := &Wildcard{} 2662 if tok, _, _ := p.Scan(); tok == DOUBLECOLON { 2663 tok, pos, lit := p.Scan() 2664 switch tok { 2665 case FIELD, TAG: 2666 wc.Type = tok 2667 default: 2668 return nil, newParseError(tokstr(tok, lit), []string{"field", "tag"}, pos) 2669 } 2670 } else { 2671 p.Unscan() 2672 } 2673 return wc, nil 2674 case REGEX: 2675 re, err := regexp.Compile(lit) 2676 if err != nil { 2677 return nil, &ParseError{Message: err.Error(), Pos: pos} 2678 } 2679 return &RegexLiteral{Val: re}, nil 2680 case BOUNDPARAM: 2681 // If we have a BOUNDPARAM in the token stream, 2682 // it wasn't resolved by the parser to another 2683 // token type which means it is invalid. 2684 // Figure out what is wrong with it. 2685 k := strings.TrimPrefix(lit, "$") 2686 if len(k) == 0 { 2687 return nil, errors.New("empty bound parameter") 2688 } 2689 2690 v, ok := p.params[k] 2691 if !ok { 2692 return nil, fmt.Errorf("missing parameter: %s", k) 2693 } 2694 2695 // The value must be an ErrorValue. 2696 // Return the value as an error. A non-error value 2697 // would have been substituted as something else. 2698 return nil, errors.New(v.Value()) 2699 case ADD, SUB: 2700 mul := 1 2701 if tok == SUB { 2702 mul = -1 2703 } 2704 2705 tok0, pos0, lit0 := p.ScanIgnoreWhitespace() 2706 switch tok0 { 2707 case NUMBER, INTEGER, DURATIONVAL, LPAREN, IDENT: 2708 // Unscan the token and use parseUnaryExpr. 2709 p.Unscan() 2710 2711 lit, err := p.parseUnaryExpr() 2712 if err != nil { 2713 return nil, err 2714 } 2715 2716 switch lit := lit.(type) { 2717 case *NumberLiteral: 2718 lit.Val *= float64(mul) 2719 case *IntegerLiteral: 2720 lit.Val *= int64(mul) 2721 case *UnsignedLiteral: 2722 if tok == SUB { 2723 // Because of twos-complement integers and the method we parse, math.MinInt64 will be parsed 2724 // as an UnsignedLiteral because it overflows an int64, but it fits into int64 if it were parsed 2725 // as a negative number instead. 2726 if lit.Val == uint64(math.MaxInt64+1) { 2727 return &IntegerLiteral{Val: int64(-lit.Val)}, nil 2728 } 2729 return nil, fmt.Errorf("constant -%d underflows int64", lit.Val) 2730 } 2731 case *DurationLiteral: 2732 lit.Val *= time.Duration(mul) 2733 case *VarRef, *Call, *ParenExpr: 2734 // Multiply the variable. 2735 return &BinaryExpr{ 2736 Op: MUL, 2737 LHS: &IntegerLiteral{Val: int64(mul)}, 2738 RHS: lit, 2739 }, nil 2740 default: 2741 panic(fmt.Sprintf("unexpected literal: %T", lit)) 2742 } 2743 return lit, nil 2744 default: 2745 return nil, newParseError(tokstr(tok0, lit0), []string{"identifier", "number", "duration", "("}, pos0) 2746 } 2747 default: 2748 return nil, newParseError(tokstr(tok, lit), []string{"identifier", "string", "number", "bool"}, pos) 2749 } 2750 } 2751 2752 // parseRegex parses a regular expression. 2753 func (p *Parser) parseRegex() (*RegexLiteral, error) { 2754 nextRune := p.peekRune() 2755 if isWhitespace(nextRune) { 2756 p.consumeWhitespace() 2757 } 2758 2759 // If the next character is not a '/', then return nils. 2760 nextRune = p.peekRune() 2761 if nextRune == '$' { 2762 // This might be a bound parameter and it might 2763 // resolve to a regex. 2764 tok, _, _ := p.Scan() 2765 p.Unscan() 2766 if tok != REGEX { 2767 // It was not a regular expression so return. 2768 return nil, nil 2769 } 2770 } else if nextRune != '/' { 2771 return nil, nil 2772 } 2773 2774 tok, pos, lit := p.ScanRegex() 2775 2776 if tok == BADESCAPE { 2777 msg := fmt.Sprintf("bad escape: %s", lit) 2778 return nil, &ParseError{Message: msg, Pos: pos} 2779 } else if tok == BADREGEX { 2780 msg := fmt.Sprintf("bad regex: %s", lit) 2781 return nil, &ParseError{Message: msg, Pos: pos} 2782 } else if tok != REGEX { 2783 return nil, newParseError(tokstr(tok, lit), []string{"regex"}, pos) 2784 } 2785 2786 re, err := regexp.Compile(lit) 2787 if err != nil { 2788 return nil, &ParseError{Message: err.Error(), Pos: pos} 2789 } 2790 2791 return &RegexLiteral{Val: re}, nil 2792 } 2793 2794 // parseCall parses a function call. 2795 // This function assumes the function name and LPAREN have been consumed. 2796 func (p *Parser) parseCall(name string) (*Call, error) { 2797 name = strings.ToLower(name) 2798 2799 // Parse first function argument if one exists. 2800 var args []Expr 2801 re, err := p.parseRegex() 2802 if err != nil { 2803 return nil, err 2804 } else if re != nil { 2805 args = append(args, re) 2806 } else { 2807 // If there's a right paren then just return immediately. 2808 if tok, _, _ := p.Scan(); tok == RPAREN { 2809 return &Call{Name: name}, nil 2810 } 2811 p.Unscan() 2812 2813 arg, err := p.ParseExpr() 2814 if err != nil { 2815 return nil, err 2816 } 2817 args = append(args, arg) 2818 } 2819 2820 // Parse additional function arguments if there is a comma. 2821 for { 2822 // If there's not a comma, stop parsing arguments. 2823 if tok, _, _ := p.ScanIgnoreWhitespace(); tok != COMMA { 2824 p.Unscan() 2825 break 2826 } 2827 2828 re, err := p.parseRegex() 2829 if err != nil { 2830 return nil, err 2831 } else if re != nil { 2832 args = append(args, re) 2833 continue 2834 } 2835 2836 // Parse an expression argument. 2837 arg, err := p.ParseExpr() 2838 if err != nil { 2839 return nil, err 2840 } 2841 args = append(args, arg) 2842 } 2843 2844 // There should be a right parentheses at the end. 2845 if tok, pos, lit := p.Scan(); tok != RPAREN { 2846 return nil, newParseError(tokstr(tok, lit), []string{")"}, pos) 2847 } 2848 2849 return &Call{Name: name, Args: args}, nil 2850 } 2851 2852 // parseResample parses a RESAMPLE [EVERY <duration>] [FOR <duration>]. 2853 // This function assumes RESAMPLE has already been consumed. 2854 // EVERY and FOR are optional, but at least one of the two has to be used. 2855 func (p *Parser) parseResample() (time.Duration, time.Duration, error) { 2856 var interval time.Duration 2857 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == EVERY { 2858 tok, pos, lit := p.ScanIgnoreWhitespace() 2859 if tok != DURATIONVAL { 2860 return 0, 0, newParseError(tokstr(tok, lit), []string{"duration"}, pos) 2861 } 2862 2863 d, err := ParseDuration(lit) 2864 if err != nil { 2865 return 0, 0, &ParseError{Message: err.Error(), Pos: pos} 2866 } 2867 interval = d 2868 } else { 2869 p.Unscan() 2870 } 2871 2872 var maxDuration time.Duration 2873 if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FOR { 2874 tok, pos, lit := p.ScanIgnoreWhitespace() 2875 if tok != DURATIONVAL { 2876 return 0, 0, newParseError(tokstr(tok, lit), []string{"duration"}, pos) 2877 } 2878 2879 d, err := ParseDuration(lit) 2880 if err != nil { 2881 return 0, 0, &ParseError{Message: err.Error(), Pos: pos} 2882 } 2883 maxDuration = d 2884 } else { 2885 p.Unscan() 2886 } 2887 2888 // Neither EVERY or FOR were read, so read the next token again 2889 // so we can return a suitable error message. 2890 if interval == 0 && maxDuration == 0 { 2891 tok, pos, lit := p.ScanIgnoreWhitespace() 2892 return 0, 0, newParseError(tokstr(tok, lit), []string{"EVERY", "FOR"}, pos) 2893 } 2894 return interval, maxDuration, nil 2895 } 2896 2897 // Scan returns the next token from the underlying scanner. 2898 func (p *Parser) Scan() (tok Token, pos Pos, lit string) { 2899 return p.scan(p.s.Scan) 2900 } 2901 2902 // ScanRegex returns the next token from the underlying scanner 2903 // using the regex scanner. 2904 func (p *Parser) ScanRegex() (tok Token, pos Pos, lit string) { 2905 return p.scan(p.s.ScanRegex) 2906 } 2907 2908 type scanFunc func() (tok Token, pos Pos, lit string) 2909 2910 func (p *Parser) scan(fn scanFunc) (tok Token, pos Pos, lit string) { 2911 tok, pos, lit = fn() 2912 if tok == BOUNDPARAM { 2913 // If we have a bound parameter, attempt to 2914 // replace it in the scanner. If the bound parameter 2915 // isn't valid, do not perform the replacement. 2916 k := strings.TrimPrefix(lit, "$") 2917 if len(k) != 0 { 2918 if v, ok := p.params[k]; ok { 2919 tok, lit = v.TokenType(), v.Value() 2920 } 2921 } 2922 } 2923 return tok, pos, lit 2924 } 2925 2926 // ScanIgnoreWhitespace scans the next non-whitespace and non-comment token. 2927 func (p *Parser) ScanIgnoreWhitespace() (tok Token, pos Pos, lit string) { 2928 for { 2929 tok, pos, lit = p.Scan() 2930 if tok == WS || tok == COMMENT { 2931 continue 2932 } 2933 return 2934 } 2935 } 2936 2937 // consumeWhitespace scans the next token if it's whitespace. 2938 func (p *Parser) consumeWhitespace() { 2939 if tok, _, _ := p.Scan(); tok != WS { 2940 p.Unscan() 2941 } 2942 } 2943 2944 // Unscan pushes the previously read token back onto the buffer. 2945 func (p *Parser) Unscan() { p.s.Unscan() } 2946 2947 // ParseDuration parses a time duration from a string. 2948 // This is needed instead of time.ParseDuration because this will support 2949 // the full syntax that InfluxQL supports for specifying durations 2950 // including weeks and days. 2951 func ParseDuration(s string) (time.Duration, error) { 2952 // Return an error if the string is blank or one character 2953 if len(s) < 2 { 2954 return 0, ErrInvalidDuration 2955 } 2956 2957 // Split string into individual runes. 2958 a := []rune(s) 2959 2960 // Start with a zero duration. 2961 var d time.Duration 2962 i := 0 2963 2964 // Check for a negative. 2965 isNegative := false 2966 if a[i] == '-' { 2967 isNegative = true 2968 i++ 2969 } 2970 2971 var measure int64 2972 var unit string 2973 2974 // Parsing loop. 2975 for i < len(a) { 2976 // Find the number portion. 2977 start := i 2978 for ; i < len(a) && isDigit(a[i]); i++ { 2979 // Scan for the digits. 2980 } 2981 2982 // Check if we reached the end of the string prematurely. 2983 if i >= len(a) || i == start { 2984 return 0, ErrInvalidDuration 2985 } 2986 2987 // Parse the numeric part. 2988 n, err := strconv.ParseInt(string(a[start:i]), 10, 64) 2989 if err != nil { 2990 return 0, ErrInvalidDuration 2991 } 2992 measure = n 2993 2994 // Extract the unit of measure. 2995 // If the last two characters are "ms" then parse as milliseconds. 2996 // Otherwise just use the last character as the unit of measure. 2997 unit = string(a[i]) 2998 switch a[i] { 2999 case 'n': 3000 if i+1 < len(a) && a[i+1] == 's' { 3001 unit = string(a[i : i+2]) 3002 d += time.Duration(n) 3003 i += 2 3004 continue 3005 } 3006 return 0, ErrInvalidDuration 3007 case 'u', 'µ': 3008 d += time.Duration(n) * time.Microsecond 3009 case 'm': 3010 if i+1 < len(a) && a[i+1] == 's' { 3011 unit = string(a[i : i+2]) 3012 d += time.Duration(n) * time.Millisecond 3013 i += 2 3014 continue 3015 } 3016 d += time.Duration(n) * time.Minute 3017 case 's': 3018 d += time.Duration(n) * time.Second 3019 case 'h': 3020 d += time.Duration(n) * time.Hour 3021 case 'd': 3022 d += time.Duration(n) * 24 * time.Hour 3023 case 'w': 3024 d += time.Duration(n) * 7 * 24 * time.Hour 3025 default: 3026 return 0, ErrInvalidDuration 3027 } 3028 i++ 3029 } 3030 3031 // Check to see if we overflowed a duration 3032 if d < 0 && !isNegative { 3033 return 0, fmt.Errorf("overflowed duration %d%s: choose a smaller duration or INF", measure, unit) 3034 } 3035 3036 if isNegative { 3037 d = -d 3038 } 3039 return d, nil 3040 } 3041 3042 // FormatDuration formats a duration to a string. 3043 func FormatDuration(d time.Duration) string { 3044 if d == 0 { 3045 return "0s" 3046 } else if d%(7*24*time.Hour) == 0 { 3047 return fmt.Sprintf("%dw", d/(7*24*time.Hour)) 3048 } else if d%(24*time.Hour) == 0 { 3049 return fmt.Sprintf("%dd", d/(24*time.Hour)) 3050 } else if d%time.Hour == 0 { 3051 return fmt.Sprintf("%dh", d/time.Hour) 3052 } else if d%time.Minute == 0 { 3053 return fmt.Sprintf("%dm", d/time.Minute) 3054 } else if d%time.Second == 0 { 3055 return fmt.Sprintf("%ds", d/time.Second) 3056 } else if d%time.Millisecond == 0 { 3057 return fmt.Sprintf("%dms", d/time.Millisecond) 3058 } else if d%time.Microsecond == 0 { 3059 // Although we accept both "u" and "µ" when reading microsecond durations, 3060 // we output with "u", which can be represented in 1 byte, 3061 // instead of "µ", which requires 2 bytes. 3062 return fmt.Sprintf("%du", d/time.Microsecond) 3063 } 3064 return fmt.Sprintf("%dns", d) 3065 } 3066 3067 // parseTokens consumes an expected sequence of tokens. 3068 func (p *Parser) parseTokens(toks []Token) error { 3069 for _, expected := range toks { 3070 if tok, pos, lit := p.ScanIgnoreWhitespace(); tok != expected { 3071 return newParseError(tokstr(tok, lit), []string{tokens[expected]}, pos) 3072 } 3073 } 3074 return nil 3075 } 3076 3077 var ( 3078 // Quote String replacer. 3079 qsReplacer = strings.NewReplacer("\n", `\n`, `\`, `\\`, `'`, `\'`) 3080 3081 // Quote Ident replacer. 3082 qiReplacer = strings.NewReplacer("\n", `\n`, `\`, `\\`, `"`, `\"`) 3083 ) 3084 3085 // QuoteString returns a quoted string. 3086 func QuoteString(s string) string { 3087 return `'` + qsReplacer.Replace(s) + `'` 3088 } 3089 3090 // QuoteIdent returns a quoted identifier from multiple bare identifiers. 3091 func QuoteIdent(segments ...string) string { 3092 var buf bytes.Buffer 3093 for i, segment := range segments { 3094 needQuote := IdentNeedsQuotes(segment) || 3095 ((i < len(segments)-1) && segment != "") || // not last segment && not "" 3096 ((i == 0 || i == len(segments)-1) && segment == "") // the first or last segment and an empty string 3097 3098 if needQuote { 3099 _ = buf.WriteByte('"') 3100 } 3101 3102 _, _ = buf.WriteString(qiReplacer.Replace(segment)) 3103 3104 if needQuote { 3105 _ = buf.WriteByte('"') 3106 } 3107 3108 if i < len(segments)-1 { 3109 _ = buf.WriteByte('.') 3110 } 3111 } 3112 return buf.String() 3113 } 3114 3115 // IdentNeedsQuotes returns true if the ident string given would require quotes. 3116 func IdentNeedsQuotes(ident string) bool { 3117 // check if this identifier is a keyword 3118 tok := Lookup(ident) 3119 if tok != IDENT { 3120 return true 3121 } 3122 for i, r := range ident { 3123 if i == 0 && !isIdentFirstChar(r) { 3124 return true 3125 } else if i > 0 && !isIdentChar(r) { 3126 return true 3127 } 3128 } 3129 return false 3130 } 3131 3132 // isDateString returns true if the string looks like a date-only time literal. 3133 func isDateString(s string) bool { return dateStringRegexp.MatchString(s) } 3134 3135 // isDateTimeString returns true if the string looks like a date+time time literal. 3136 func isDateTimeString(s string) bool { return dateTimeStringRegexp.MatchString(s) } 3137 3138 var dateStringRegexp = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`) 3139 var dateTimeStringRegexp = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}.+`) 3140 3141 // ErrInvalidDuration is returned when parsing a malformed duration. 3142 var ErrInvalidDuration = errors.New("invalid duration") 3143 3144 // ParseError represents an error that occurred during parsing. 3145 type ParseError struct { 3146 Message string 3147 Found string 3148 Expected []string 3149 Pos Pos 3150 } 3151 3152 // newParseError returns a new instance of ParseError. 3153 func newParseError(found string, expected []string, pos Pos) *ParseError { 3154 return &ParseError{Found: found, Expected: expected, Pos: pos} 3155 } 3156 3157 // Error returns the string representation of the error. 3158 func (e *ParseError) Error() string { 3159 if e.Message != "" { 3160 return fmt.Sprintf("%s at line %d, char %d", e.Message, e.Pos.Line+1, e.Pos.Char+1) 3161 } 3162 return fmt.Sprintf("found %s, expected %s at line %d, char %d", e.Found, strings.Join(e.Expected, ", "), e.Pos.Line+1, e.Pos.Char+1) 3163 }