Debian Codegraph @

token.go

raw symbols SCIP
1 /*
2 Copyright 2017 Google Inc.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package sqlparser
18
19 import (
20 "bytes"
21 "errors"
22 "fmt"
23 "io"
24
25 "github.com/xwb1989/sqlparser/dependency/bytes2"
26 "github.com/xwb1989/sqlparser/dependency/sqltypes"
27 )
28
29 const (
30 defaultBufSize = 4096
31 eofChar = 0x100
32 )
33
34 // Tokenizer is the struct used to generate SQL
35 // tokens for the parser.
36 type Tokenizer struct {
37 InStream io.Reader
38 AllowComments bool
39 ForceEOF bool
40 lastChar uint16
41 Position int
42 lastToken []byte
43 LastError error
44 posVarIndex int
45 ParseTree Statement
46 partialDDL *DDL
47 nesting int
48 multi bool
49 specialComment *Tokenizer
50
51 buf []byte
52 bufPos int
53 bufSize int
54 }
55
56 // NewStringTokenizer creates a new Tokenizer for the
57 // sql string.
58 func NewStringTokenizer(sql string) *Tokenizer {
59 buf := []byte(sql)
60 return &Tokenizer{
61 buf: buf,
62 bufSize: len(buf),
63 }
64 }
65
66 // NewTokenizer creates a new Tokenizer reading a sql
67 // string from the io.Reader.
68 func NewTokenizer(r io.Reader) *Tokenizer {
69 return &Tokenizer{
70 InStream: r,
71 buf: make([]byte, defaultBufSize),
72 }
73 }
74
75 // keywords is a map of mysql keywords that fall into two categories:
76 // 1) keywords considered reserved by MySQL
77 // 2) keywords for us to handle specially in sql.y
78 //
79 // Those marked as UNUSED are likely reserved keywords. We add them here so that
80 // when rewriting queries we can properly backtick quote them so they don't cause issues
81 //
82 // NOTE: If you add new keywords, add them also to the reserved_keywords or
83 // non_reserved_keywords grammar in sql.y -- this will allow the keyword to be used
84 // in identifiers. See the docs for each grammar to determine which one to put it into.
85 var keywords = map[string]int{
86 "accessible": UNUSED,
87 "add": ADD,
88 "against": AGAINST,
89 "all": ALL,
90 "alter": ALTER,
91 "analyze": ANALYZE,
92 "and": AND,
93 "as": AS,
94 "asc": ASC,
95 "asensitive": UNUSED,
96 "auto_increment": AUTO_INCREMENT,
97 "before": UNUSED,
98 "begin": BEGIN,
99 "between": BETWEEN,
100 "bigint": BIGINT,
101 "binary": BINARY,
102 "_binary": UNDERSCORE_BINARY,
103 "bit": BIT,
104 "blob": BLOB,
105 "bool": BOOL,
106 "boolean": BOOLEAN,
107 "both": UNUSED,
108 "by": BY,
109 "call": UNUSED,
110 "cascade": UNUSED,
111 "case": CASE,
112 "cast": CAST,
113 "change": UNUSED,
114 "char": CHAR,
115 "character": CHARACTER,
116 "charset": CHARSET,
117 "check": UNUSED,
118 "collate": COLLATE,
119 "column": COLUMN,
120 "comment": COMMENT_KEYWORD,
121 "committed": COMMITTED,
122 "commit": COMMIT,
123 "condition": UNUSED,
124 "constraint": CONSTRAINT,
125 "continue": UNUSED,
126 "convert": CONVERT,
127 "substr": SUBSTR,
128 "substring": SUBSTRING,
129 "create": CREATE,
130 "cross": CROSS,
131 "current_date": CURRENT_DATE,
132 "current_time": CURRENT_TIME,
133 "current_timestamp": CURRENT_TIMESTAMP,
134 "current_user": UNUSED,
135 "cursor": UNUSED,
136 "database": DATABASE,
137 "databases": DATABASES,
138 "day_hour": UNUSED,
139 "day_microsecond": UNUSED,
140 "day_minute": UNUSED,
141 "day_second": UNUSED,
142 "date": DATE,
143 "datetime": DATETIME,
144 "dec": UNUSED,
145 "decimal": DECIMAL,
146 "declare": UNUSED,
147 "default": DEFAULT,
148 "delayed": UNUSED,
149 "delete": DELETE,
150 "desc": DESC,
151 "describe": DESCRIBE,
152 "deterministic": UNUSED,
153 "distinct": DISTINCT,
154 "distinctrow": UNUSED,
155 "div": DIV,
156 "double": DOUBLE,
157 "drop": DROP,
158 "duplicate": DUPLICATE,
159 "each": UNUSED,
160 "else": ELSE,
161 "elseif": UNUSED,
162 "enclosed": UNUSED,
163 "end": END,
164 "enum": ENUM,
165 "escape": ESCAPE,
166 "escaped": UNUSED,
167 "exists": EXISTS,
168 "exit": UNUSED,
169 "explain": EXPLAIN,
170 "expansion": EXPANSION,
171 "extended": EXTENDED,
172 "false": FALSE,
173 "fetch": UNUSED,
174 "float": FLOAT_TYPE,
175 "float4": UNUSED,
176 "float8": UNUSED,
177 "for": FOR,
178 "force": FORCE,
179 "foreign": FOREIGN,
180 "from": FROM,
181 "full": FULL,
182 "fulltext": FULLTEXT,
183 "generated": UNUSED,
184 "geometry": GEOMETRY,
185 "geometrycollection": GEOMETRYCOLLECTION,
186 "get": UNUSED,
187 "global": GLOBAL,
188 "grant": UNUSED,
189 "group": GROUP,
190 "group_concat": GROUP_CONCAT,
191 "having": HAVING,
192 "high_priority": UNUSED,
193 "hour_microsecond": UNUSED,
194 "hour_minute": UNUSED,
195 "hour_second": UNUSED,
196 "if": IF,
197 "ignore": IGNORE,
198 "in": IN,
199 "index": INDEX,
200 "infile": UNUSED,
201 "inout": UNUSED,
202 "inner": INNER,
203 "insensitive": UNUSED,
204 "insert": INSERT,
205 "int": INT,
206 "int1": UNUSED,
207 "int2": UNUSED,
208 "int3": UNUSED,
209 "int4": UNUSED,
210 "int8": UNUSED,
211 "integer": INTEGER,
212 "interval": INTERVAL,
213 "into": INTO,
214 "io_after_gtids": UNUSED,
215 "is": IS,
216 "isolation": ISOLATION,
217 "iterate": UNUSED,
218 "join": JOIN,
219 "json": JSON,
220 "key": KEY,
221 "keys": KEYS,
222 "key_block_size": KEY_BLOCK_SIZE,
223 "kill": UNUSED,
224 "language": LANGUAGE,
225 "last_insert_id": LAST_INSERT_ID,
226 "leading": UNUSED,
227 "leave": UNUSED,
228 "left": LEFT,
229 "less": LESS,
230 "level": LEVEL,
231 "like": LIKE,
232 "limit": LIMIT,
233 "linear": UNUSED,
234 "lines": UNUSED,
235 "linestring": LINESTRING,
236 "load": UNUSED,
237 "localtime": LOCALTIME,
238 "localtimestamp": LOCALTIMESTAMP,
239 "lock": LOCK,
240 "long": UNUSED,
241 "longblob": LONGBLOB,
242 "longtext": LONGTEXT,
243 "loop": UNUSED,
244 "low_priority": UNUSED,
245 "master_bind": UNUSED,
246 "match": MATCH,
247 "maxvalue": MAXVALUE,
248 "mediumblob": MEDIUMBLOB,
249 "mediumint": MEDIUMINT,
250 "mediumtext": MEDIUMTEXT,
251 "middleint": UNUSED,
252 "minute_microsecond": UNUSED,
253 "minute_second": UNUSED,
254 "mod": MOD,
255 "mode": MODE,
256 "modifies": UNUSED,
257 "multilinestring": MULTILINESTRING,
258 "multipoint": MULTIPOINT,
259 "multipolygon": MULTIPOLYGON,
260 "names": NAMES,
261 "natural": NATURAL,
262 "nchar": NCHAR,
263 "next": NEXT,
264 "not": NOT,
265 "no_write_to_binlog": UNUSED,
266 "null": NULL,
267 "numeric": NUMERIC,
268 "offset": OFFSET,
269 "on": ON,
270 "only": ONLY,
271 "optimize": OPTIMIZE,
272 "optimizer_costs": UNUSED,
273 "option": UNUSED,
274 "optionally": UNUSED,
275 "or": OR,
276 "order": ORDER,
277 "out": UNUSED,
278 "outer": OUTER,
279 "outfile": UNUSED,
280 "partition": PARTITION,
281 "point": POINT,
282 "polygon": POLYGON,
283 "precision": UNUSED,
284 "primary": PRIMARY,
285 "processlist": PROCESSLIST,
286 "procedure": PROCEDURE,
287 "query": QUERY,
288 "range": UNUSED,
289 "read": READ,
290 "reads": UNUSED,
291 "read_write": UNUSED,
292 "real": REAL,
293 "references": UNUSED,
294 "regexp": REGEXP,
295 "release": UNUSED,
296 "rename": RENAME,
297 "reorganize": REORGANIZE,
298 "repair": REPAIR,
299 "repeat": UNUSED,
300 "repeatable": REPEATABLE,
301 "replace": REPLACE,
302 "require": UNUSED,
303 "resignal": UNUSED,
304 "restrict": UNUSED,
305 "return": UNUSED,
306 "revoke": UNUSED,
307 "right": RIGHT,
308 "rlike": REGEXP,
309 "rollback": ROLLBACK,
310 "schema": SCHEMA,
311 "schemas": UNUSED,
312 "second_microsecond": UNUSED,
313 "select": SELECT,
314 "sensitive": UNUSED,
315 "separator": SEPARATOR,
316 "serializable": SERIALIZABLE,
317 "session": SESSION,
318 "set": SET,
319 "share": SHARE,
320 "show": SHOW,
321 "signal": UNUSED,
322 "signed": SIGNED,
323 "smallint": SMALLINT,
324 "spatial": SPATIAL,
325 "specific": UNUSED,
326 "sql": UNUSED,
327 "sqlexception": UNUSED,
328 "sqlstate": UNUSED,
329 "sqlwarning": UNUSED,
330 "sql_big_result": UNUSED,
331 "sql_cache": SQL_CACHE,
332 "sql_calc_found_rows": UNUSED,
333 "sql_no_cache": SQL_NO_CACHE,
334 "sql_small_result": UNUSED,
335 "ssl": UNUSED,
336 "start": START,
337 "starting": UNUSED,
338 "status": STATUS,
339 "stored": UNUSED,
340 "straight_join": STRAIGHT_JOIN,
341 "stream": STREAM,
342 "table": TABLE,
343 "tables": TABLES,
344 "terminated": UNUSED,
345 "text": TEXT,
346 "than": THAN,
347 "then": THEN,
348 "time": TIME,
349 "timestamp": TIMESTAMP,
350 "tinyblob": TINYBLOB,
351 "tinyint": TINYINT,
352 "tinytext": TINYTEXT,
353 "to": TO,
354 "trailing": UNUSED,
355 "transaction": TRANSACTION,
356 "trigger": TRIGGER,
357 "true": TRUE,
358 "truncate": TRUNCATE,
359 "uncommitted": UNCOMMITTED,
360 "undo": UNUSED,
361 "union": UNION,
362 "unique": UNIQUE,
363 "unlock": UNUSED,
364 "unsigned": UNSIGNED,
365 "update": UPDATE,
366 "usage": UNUSED,
367 "use": USE,
368 "using": USING,
369 "utc_date": UTC_DATE,
370 "utc_time": UTC_TIME,
371 "utc_timestamp": UTC_TIMESTAMP,
372 "values": VALUES,
373 "variables": VARIABLES,
374 "varbinary": VARBINARY,
375 "varchar": VARCHAR,
376 "varcharacter": UNUSED,
377 "varying": UNUSED,
378 "virtual": UNUSED,
379 "vindex": VINDEX,
380 "vindexes": VINDEXES,
381 "view": VIEW,
382 "vitess_keyspaces": VITESS_KEYSPACES,
383 "vitess_shards": VITESS_SHARDS,
384 "vitess_tablets": VITESS_TABLETS,
385 "vschema_tables": VSCHEMA_TABLES,
386 "when": WHEN,
387 "where": WHERE,
388 "while": UNUSED,
389 "with": WITH,
390 "write": WRITE,
391 "xor": UNUSED,
392 "year": YEAR,
393 "year_month": UNUSED,
394 "zerofill": ZEROFILL,
395 }
396
397 // keywordStrings contains the reverse mapping of token to keyword strings
398 var keywordStrings = map[int]string{}
399
400 func init() {
401 for str, id := range keywords {
402 if id == UNUSED {
403 continue
404 }
405 keywordStrings[id] = str
406 }
407 }
408
409 // KeywordString returns the string corresponding to the given keyword
410 func KeywordString(id int) string {
411 str, ok := keywordStrings[id]
412 if !ok {
413 return ""
414 }
415 return str
416 }
417
418 // Lex returns the next token form the Tokenizer.
419 // This function is used by go yacc.
420 func (tkn *Tokenizer) Lex(lval *yySymType) int {
421 typ, val := tkn.Scan()
422 for typ == COMMENT {
423 if tkn.AllowComments {
424 break
425 }
426 typ, val = tkn.Scan()
427 }
428 lval.bytes = val
429 tkn.lastToken = val
430 return typ
431 }
432
433 // Error is called by go yacc if there's a parsing error.
434 func (tkn *Tokenizer) Error(err string) {
435 buf := &bytes2.Buffer{}
436 if tkn.lastToken != nil {
437 fmt.Fprintf(buf, "%s at position %v near '%s'", err, tkn.Position, tkn.lastToken)
438 } else {
439 fmt.Fprintf(buf, "%s at position %v", err, tkn.Position)
440 }
441 tkn.LastError = errors.New(buf.String())
442
443 // Try and re-sync to the next statement
444 if tkn.lastChar != ';' {
445 tkn.skipStatement()
446 }
447 }
448
449 // Scan scans the tokenizer for the next token and returns
450 // the token type and an optional value.
451 func (tkn *Tokenizer) Scan() (int, []byte) {
452 if tkn.specialComment != nil {
453 // Enter specialComment scan mode.
454 // for scanning such kind of comment: /*! MySQL-specific code */
455 specialComment := tkn.specialComment
456 tok, val := specialComment.Scan()
457 if tok != 0 {
458 // return the specialComment scan result as the result
459 return tok, val
460 }
461 // leave specialComment scan mode after all stream consumed.
462 tkn.specialComment = nil
463 }
464 if tkn.lastChar == 0 {
465 tkn.next()
466 }
467
468 if tkn.ForceEOF {
469 tkn.skipStatement()
470 return 0, nil
471 }
472
473 tkn.skipBlank()
474 switch ch := tkn.lastChar; {
475 case isLetter(ch):
476 tkn.next()
477 if ch == 'X' || ch == 'x' {
478 if tkn.lastChar == '\'' {
479 tkn.next()
480 return tkn.scanHex()
481 }
482 }
483 if ch == 'B' || ch == 'b' {
484 if tkn.lastChar == '\'' {
485 tkn.next()
486 return tkn.scanBitLiteral()
487 }
488 }
489 isDbSystemVariable := false
490 if ch == '@' && tkn.lastChar == '@' {
491 isDbSystemVariable = true
492 }
493 return tkn.scanIdentifier(byte(ch), isDbSystemVariable)
494 case isDigit(ch):
495 return tkn.scanNumber(false)
496 case ch == ':':
497 return tkn.scanBindVar()
498 case ch == ';' && tkn.multi:
499 return 0, nil
500 default:
501 tkn.next()
502 switch ch {
503 case eofChar:
504 return 0, nil
505 case '=', ',', ';', '(', ')', '+', '*', '%', '^', '~':
506 return int(ch), nil
507 case '&':
508 if tkn.lastChar == '&' {
509 tkn.next()
510 return AND, nil
511 }
512 return int(ch), nil
513 case '|':
514 if tkn.lastChar == '|' {
515 tkn.next()
516 return OR, nil
517 }
518 return int(ch), nil
519 case '?':
520 tkn.posVarIndex++
521 buf := new(bytes2.Buffer)
522 fmt.Fprintf(buf, ":v%d", tkn.posVarIndex)
523 return VALUE_ARG, buf.Bytes()
524 case '.':
525 if isDigit(tkn.lastChar) {
526 return tkn.scanNumber(true)
527 }
528 return int(ch), nil
529 case '/':
530 switch tkn.lastChar {
531 case '/':
532 tkn.next()
533 return tkn.scanCommentType1("//")
534 case '*':
535 tkn.next()
536 switch tkn.lastChar {
537 case '!':
538 return tkn.scanMySQLSpecificComment()
539 default:
540 return tkn.scanCommentType2()
541 }
542 default:
543 return int(ch), nil
544 }
545 case '#':
546 return tkn.scanCommentType1("#")
547 case '-':
548 switch tkn.lastChar {
549 case '-':
550 tkn.next()
551 return tkn.scanCommentType1("--")
552 case '>':
553 tkn.next()
554 if tkn.lastChar == '>' {
555 tkn.next()
556 return JSON_UNQUOTE_EXTRACT_OP, nil
557 }
558 return JSON_EXTRACT_OP, nil
559 }
560 return int(ch), nil
561 case '<':
562 switch tkn.lastChar {
563 case '>':
564 tkn.next()
565 return NE, nil
566 case '<':
567 tkn.next()
568 return SHIFT_LEFT, nil
569 case '=':
570 tkn.next()
571 switch tkn.lastChar {
572 case '>':
573 tkn.next()
574 return NULL_SAFE_EQUAL, nil
575 default:
576 return LE, nil
577 }
578 default:
579 return int(ch), nil
580 }
581 case '>':
582 switch tkn.lastChar {
583 case '=':
584 tkn.next()
585 return GE, nil
586 case '>':
587 tkn.next()
588 return SHIFT_RIGHT, nil
589 default:
590 return int(ch), nil
591 }
592 case '!':
593 if tkn.lastChar == '=' {
594 tkn.next()
595 return NE, nil
596 }
597 return int(ch), nil
598 case '\'', '"':
599 return tkn.scanString(ch, STRING)
600 case '`':
601 return tkn.scanLiteralIdentifier()
602 default:
603 return LEX_ERROR, []byte{byte(ch)}
604 }
605 }
606 }
607
608 // skipStatement scans until the EOF, or end of statement is encountered.
609 func (tkn *Tokenizer) skipStatement() {
610 ch := tkn.lastChar
611 for ch != ';' && ch != eofChar {
612 tkn.next()
613 ch = tkn.lastChar
614 }
615 }
616
617 func (tkn *Tokenizer) skipBlank() {
618 ch := tkn.lastChar
619 for ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' {
620 tkn.next()
621 ch = tkn.lastChar
622 }
623 }
624
625 func (tkn *Tokenizer) scanIdentifier(firstByte byte, isDbSystemVariable bool) (int, []byte) {
626 buffer := &bytes2.Buffer{}
627 buffer.WriteByte(firstByte)
628 for isLetter(tkn.lastChar) || isDigit(tkn.lastChar) || (isDbSystemVariable && isCarat(tkn.lastChar)) {
629 buffer.WriteByte(byte(tkn.lastChar))
630 tkn.next()
631 }
632 lowered := bytes.ToLower(buffer.Bytes())
633 loweredStr := string(lowered)
634 if keywordID, found := keywords[loweredStr]; found {
635 return keywordID, lowered
636 }
637 // dual must always be case-insensitive
638 if loweredStr == "dual" {
639 return ID, lowered
640 }
641 return ID, buffer.Bytes()
642 }
643
644 func (tkn *Tokenizer) scanHex() (int, []byte) {
645 buffer := &bytes2.Buffer{}
646 tkn.scanMantissa(16, buffer)
647 if tkn.lastChar != '\'' {
648 return LEX_ERROR, buffer.Bytes()
649 }
650 tkn.next()
651 if buffer.Len()%2 != 0 {
652 return LEX_ERROR, buffer.Bytes()
653 }
654 return HEX, buffer.Bytes()
655 }
656
657 func (tkn *Tokenizer) scanBitLiteral() (int, []byte) {
658 buffer := &bytes2.Buffer{}
659 tkn.scanMantissa(2, buffer)
660 if tkn.lastChar != '\'' {
661 return LEX_ERROR, buffer.Bytes()
662 }
663 tkn.next()
664 return BIT_LITERAL, buffer.Bytes()
665 }
666
667 func (tkn *Tokenizer) scanLiteralIdentifier() (int, []byte) {
668 buffer := &bytes2.Buffer{}
669 backTickSeen := false
670 for {
671 if backTickSeen {
672 if tkn.lastChar != '`' {
673 break
674 }
675 backTickSeen = false
676 buffer.WriteByte('`')
677 tkn.next()
678 continue
679 }
680 // The previous char was not a backtick.
681 switch tkn.lastChar {
682 case '`':
683 backTickSeen = true
684 case eofChar:
685 // Premature EOF.
686 return LEX_ERROR, buffer.Bytes()
687 default:
688 buffer.WriteByte(byte(tkn.lastChar))
689 }
690 tkn.next()
691 }
692 if buffer.Len() == 0 {
693 return LEX_ERROR, buffer.Bytes()
694 }
695 return ID, buffer.Bytes()
696 }
697
698 func (tkn *Tokenizer) scanBindVar() (int, []byte) {
699 buffer := &bytes2.Buffer{}
700 buffer.WriteByte(byte(tkn.lastChar))
701 token := VALUE_ARG
702 tkn.next()
703 if tkn.lastChar == ':' {
704 token = LIST_ARG
705 buffer.WriteByte(byte(tkn.lastChar))
706 tkn.next()
707 }
708 if !isLetter(tkn.lastChar) {
709 return LEX_ERROR, buffer.Bytes()
710 }
711 for isLetter(tkn.lastChar) || isDigit(tkn.lastChar) || tkn.lastChar == '.' {
712 buffer.WriteByte(byte(tkn.lastChar))
713 tkn.next()
714 }
715 return token, buffer.Bytes()
716 }
717
718 func (tkn *Tokenizer) scanMantissa(base int, buffer *bytes2.Buffer) {
719 for digitVal(tkn.lastChar) < base {
720 tkn.consumeNext(buffer)
721 }
722 }
723
724 func (tkn *Tokenizer) scanNumber(seenDecimalPoint bool) (int, []byte) {
725 token := INTEGRAL
726 buffer := &bytes2.Buffer{}
727 if seenDecimalPoint {
728 token = FLOAT
729 buffer.WriteByte('.')
730 tkn.scanMantissa(10, buffer)
731 goto exponent
732 }
733
734 // 0x construct.
735 if tkn.lastChar == '0' {
736 tkn.consumeNext(buffer)
737 if tkn.lastChar == 'x' || tkn.lastChar == 'X' {
738 token = HEXNUM
739 tkn.consumeNext(buffer)
740 tkn.scanMantissa(16, buffer)
741 goto exit
742 }
743 }
744
745 tkn.scanMantissa(10, buffer)
746
747 if tkn.lastChar == '.' {
748 token = FLOAT
749 tkn.consumeNext(buffer)
750 tkn.scanMantissa(10, buffer)
751 }
752
753 exponent:
754 if tkn.lastChar == 'e' || tkn.lastChar == 'E' {
755 token = FLOAT
756 tkn.consumeNext(buffer)
757 if tkn.lastChar == '+' || tkn.lastChar == '-' {
758 tkn.consumeNext(buffer)
759 }
760 tkn.scanMantissa(10, buffer)
761 }
762
763 exit:
764 // A letter cannot immediately follow a number.
765 if isLetter(tkn.lastChar) {
766 return LEX_ERROR, buffer.Bytes()
767 }
768
769 return token, buffer.Bytes()
770 }
771
772 func (tkn *Tokenizer) scanString(delim uint16, typ int) (int, []byte) {
773 var buffer bytes2.Buffer
774 for {
775 ch := tkn.lastChar
776 if ch == eofChar {
777 // Unterminated string.
778 return LEX_ERROR, buffer.Bytes()
779 }
780
781 if ch != delim && ch != '\\' {
782 buffer.WriteByte(byte(ch))
783
784 // Scan ahead to the next interesting character.
785 start := tkn.bufPos
786 for ; tkn.bufPos < tkn.bufSize; tkn.bufPos++ {
787 ch = uint16(tkn.buf[tkn.bufPos])
788 if ch == delim || ch == '\\' {
789 break
790 }
791 }
792
793 buffer.Write(tkn.buf[start:tkn.bufPos])
794 tkn.Position += (tkn.bufPos - start)
795
796 if tkn.bufPos >= tkn.bufSize {
797 // Reached the end of the buffer without finding a delim or
798 // escape character.
799 tkn.next()
800 continue
801 }
802
803 tkn.bufPos++
804 tkn.Position++
805 }
806 tkn.next() // Read one past the delim or escape character.
807
808 if ch == '\\' {
809 if tkn.lastChar == eofChar {
810 // String terminates mid escape character.
811 return LEX_ERROR, buffer.Bytes()
812 }
813 if decodedChar := sqltypes.SQLDecodeMap[byte(tkn.lastChar)]; decodedChar == sqltypes.DontEscape {
814 ch = tkn.lastChar
815 } else {
816 ch = uint16(decodedChar)
817 }
818
819 } else if ch == delim && tkn.lastChar != delim {
820 // Correctly terminated string, which is not a double delim.
821 break
822 }
823
824 buffer.WriteByte(byte(ch))
825 tkn.next()
826 }
827
828 return typ, buffer.Bytes()
829 }
830
831 func (tkn *Tokenizer) scanCommentType1(prefix string) (int, []byte) {
832 buffer := &bytes2.Buffer{}
833 buffer.WriteString(prefix)
834 for tkn.lastChar != eofChar {
835 if tkn.lastChar == '\n' {
836 tkn.consumeNext(buffer)
837 break
838 }
839 tkn.consumeNext(buffer)
840 }
841 return COMMENT, buffer.Bytes()
842 }
843
844 func (tkn *Tokenizer) scanCommentType2() (int, []byte) {
845 buffer := &bytes2.Buffer{}
846 buffer.WriteString("/*")
847 for {
848 if tkn.lastChar == '*' {
849 tkn.consumeNext(buffer)
850 if tkn.lastChar == '/' {
851 tkn.consumeNext(buffer)
852 break
853 }
854 continue
855 }
856 if tkn.lastChar == eofChar {
857 return LEX_ERROR, buffer.Bytes()
858 }
859 tkn.consumeNext(buffer)
860 }
861 return COMMENT, buffer.Bytes()
862 }
863
864 func (tkn *Tokenizer) scanMySQLSpecificComment() (int, []byte) {
865 buffer := &bytes2.Buffer{}
866 buffer.WriteString("/*!")
867 tkn.next()
868 for {
869 if tkn.lastChar == '*' {
870 tkn.consumeNext(buffer)
871 if tkn.lastChar == '/' {
872 tkn.consumeNext(buffer)
873 break
874 }
875 continue
876 }
877 if tkn.lastChar == eofChar {
878 return LEX_ERROR, buffer.Bytes()
879 }
880 tkn.consumeNext(buffer)
881 }
882 _, sql := ExtractMysqlComment(buffer.String())
883 tkn.specialComment = NewStringTokenizer(sql)
884 return tkn.Scan()
885 }
886
887 func (tkn *Tokenizer) consumeNext(buffer *bytes2.Buffer) {
888 if tkn.lastChar == eofChar {
889 // This should never happen.
890 panic("unexpected EOF")
891 }
892 buffer.WriteByte(byte(tkn.lastChar))
893 tkn.next()
894 }
895
896 func (tkn *Tokenizer) next() {
897 if tkn.bufPos >= tkn.bufSize && tkn.InStream != nil {
898 // Try and refill the buffer
899 var err error
900 tkn.bufPos = 0
901 if tkn.bufSize, err = tkn.InStream.Read(tkn.buf); err != io.EOF && err != nil {
902 tkn.LastError = err
903 }
904 }
905
906 if tkn.bufPos >= tkn.bufSize {
907 if tkn.lastChar != eofChar {
908 tkn.Position++
909 tkn.lastChar = eofChar
910 }
911 } else {
912 tkn.Position++
913 tkn.lastChar = uint16(tkn.buf[tkn.bufPos])
914 tkn.bufPos++
915 }
916 }
917
918 // reset clears any internal state.
919 func (tkn *Tokenizer) reset() {
920 tkn.ParseTree = nil
921 tkn.partialDDL = nil
922 tkn.specialComment = nil
923 tkn.posVarIndex = 0
924 tkn.nesting = 0
925 tkn.ForceEOF = false
926 }
927
928 func isLetter(ch uint16) bool {
929 return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch == '@'
930 }
931
932 func isCarat(ch uint16) bool {
933 return ch == '.' || ch == '\'' || ch == '"' || ch == '`'
934 }
935
936 func digitVal(ch uint16) int {
937 switch {
938 case '0' <= ch && ch <= '9':
939 return int(ch) - '0'
940 case 'a' <= ch && ch <= 'f':
941 return int(ch) - 'a' + 10
942 case 'A' <= ch && ch <= 'F':
943 return int(ch) - 'A' + 10
944 }
945 return 16 // larger than any legal digit val
946 }
947
948 func isDigit(ch uint16) bool {
949 return '0' <= ch && ch <= '9'
950 }