sqlglot.tokens
1from __future__ import annotations 2 3import os 4import typing as t 5from enum import auto 6 7from sqlglot.errors import SqlglotError, TokenError 8from sqlglot.helper import AutoName 9from sqlglot.trie import TrieResult, in_trie, new_trie 10 11if t.TYPE_CHECKING: 12 from sqlglot.dialects.dialect import DialectType 13 14 15try: 16 from sqlglotrs import ( # type: ignore 17 Tokenizer as RsTokenizer, 18 TokenizerDialectSettings as RsTokenizerDialectSettings, 19 TokenizerSettings as RsTokenizerSettings, 20 TokenTypeSettings as RsTokenTypeSettings, 21 ) 22 23 USE_RS_TOKENIZER = os.environ.get("SQLGLOTRS_TOKENIZER", "1") == "1" 24except ImportError: 25 USE_RS_TOKENIZER = False 26 27 28class TokenType(AutoName): 29 L_PAREN = auto() 30 R_PAREN = auto() 31 L_BRACKET = auto() 32 R_BRACKET = auto() 33 L_BRACE = auto() 34 R_BRACE = auto() 35 COMMA = auto() 36 DOT = auto() 37 DASH = auto() 38 PLUS = auto() 39 COLON = auto() 40 DCOLON = auto() 41 DQMARK = auto() 42 SEMICOLON = auto() 43 STAR = auto() 44 BACKSLASH = auto() 45 SLASH = auto() 46 LT = auto() 47 LTE = auto() 48 GT = auto() 49 GTE = auto() 50 NOT = auto() 51 EQ = auto() 52 NEQ = auto() 53 NULLSAFE_EQ = auto() 54 COLON_EQ = auto() 55 AND = auto() 56 OR = auto() 57 AMP = auto() 58 DPIPE = auto() 59 PIPE = auto() 60 PIPE_SLASH = auto() 61 DPIPE_SLASH = auto() 62 CARET = auto() 63 CARET_AT = auto() 64 TILDA = auto() 65 ARROW = auto() 66 DARROW = auto() 67 FARROW = auto() 68 HASH = auto() 69 HASH_ARROW = auto() 70 DHASH_ARROW = auto() 71 LR_ARROW = auto() 72 DAT = auto() 73 LT_AT = auto() 74 AT_GT = auto() 75 DOLLAR = auto() 76 PARAMETER = auto() 77 SESSION_PARAMETER = auto() 78 DAMP = auto() 79 XOR = auto() 80 DSTAR = auto() 81 82 BLOCK_START = auto() 83 BLOCK_END = auto() 84 85 SPACE = auto() 86 BREAK = auto() 87 88 STRING = auto() 89 NUMBER = auto() 90 IDENTIFIER = auto() 91 DATABASE = auto() 92 COLUMN = auto() 93 COLUMN_DEF = auto() 94 SCHEMA = auto() 95 TABLE = auto() 96 WAREHOUSE = auto() 97 STREAMLIT = auto() 98 VAR = auto() 99 BIT_STRING = auto() 100 HEX_STRING = auto() 101 BYTE_STRING = auto() 102 NATIONAL_STRING = auto() 103 RAW_STRING = auto() 104 HEREDOC_STRING = auto() 105 UNICODE_STRING = auto() 106 107 # types 108 BIT = auto() 109 BOOLEAN = auto() 110 TINYINT = auto() 111 UTINYINT = auto() 112 SMALLINT = auto() 113 USMALLINT = auto() 114 MEDIUMINT = auto() 115 UMEDIUMINT = auto() 116 INT = auto() 117 UINT = auto() 118 BIGINT = auto() 119 UBIGINT = auto() 120 INT128 = auto() 121 UINT128 = auto() 122 INT256 = auto() 123 UINT256 = auto() 124 FLOAT = auto() 125 DOUBLE = auto() 126 DECIMAL = auto() 127 DECIMAL32 = auto() 128 DECIMAL64 = auto() 129 DECIMAL128 = auto() 130 DECIMAL256 = auto() 131 UDECIMAL = auto() 132 BIGDECIMAL = auto() 133 CHAR = auto() 134 NCHAR = auto() 135 VARCHAR = auto() 136 NVARCHAR = auto() 137 BPCHAR = auto() 138 TEXT = auto() 139 MEDIUMTEXT = auto() 140 LONGTEXT = auto() 141 MEDIUMBLOB = auto() 142 LONGBLOB = auto() 143 TINYBLOB = auto() 144 TINYTEXT = auto() 145 NAME = auto() 146 BINARY = auto() 147 VARBINARY = auto() 148 JSON = auto() 149 JSONB = auto() 150 TIME = auto() 151 TIMETZ = auto() 152 TIMESTAMP = auto() 153 TIMESTAMPTZ = auto() 154 TIMESTAMPLTZ = auto() 155 TIMESTAMPNTZ = auto() 156 TIMESTAMP_S = auto() 157 TIMESTAMP_MS = auto() 158 TIMESTAMP_NS = auto() 159 DATETIME = auto() 160 DATETIME2 = auto() 161 DATETIME64 = auto() 162 SMALLDATETIME = auto() 163 DATE = auto() 164 DATE32 = auto() 165 INT4RANGE = auto() 166 INT4MULTIRANGE = auto() 167 INT8RANGE = auto() 168 INT8MULTIRANGE = auto() 169 NUMRANGE = auto() 170 NUMMULTIRANGE = auto() 171 TSRANGE = auto() 172 TSMULTIRANGE = auto() 173 TSTZRANGE = auto() 174 TSTZMULTIRANGE = auto() 175 DATERANGE = auto() 176 DATEMULTIRANGE = auto() 177 UUID = auto() 178 GEOGRAPHY = auto() 179 NULLABLE = auto() 180 GEOMETRY = auto() 181 POINT = auto() 182 RING = auto() 183 LINESTRING = auto() 184 MULTILINESTRING = auto() 185 POLYGON = auto() 186 MULTIPOLYGON = auto() 187 HLLSKETCH = auto() 188 HSTORE = auto() 189 SUPER = auto() 190 SERIAL = auto() 191 SMALLSERIAL = auto() 192 BIGSERIAL = auto() 193 XML = auto() 194 YEAR = auto() 195 UNIQUEIDENTIFIER = auto() 196 USERDEFINED = auto() 197 MONEY = auto() 198 SMALLMONEY = auto() 199 ROWVERSION = auto() 200 IMAGE = auto() 201 VARIANT = auto() 202 OBJECT = auto() 203 INET = auto() 204 IPADDRESS = auto() 205 IPPREFIX = auto() 206 IPV4 = auto() 207 IPV6 = auto() 208 ENUM = auto() 209 ENUM8 = auto() 210 ENUM16 = auto() 211 FIXEDSTRING = auto() 212 LOWCARDINALITY = auto() 213 NESTED = auto() 214 AGGREGATEFUNCTION = auto() 215 SIMPLEAGGREGATEFUNCTION = auto() 216 TDIGEST = auto() 217 UNKNOWN = auto() 218 VECTOR = auto() 219 220 # keywords 221 ALIAS = auto() 222 ALTER = auto() 223 ALWAYS = auto() 224 ALL = auto() 225 ANTI = auto() 226 ANY = auto() 227 APPLY = auto() 228 ARRAY = auto() 229 ASC = auto() 230 ASOF = auto() 231 ATTACH = auto() 232 AUTO_INCREMENT = auto() 233 BEGIN = auto() 234 BETWEEN = auto() 235 BULK_COLLECT_INTO = auto() 236 CACHE = auto() 237 CASE = auto() 238 CHARACTER_SET = auto() 239 CLUSTER_BY = auto() 240 COLLATE = auto() 241 COMMAND = auto() 242 COMMENT = auto() 243 COMMIT = auto() 244 CONNECT_BY = auto() 245 CONSTRAINT = auto() 246 COPY = auto() 247 CREATE = auto() 248 CROSS = auto() 249 CUBE = auto() 250 CURRENT_DATE = auto() 251 CURRENT_DATETIME = auto() 252 CURRENT_TIME = auto() 253 CURRENT_TIMESTAMP = auto() 254 CURRENT_USER = auto() 255 DECLARE = auto() 256 DEFAULT = auto() 257 DELETE = auto() 258 DESC = auto() 259 DESCRIBE = auto() 260 DETACH = auto() 261 DICTIONARY = auto() 262 DISTINCT = auto() 263 DISTRIBUTE_BY = auto() 264 DIV = auto() 265 DROP = auto() 266 ELSE = auto() 267 END = auto() 268 ESCAPE = auto() 269 EXCEPT = auto() 270 EXECUTE = auto() 271 EXISTS = auto() 272 FALSE = auto() 273 FETCH = auto() 274 FILTER = auto() 275 FINAL = auto() 276 FIRST = auto() 277 FOR = auto() 278 FORCE = auto() 279 FOREIGN_KEY = auto() 280 FORMAT = auto() 281 FROM = auto() 282 FULL = auto() 283 FUNCTION = auto() 284 GLOB = auto() 285 GLOBAL = auto() 286 GRANT = auto() 287 GROUP_BY = auto() 288 GROUPING_SETS = auto() 289 HAVING = auto() 290 HINT = auto() 291 IGNORE = auto() 292 ILIKE = auto() 293 ILIKE_ANY = auto() 294 IN = auto() 295 INDEX = auto() 296 INNER = auto() 297 INSERT = auto() 298 INTERSECT = auto() 299 INTERVAL = auto() 300 INTO = auto() 301 INTRODUCER = auto() 302 IRLIKE = auto() 303 IS = auto() 304 ISNULL = auto() 305 JOIN = auto() 306 JOIN_MARKER = auto() 307 KEEP = auto() 308 KEY = auto() 309 KILL = auto() 310 LANGUAGE = auto() 311 LATERAL = auto() 312 LEFT = auto() 313 LIKE = auto() 314 LIKE_ANY = auto() 315 LIMIT = auto() 316 LIST = auto() 317 LOAD = auto() 318 LOCK = auto() 319 MAP = auto() 320 MATCH_CONDITION = auto() 321 MATCH_RECOGNIZE = auto() 322 MEMBER_OF = auto() 323 MERGE = auto() 324 MOD = auto() 325 MODEL = auto() 326 NATURAL = auto() 327 NEXT = auto() 328 NOTNULL = auto() 329 NULL = auto() 330 OBJECT_IDENTIFIER = auto() 331 OFFSET = auto() 332 ON = auto() 333 ONLY = auto() 334 OPERATOR = auto() 335 ORDER_BY = auto() 336 ORDER_SIBLINGS_BY = auto() 337 ORDERED = auto() 338 ORDINALITY = auto() 339 OUTER = auto() 340 OVER = auto() 341 OVERLAPS = auto() 342 OVERWRITE = auto() 343 PARTITION = auto() 344 PARTITION_BY = auto() 345 PERCENT = auto() 346 PIVOT = auto() 347 PLACEHOLDER = auto() 348 POSITIONAL = auto() 349 PRAGMA = auto() 350 PREWHERE = auto() 351 PRIMARY_KEY = auto() 352 PROCEDURE = auto() 353 PROPERTIES = auto() 354 PSEUDO_TYPE = auto() 355 QUALIFY = auto() 356 QUOTE = auto() 357 RANGE = auto() 358 RECURSIVE = auto() 359 REFRESH = auto() 360 RENAME = auto() 361 REPLACE = auto() 362 RETURNING = auto() 363 REFERENCES = auto() 364 RIGHT = auto() 365 RLIKE = auto() 366 ROLLBACK = auto() 367 ROLLUP = auto() 368 ROW = auto() 369 ROWS = auto() 370 SELECT = auto() 371 SEMI = auto() 372 SEPARATOR = auto() 373 SEQUENCE = auto() 374 SERDE_PROPERTIES = auto() 375 SET = auto() 376 SETTINGS = auto() 377 SHOW = auto() 378 SIMILAR_TO = auto() 379 SOME = auto() 380 SORT_BY = auto() 381 START_WITH = auto() 382 STORAGE_INTEGRATION = auto() 383 STRAIGHT_JOIN = auto() 384 STRUCT = auto() 385 SUMMARIZE = auto() 386 TABLE_SAMPLE = auto() 387 TAG = auto() 388 TEMPORARY = auto() 389 TOP = auto() 390 THEN = auto() 391 TRUE = auto() 392 TRUNCATE = auto() 393 UNCACHE = auto() 394 UNION = auto() 395 UNNEST = auto() 396 UNPIVOT = auto() 397 UPDATE = auto() 398 USE = auto() 399 USING = auto() 400 VALUES = auto() 401 VIEW = auto() 402 VOLATILE = auto() 403 WHEN = auto() 404 WHERE = auto() 405 WINDOW = auto() 406 WITH = auto() 407 UNIQUE = auto() 408 VERSION_SNAPSHOT = auto() 409 TIMESTAMP_SNAPSHOT = auto() 410 OPTION = auto() 411 SINK = auto() 412 SOURCE = auto() 413 414 415_ALL_TOKEN_TYPES = list(TokenType) 416_TOKEN_TYPE_TO_INDEX = {token_type: i for i, token_type in enumerate(_ALL_TOKEN_TYPES)} 417 418 419class Token: 420 __slots__ = ("token_type", "text", "line", "col", "start", "end", "comments") 421 422 @classmethod 423 def number(cls, number: int) -> Token: 424 """Returns a NUMBER token with `number` as its text.""" 425 return cls(TokenType.NUMBER, str(number)) 426 427 @classmethod 428 def string(cls, string: str) -> Token: 429 """Returns a STRING token with `string` as its text.""" 430 return cls(TokenType.STRING, string) 431 432 @classmethod 433 def identifier(cls, identifier: str) -> Token: 434 """Returns an IDENTIFIER token with `identifier` as its text.""" 435 return cls(TokenType.IDENTIFIER, identifier) 436 437 @classmethod 438 def var(cls, var: str) -> Token: 439 """Returns an VAR token with `var` as its text.""" 440 return cls(TokenType.VAR, var) 441 442 def __init__( 443 self, 444 token_type: TokenType, 445 text: str, 446 line: int = 1, 447 col: int = 1, 448 start: int = 0, 449 end: int = 0, 450 comments: t.Optional[t.List[str]] = None, 451 ) -> None: 452 """Token initializer. 453 454 Args: 455 token_type: The TokenType Enum. 456 text: The text of the token. 457 line: The line that the token ends on. 458 col: The column that the token ends on. 459 start: The start index of the token. 460 end: The ending index of the token. 461 comments: The comments to attach to the token. 462 """ 463 self.token_type = token_type 464 self.text = text 465 self.line = line 466 self.col = col 467 self.start = start 468 self.end = end 469 self.comments = [] if comments is None else comments 470 471 def __repr__(self) -> str: 472 attributes = ", ".join(f"{k}: {getattr(self, k)}" for k in self.__slots__) 473 return f"<Token {attributes}>" 474 475 476class _Tokenizer(type): 477 def __new__(cls, clsname, bases, attrs): 478 klass = super().__new__(cls, clsname, bases, attrs) 479 480 def _convert_quotes(arr: t.List[str | t.Tuple[str, str]]) -> t.Dict[str, str]: 481 return dict( 482 (item, item) if isinstance(item, str) else (item[0], item[1]) for item in arr 483 ) 484 485 def _quotes_to_format( 486 token_type: TokenType, arr: t.List[str | t.Tuple[str, str]] 487 ) -> t.Dict[str, t.Tuple[str, TokenType]]: 488 return {k: (v, token_type) for k, v in _convert_quotes(arr).items()} 489 490 klass._QUOTES = _convert_quotes(klass.QUOTES) 491 klass._IDENTIFIERS = _convert_quotes(klass.IDENTIFIERS) 492 493 klass._FORMAT_STRINGS = { 494 **{ 495 p + s: (e, TokenType.NATIONAL_STRING) 496 for s, e in klass._QUOTES.items() 497 for p in ("n", "N") 498 }, 499 **_quotes_to_format(TokenType.BIT_STRING, klass.BIT_STRINGS), 500 **_quotes_to_format(TokenType.BYTE_STRING, klass.BYTE_STRINGS), 501 **_quotes_to_format(TokenType.HEX_STRING, klass.HEX_STRINGS), 502 **_quotes_to_format(TokenType.RAW_STRING, klass.RAW_STRINGS), 503 **_quotes_to_format(TokenType.HEREDOC_STRING, klass.HEREDOC_STRINGS), 504 **_quotes_to_format(TokenType.UNICODE_STRING, klass.UNICODE_STRINGS), 505 } 506 507 klass._STRING_ESCAPES = set(klass.STRING_ESCAPES) 508 klass._IDENTIFIER_ESCAPES = set(klass.IDENTIFIER_ESCAPES) 509 klass._COMMENTS = { 510 **dict( 511 (comment, None) if isinstance(comment, str) else (comment[0], comment[1]) 512 for comment in klass.COMMENTS 513 ), 514 "{#": "#}", # Ensure Jinja comments are tokenized correctly in all dialects 515 } 516 if klass.HINT_START in klass.KEYWORDS: 517 klass._COMMENTS[klass.HINT_START] = "*/" 518 519 klass._KEYWORD_TRIE = new_trie( 520 key.upper() 521 for key in ( 522 *klass.KEYWORDS, 523 *klass._COMMENTS, 524 *klass._QUOTES, 525 *klass._FORMAT_STRINGS, 526 ) 527 if " " in key or any(single in key for single in klass.SINGLE_TOKENS) 528 ) 529 530 if USE_RS_TOKENIZER: 531 settings = RsTokenizerSettings( 532 white_space={k: _TOKEN_TYPE_TO_INDEX[v] for k, v in klass.WHITE_SPACE.items()}, 533 single_tokens={k: _TOKEN_TYPE_TO_INDEX[v] for k, v in klass.SINGLE_TOKENS.items()}, 534 keywords={k: _TOKEN_TYPE_TO_INDEX[v] for k, v in klass.KEYWORDS.items()}, 535 numeric_literals=klass.NUMERIC_LITERALS, 536 identifiers=klass._IDENTIFIERS, 537 identifier_escapes=klass._IDENTIFIER_ESCAPES, 538 string_escapes=klass._STRING_ESCAPES, 539 quotes=klass._QUOTES, 540 format_strings={ 541 k: (v1, _TOKEN_TYPE_TO_INDEX[v2]) 542 for k, (v1, v2) in klass._FORMAT_STRINGS.items() 543 }, 544 has_bit_strings=bool(klass.BIT_STRINGS), 545 has_hex_strings=bool(klass.HEX_STRINGS), 546 comments=klass._COMMENTS, 547 var_single_tokens=klass.VAR_SINGLE_TOKENS, 548 commands={_TOKEN_TYPE_TO_INDEX[v] for v in klass.COMMANDS}, 549 command_prefix_tokens={ 550 _TOKEN_TYPE_TO_INDEX[v] for v in klass.COMMAND_PREFIX_TOKENS 551 }, 552 heredoc_tag_is_identifier=klass.HEREDOC_TAG_IS_IDENTIFIER, 553 string_escapes_allowed_in_raw_strings=klass.STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS, 554 nested_comments=klass.NESTED_COMMENTS, 555 hint_start=klass.HINT_START, 556 tokens_preceding_hint={ 557 _TOKEN_TYPE_TO_INDEX[v] for v in klass.TOKENS_PRECEDING_HINT 558 }, 559 ) 560 token_types = RsTokenTypeSettings( 561 bit_string=_TOKEN_TYPE_TO_INDEX[TokenType.BIT_STRING], 562 break_=_TOKEN_TYPE_TO_INDEX[TokenType.BREAK], 563 dcolon=_TOKEN_TYPE_TO_INDEX[TokenType.DCOLON], 564 heredoc_string=_TOKEN_TYPE_TO_INDEX[TokenType.HEREDOC_STRING], 565 raw_string=_TOKEN_TYPE_TO_INDEX[TokenType.RAW_STRING], 566 hex_string=_TOKEN_TYPE_TO_INDEX[TokenType.HEX_STRING], 567 identifier=_TOKEN_TYPE_TO_INDEX[TokenType.IDENTIFIER], 568 number=_TOKEN_TYPE_TO_INDEX[TokenType.NUMBER], 569 parameter=_TOKEN_TYPE_TO_INDEX[TokenType.PARAMETER], 570 semicolon=_TOKEN_TYPE_TO_INDEX[TokenType.SEMICOLON], 571 string=_TOKEN_TYPE_TO_INDEX[TokenType.STRING], 572 var=_TOKEN_TYPE_TO_INDEX[TokenType.VAR], 573 heredoc_string_alternative=_TOKEN_TYPE_TO_INDEX[klass.HEREDOC_STRING_ALTERNATIVE], 574 hint=_TOKEN_TYPE_TO_INDEX[TokenType.HINT], 575 ) 576 klass._RS_TOKENIZER = RsTokenizer(settings, token_types) 577 else: 578 klass._RS_TOKENIZER = None 579 580 return klass 581 582 583class Tokenizer(metaclass=_Tokenizer): 584 SINGLE_TOKENS = { 585 "(": TokenType.L_PAREN, 586 ")": TokenType.R_PAREN, 587 "[": TokenType.L_BRACKET, 588 "]": TokenType.R_BRACKET, 589 "{": TokenType.L_BRACE, 590 "}": TokenType.R_BRACE, 591 "&": TokenType.AMP, 592 "^": TokenType.CARET, 593 ":": TokenType.COLON, 594 ",": TokenType.COMMA, 595 ".": TokenType.DOT, 596 "-": TokenType.DASH, 597 "=": TokenType.EQ, 598 ">": TokenType.GT, 599 "<": TokenType.LT, 600 "%": TokenType.MOD, 601 "!": TokenType.NOT, 602 "|": TokenType.PIPE, 603 "+": TokenType.PLUS, 604 ";": TokenType.SEMICOLON, 605 "/": TokenType.SLASH, 606 "\\": TokenType.BACKSLASH, 607 "*": TokenType.STAR, 608 "~": TokenType.TILDA, 609 "?": TokenType.PLACEHOLDER, 610 "@": TokenType.PARAMETER, 611 "#": TokenType.HASH, 612 # Used for breaking a var like x'y' but nothing else the token type doesn't matter 613 "'": TokenType.UNKNOWN, 614 "`": TokenType.UNKNOWN, 615 '"': TokenType.UNKNOWN, 616 } 617 618 BIT_STRINGS: t.List[str | t.Tuple[str, str]] = [] 619 BYTE_STRINGS: t.List[str | t.Tuple[str, str]] = [] 620 HEX_STRINGS: t.List[str | t.Tuple[str, str]] = [] 621 RAW_STRINGS: t.List[str | t.Tuple[str, str]] = [] 622 HEREDOC_STRINGS: t.List[str | t.Tuple[str, str]] = [] 623 UNICODE_STRINGS: t.List[str | t.Tuple[str, str]] = [] 624 IDENTIFIERS: t.List[str | t.Tuple[str, str]] = ['"'] 625 QUOTES: t.List[t.Tuple[str, str] | str] = ["'"] 626 STRING_ESCAPES = ["'"] 627 VAR_SINGLE_TOKENS: t.Set[str] = set() 628 629 # The strings in this list can always be used as escapes, regardless of the surrounding 630 # identifier delimiters. By default, the closing delimiter is assumed to also act as an 631 # identifier escape, e.g. if we use double-quotes, then they also act as escapes: "x""" 632 IDENTIFIER_ESCAPES: t.List[str] = [] 633 634 # Whether the heredoc tags follow the same lexical rules as unquoted identifiers 635 HEREDOC_TAG_IS_IDENTIFIER = False 636 637 # Token that we'll generate as a fallback if the heredoc prefix doesn't correspond to a heredoc 638 HEREDOC_STRING_ALTERNATIVE = TokenType.VAR 639 640 # Whether string escape characters function as such when placed within raw strings 641 STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS = True 642 643 NESTED_COMMENTS = True 644 645 HINT_START = "/*+" 646 647 TOKENS_PRECEDING_HINT = {TokenType.SELECT, TokenType.INSERT, TokenType.UPDATE, TokenType.DELETE} 648 649 # Autofilled 650 _COMMENTS: t.Dict[str, str] = {} 651 _FORMAT_STRINGS: t.Dict[str, t.Tuple[str, TokenType]] = {} 652 _IDENTIFIERS: t.Dict[str, str] = {} 653 _IDENTIFIER_ESCAPES: t.Set[str] = set() 654 _QUOTES: t.Dict[str, str] = {} 655 _STRING_ESCAPES: t.Set[str] = set() 656 _KEYWORD_TRIE: t.Dict = {} 657 _RS_TOKENIZER: t.Optional[t.Any] = None 658 659 KEYWORDS: t.Dict[str, TokenType] = { 660 **{f"{{%{postfix}": TokenType.BLOCK_START for postfix in ("", "+", "-")}, 661 **{f"{prefix}%}}": TokenType.BLOCK_END for prefix in ("", "+", "-")}, 662 **{f"{{{{{postfix}": TokenType.BLOCK_START for postfix in ("+", "-")}, 663 **{f"{prefix}}}}}": TokenType.BLOCK_END for prefix in ("+", "-")}, 664 HINT_START: TokenType.HINT, 665 "==": TokenType.EQ, 666 "::": TokenType.DCOLON, 667 "||": TokenType.DPIPE, 668 ">=": TokenType.GTE, 669 "<=": TokenType.LTE, 670 "<>": TokenType.NEQ, 671 "!=": TokenType.NEQ, 672 ":=": TokenType.COLON_EQ, 673 "<=>": TokenType.NULLSAFE_EQ, 674 "->": TokenType.ARROW, 675 "->>": TokenType.DARROW, 676 "=>": TokenType.FARROW, 677 "#>": TokenType.HASH_ARROW, 678 "#>>": TokenType.DHASH_ARROW, 679 "<->": TokenType.LR_ARROW, 680 "&&": TokenType.DAMP, 681 "??": TokenType.DQMARK, 682 "~~~": TokenType.GLOB, 683 "~~": TokenType.LIKE, 684 "~~*": TokenType.ILIKE, 685 "~*": TokenType.IRLIKE, 686 "ALL": TokenType.ALL, 687 "ALWAYS": TokenType.ALWAYS, 688 "AND": TokenType.AND, 689 "ANTI": TokenType.ANTI, 690 "ANY": TokenType.ANY, 691 "ASC": TokenType.ASC, 692 "AS": TokenType.ALIAS, 693 "ASOF": TokenType.ASOF, 694 "AUTOINCREMENT": TokenType.AUTO_INCREMENT, 695 "AUTO_INCREMENT": TokenType.AUTO_INCREMENT, 696 "BEGIN": TokenType.BEGIN, 697 "BETWEEN": TokenType.BETWEEN, 698 "CACHE": TokenType.CACHE, 699 "UNCACHE": TokenType.UNCACHE, 700 "CASE": TokenType.CASE, 701 "CHARACTER SET": TokenType.CHARACTER_SET, 702 "CLUSTER BY": TokenType.CLUSTER_BY, 703 "COLLATE": TokenType.COLLATE, 704 "COLUMN": TokenType.COLUMN, 705 "COMMIT": TokenType.COMMIT, 706 "CONNECT BY": TokenType.CONNECT_BY, 707 "CONSTRAINT": TokenType.CONSTRAINT, 708 "COPY": TokenType.COPY, 709 "CREATE": TokenType.CREATE, 710 "CROSS": TokenType.CROSS, 711 "CUBE": TokenType.CUBE, 712 "CURRENT_DATE": TokenType.CURRENT_DATE, 713 "CURRENT_TIME": TokenType.CURRENT_TIME, 714 "CURRENT_TIMESTAMP": TokenType.CURRENT_TIMESTAMP, 715 "CURRENT_USER": TokenType.CURRENT_USER, 716 "DATABASE": TokenType.DATABASE, 717 "DEFAULT": TokenType.DEFAULT, 718 "DELETE": TokenType.DELETE, 719 "DESC": TokenType.DESC, 720 "DESCRIBE": TokenType.DESCRIBE, 721 "DISTINCT": TokenType.DISTINCT, 722 "DISTRIBUTE BY": TokenType.DISTRIBUTE_BY, 723 "DIV": TokenType.DIV, 724 "DROP": TokenType.DROP, 725 "ELSE": TokenType.ELSE, 726 "END": TokenType.END, 727 "ENUM": TokenType.ENUM, 728 "ESCAPE": TokenType.ESCAPE, 729 "EXCEPT": TokenType.EXCEPT, 730 "EXECUTE": TokenType.EXECUTE, 731 "EXISTS": TokenType.EXISTS, 732 "FALSE": TokenType.FALSE, 733 "FETCH": TokenType.FETCH, 734 "FILTER": TokenType.FILTER, 735 "FIRST": TokenType.FIRST, 736 "FULL": TokenType.FULL, 737 "FUNCTION": TokenType.FUNCTION, 738 "FOR": TokenType.FOR, 739 "FOREIGN KEY": TokenType.FOREIGN_KEY, 740 "FORMAT": TokenType.FORMAT, 741 "FROM": TokenType.FROM, 742 "GEOGRAPHY": TokenType.GEOGRAPHY, 743 "GEOMETRY": TokenType.GEOMETRY, 744 "GLOB": TokenType.GLOB, 745 "GROUP BY": TokenType.GROUP_BY, 746 "GROUPING SETS": TokenType.GROUPING_SETS, 747 "HAVING": TokenType.HAVING, 748 "ILIKE": TokenType.ILIKE, 749 "IN": TokenType.IN, 750 "INDEX": TokenType.INDEX, 751 "INET": TokenType.INET, 752 "INNER": TokenType.INNER, 753 "INSERT": TokenType.INSERT, 754 "INTERVAL": TokenType.INTERVAL, 755 "INTERSECT": TokenType.INTERSECT, 756 "INTO": TokenType.INTO, 757 "IS": TokenType.IS, 758 "ISNULL": TokenType.ISNULL, 759 "JOIN": TokenType.JOIN, 760 "KEEP": TokenType.KEEP, 761 "KILL": TokenType.KILL, 762 "LATERAL": TokenType.LATERAL, 763 "LEFT": TokenType.LEFT, 764 "LIKE": TokenType.LIKE, 765 "LIMIT": TokenType.LIMIT, 766 "LOAD": TokenType.LOAD, 767 "LOCK": TokenType.LOCK, 768 "MERGE": TokenType.MERGE, 769 "NATURAL": TokenType.NATURAL, 770 "NEXT": TokenType.NEXT, 771 "NOT": TokenType.NOT, 772 "NOTNULL": TokenType.NOTNULL, 773 "NULL": TokenType.NULL, 774 "OBJECT": TokenType.OBJECT, 775 "OFFSET": TokenType.OFFSET, 776 "ON": TokenType.ON, 777 "OR": TokenType.OR, 778 "XOR": TokenType.XOR, 779 "ORDER BY": TokenType.ORDER_BY, 780 "ORDINALITY": TokenType.ORDINALITY, 781 "OUTER": TokenType.OUTER, 782 "OVER": TokenType.OVER, 783 "OVERLAPS": TokenType.OVERLAPS, 784 "OVERWRITE": TokenType.OVERWRITE, 785 "PARTITION": TokenType.PARTITION, 786 "PARTITION BY": TokenType.PARTITION_BY, 787 "PARTITIONED BY": TokenType.PARTITION_BY, 788 "PARTITIONED_BY": TokenType.PARTITION_BY, 789 "PERCENT": TokenType.PERCENT, 790 "PIVOT": TokenType.PIVOT, 791 "PRAGMA": TokenType.PRAGMA, 792 "PRIMARY KEY": TokenType.PRIMARY_KEY, 793 "PROCEDURE": TokenType.PROCEDURE, 794 "QUALIFY": TokenType.QUALIFY, 795 "RANGE": TokenType.RANGE, 796 "RECURSIVE": TokenType.RECURSIVE, 797 "REGEXP": TokenType.RLIKE, 798 "RENAME": TokenType.RENAME, 799 "REPLACE": TokenType.REPLACE, 800 "RETURNING": TokenType.RETURNING, 801 "REFERENCES": TokenType.REFERENCES, 802 "RIGHT": TokenType.RIGHT, 803 "RLIKE": TokenType.RLIKE, 804 "ROLLBACK": TokenType.ROLLBACK, 805 "ROLLUP": TokenType.ROLLUP, 806 "ROW": TokenType.ROW, 807 "ROWS": TokenType.ROWS, 808 "SCHEMA": TokenType.SCHEMA, 809 "SELECT": TokenType.SELECT, 810 "SEMI": TokenType.SEMI, 811 "SET": TokenType.SET, 812 "SETTINGS": TokenType.SETTINGS, 813 "SHOW": TokenType.SHOW, 814 "SIMILAR TO": TokenType.SIMILAR_TO, 815 "SOME": TokenType.SOME, 816 "SORT BY": TokenType.SORT_BY, 817 "START WITH": TokenType.START_WITH, 818 "STRAIGHT_JOIN": TokenType.STRAIGHT_JOIN, 819 "TABLE": TokenType.TABLE, 820 "TABLESAMPLE": TokenType.TABLE_SAMPLE, 821 "TEMP": TokenType.TEMPORARY, 822 "TEMPORARY": TokenType.TEMPORARY, 823 "THEN": TokenType.THEN, 824 "TRUE": TokenType.TRUE, 825 "TRUNCATE": TokenType.TRUNCATE, 826 "UNION": TokenType.UNION, 827 "UNKNOWN": TokenType.UNKNOWN, 828 "UNNEST": TokenType.UNNEST, 829 "UNPIVOT": TokenType.UNPIVOT, 830 "UPDATE": TokenType.UPDATE, 831 "USE": TokenType.USE, 832 "USING": TokenType.USING, 833 "UUID": TokenType.UUID, 834 "VALUES": TokenType.VALUES, 835 "VIEW": TokenType.VIEW, 836 "VOLATILE": TokenType.VOLATILE, 837 "WHEN": TokenType.WHEN, 838 "WHERE": TokenType.WHERE, 839 "WINDOW": TokenType.WINDOW, 840 "WITH": TokenType.WITH, 841 "APPLY": TokenType.APPLY, 842 "ARRAY": TokenType.ARRAY, 843 "BIT": TokenType.BIT, 844 "BOOL": TokenType.BOOLEAN, 845 "BOOLEAN": TokenType.BOOLEAN, 846 "BYTE": TokenType.TINYINT, 847 "MEDIUMINT": TokenType.MEDIUMINT, 848 "INT1": TokenType.TINYINT, 849 "TINYINT": TokenType.TINYINT, 850 "INT16": TokenType.SMALLINT, 851 "SHORT": TokenType.SMALLINT, 852 "SMALLINT": TokenType.SMALLINT, 853 "INT128": TokenType.INT128, 854 "HUGEINT": TokenType.INT128, 855 "UHUGEINT": TokenType.UINT128, 856 "INT2": TokenType.SMALLINT, 857 "INTEGER": TokenType.INT, 858 "INT": TokenType.INT, 859 "INT4": TokenType.INT, 860 "INT32": TokenType.INT, 861 "INT64": TokenType.BIGINT, 862 "LONG": TokenType.BIGINT, 863 "BIGINT": TokenType.BIGINT, 864 "INT8": TokenType.TINYINT, 865 "UINT": TokenType.UINT, 866 "DEC": TokenType.DECIMAL, 867 "DECIMAL": TokenType.DECIMAL, 868 "DECIMAL32": TokenType.DECIMAL32, 869 "DECIMAL64": TokenType.DECIMAL64, 870 "DECIMAL128": TokenType.DECIMAL128, 871 "DECIMAL256": TokenType.DECIMAL256, 872 "BIGDECIMAL": TokenType.BIGDECIMAL, 873 "BIGNUMERIC": TokenType.BIGDECIMAL, 874 "LIST": TokenType.LIST, 875 "MAP": TokenType.MAP, 876 "NULLABLE": TokenType.NULLABLE, 877 "NUMBER": TokenType.DECIMAL, 878 "NUMERIC": TokenType.DECIMAL, 879 "FIXED": TokenType.DECIMAL, 880 "REAL": TokenType.FLOAT, 881 "FLOAT": TokenType.FLOAT, 882 "FLOAT4": TokenType.FLOAT, 883 "FLOAT8": TokenType.DOUBLE, 884 "DOUBLE": TokenType.DOUBLE, 885 "DOUBLE PRECISION": TokenType.DOUBLE, 886 "JSON": TokenType.JSON, 887 "JSONB": TokenType.JSONB, 888 "CHAR": TokenType.CHAR, 889 "CHARACTER": TokenType.CHAR, 890 "NCHAR": TokenType.NCHAR, 891 "VARCHAR": TokenType.VARCHAR, 892 "VARCHAR2": TokenType.VARCHAR, 893 "NVARCHAR": TokenType.NVARCHAR, 894 "NVARCHAR2": TokenType.NVARCHAR, 895 "BPCHAR": TokenType.BPCHAR, 896 "STR": TokenType.TEXT, 897 "STRING": TokenType.TEXT, 898 "TEXT": TokenType.TEXT, 899 "LONGTEXT": TokenType.LONGTEXT, 900 "MEDIUMTEXT": TokenType.MEDIUMTEXT, 901 "TINYTEXT": TokenType.TINYTEXT, 902 "CLOB": TokenType.TEXT, 903 "LONGVARCHAR": TokenType.TEXT, 904 "BINARY": TokenType.BINARY, 905 "BLOB": TokenType.VARBINARY, 906 "LONGBLOB": TokenType.LONGBLOB, 907 "MEDIUMBLOB": TokenType.MEDIUMBLOB, 908 "TINYBLOB": TokenType.TINYBLOB, 909 "BYTEA": TokenType.VARBINARY, 910 "VARBINARY": TokenType.VARBINARY, 911 "TIME": TokenType.TIME, 912 "TIMETZ": TokenType.TIMETZ, 913 "TIMESTAMP": TokenType.TIMESTAMP, 914 "TIMESTAMPTZ": TokenType.TIMESTAMPTZ, 915 "TIMESTAMPLTZ": TokenType.TIMESTAMPLTZ, 916 "TIMESTAMP_LTZ": TokenType.TIMESTAMPLTZ, 917 "TIMESTAMPNTZ": TokenType.TIMESTAMPNTZ, 918 "TIMESTAMP_NTZ": TokenType.TIMESTAMPNTZ, 919 "DATE": TokenType.DATE, 920 "DATETIME": TokenType.DATETIME, 921 "INT4RANGE": TokenType.INT4RANGE, 922 "INT4MULTIRANGE": TokenType.INT4MULTIRANGE, 923 "INT8RANGE": TokenType.INT8RANGE, 924 "INT8MULTIRANGE": TokenType.INT8MULTIRANGE, 925 "NUMRANGE": TokenType.NUMRANGE, 926 "NUMMULTIRANGE": TokenType.NUMMULTIRANGE, 927 "TSRANGE": TokenType.TSRANGE, 928 "TSMULTIRANGE": TokenType.TSMULTIRANGE, 929 "TSTZRANGE": TokenType.TSTZRANGE, 930 "TSTZMULTIRANGE": TokenType.TSTZMULTIRANGE, 931 "DATERANGE": TokenType.DATERANGE, 932 "DATEMULTIRANGE": TokenType.DATEMULTIRANGE, 933 "UNIQUE": TokenType.UNIQUE, 934 "VECTOR": TokenType.VECTOR, 935 "STRUCT": TokenType.STRUCT, 936 "SEQUENCE": TokenType.SEQUENCE, 937 "VARIANT": TokenType.VARIANT, 938 "ALTER": TokenType.ALTER, 939 "ANALYZE": TokenType.COMMAND, 940 "CALL": TokenType.COMMAND, 941 "COMMENT": TokenType.COMMENT, 942 "EXPLAIN": TokenType.COMMAND, 943 "GRANT": TokenType.GRANT, 944 "OPTIMIZE": TokenType.COMMAND, 945 "PREPARE": TokenType.COMMAND, 946 "VACUUM": TokenType.COMMAND, 947 "USER-DEFINED": TokenType.USERDEFINED, 948 "FOR VERSION": TokenType.VERSION_SNAPSHOT, 949 "FOR TIMESTAMP": TokenType.TIMESTAMP_SNAPSHOT, 950 } 951 952 WHITE_SPACE: t.Dict[t.Optional[str], TokenType] = { 953 " ": TokenType.SPACE, 954 "\t": TokenType.SPACE, 955 "\n": TokenType.BREAK, 956 "\r": TokenType.BREAK, 957 } 958 959 COMMANDS = { 960 TokenType.COMMAND, 961 TokenType.EXECUTE, 962 TokenType.FETCH, 963 TokenType.SHOW, 964 TokenType.RENAME, 965 } 966 967 COMMAND_PREFIX_TOKENS = {TokenType.SEMICOLON, TokenType.BEGIN} 968 969 # Handle numeric literals like in hive (3L = BIGINT) 970 NUMERIC_LITERALS: t.Dict[str, str] = {} 971 972 COMMENTS = ["--", ("/*", "*/")] 973 974 __slots__ = ( 975 "sql", 976 "size", 977 "tokens", 978 "dialect", 979 "_start", 980 "_current", 981 "_line", 982 "_col", 983 "_comments", 984 "_char", 985 "_end", 986 "_peek", 987 "_prev_token_line", 988 "_rs_dialect_settings", 989 ) 990 991 def __init__(self, dialect: DialectType = None) -> None: 992 from sqlglot.dialects import Dialect 993 994 self.dialect = Dialect.get_or_raise(dialect) 995 996 if USE_RS_TOKENIZER: 997 self._rs_dialect_settings = RsTokenizerDialectSettings( 998 unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES, 999 identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT, 1000 ) 1001 1002 self.reset() 1003 1004 def reset(self) -> None: 1005 self.sql = "" 1006 self.size = 0 1007 self.tokens: t.List[Token] = [] 1008 self._start = 0 1009 self._current = 0 1010 self._line = 1 1011 self._col = 0 1012 self._comments: t.List[str] = [] 1013 1014 self._char = "" 1015 self._end = False 1016 self._peek = "" 1017 self._prev_token_line = -1 1018 1019 def tokenize(self, sql: str) -> t.List[Token]: 1020 """Returns a list of tokens corresponding to the SQL string `sql`.""" 1021 if USE_RS_TOKENIZER: 1022 return self.tokenize_rs(sql) 1023 1024 self.reset() 1025 self.sql = sql 1026 self.size = len(sql) 1027 1028 try: 1029 self._scan() 1030 except Exception as e: 1031 start = max(self._current - 50, 0) 1032 end = min(self._current + 50, self.size - 1) 1033 context = self.sql[start:end] 1034 raise TokenError(f"Error tokenizing '{context}'") from e 1035 1036 return self.tokens 1037 1038 def _scan(self, until: t.Optional[t.Callable] = None) -> None: 1039 while self.size and not self._end: 1040 current = self._current 1041 1042 # Skip spaces here rather than iteratively calling advance() for performance reasons 1043 while current < self.size: 1044 char = self.sql[current] 1045 1046 if char.isspace() and (char == " " or char == "\t"): 1047 current += 1 1048 else: 1049 break 1050 1051 offset = current - self._current if current > self._current else 1 1052 1053 self._start = current 1054 self._advance(offset) 1055 1056 if not self._char.isspace(): 1057 if self._char.isdigit(): 1058 self._scan_number() 1059 elif self._char in self._IDENTIFIERS: 1060 self._scan_identifier(self._IDENTIFIERS[self._char]) 1061 else: 1062 self._scan_keywords() 1063 1064 if until and until(): 1065 break 1066 1067 if self.tokens and self._comments: 1068 self.tokens[-1].comments.extend(self._comments) 1069 1070 def _chars(self, size: int) -> str: 1071 if size == 1: 1072 return self._char 1073 1074 start = self._current - 1 1075 end = start + size 1076 1077 return self.sql[start:end] if end <= self.size else "" 1078 1079 def _advance(self, i: int = 1, alnum: bool = False) -> None: 1080 if self.WHITE_SPACE.get(self._char) is TokenType.BREAK: 1081 # Ensures we don't count an extra line if we get a \r\n line break sequence 1082 if not (self._char == "\r" and self._peek == "\n"): 1083 self._col = 1 1084 self._line += 1 1085 else: 1086 self._col += i 1087 1088 self._current += i 1089 self._end = self._current >= self.size 1090 self._char = self.sql[self._current - 1] 1091 self._peek = "" if self._end else self.sql[self._current] 1092 1093 if alnum and self._char.isalnum(): 1094 # Here we use local variables instead of attributes for better performance 1095 _col = self._col 1096 _current = self._current 1097 _end = self._end 1098 _peek = self._peek 1099 1100 while _peek.isalnum(): 1101 _col += 1 1102 _current += 1 1103 _end = _current >= self.size 1104 _peek = "" if _end else self.sql[_current] 1105 1106 self._col = _col 1107 self._current = _current 1108 self._end = _end 1109 self._peek = _peek 1110 self._char = self.sql[_current - 1] 1111 1112 @property 1113 def _text(self) -> str: 1114 return self.sql[self._start : self._current] 1115 1116 def _add(self, token_type: TokenType, text: t.Optional[str] = None) -> None: 1117 self._prev_token_line = self._line 1118 1119 if self._comments and token_type == TokenType.SEMICOLON and self.tokens: 1120 self.tokens[-1].comments.extend(self._comments) 1121 self._comments = [] 1122 1123 self.tokens.append( 1124 Token( 1125 token_type, 1126 text=self._text if text is None else text, 1127 line=self._line, 1128 col=self._col, 1129 start=self._start, 1130 end=self._current - 1, 1131 comments=self._comments, 1132 ) 1133 ) 1134 self._comments = [] 1135 1136 # If we have either a semicolon or a begin token before the command's token, we'll parse 1137 # whatever follows the command's token as a string 1138 if ( 1139 token_type in self.COMMANDS 1140 and self._peek != ";" 1141 and (len(self.tokens) == 1 or self.tokens[-2].token_type in self.COMMAND_PREFIX_TOKENS) 1142 ): 1143 start = self._current 1144 tokens = len(self.tokens) 1145 self._scan(lambda: self._peek == ";") 1146 self.tokens = self.tokens[:tokens] 1147 text = self.sql[start : self._current].strip() 1148 if text: 1149 self._add(TokenType.STRING, text) 1150 1151 def _scan_keywords(self) -> None: 1152 size = 0 1153 word = None 1154 chars = self._text 1155 char = chars 1156 prev_space = False 1157 skip = False 1158 trie = self._KEYWORD_TRIE 1159 single_token = char in self.SINGLE_TOKENS 1160 1161 while chars: 1162 if skip: 1163 result = TrieResult.PREFIX 1164 else: 1165 result, trie = in_trie(trie, char.upper()) 1166 1167 if result == TrieResult.FAILED: 1168 break 1169 if result == TrieResult.EXISTS: 1170 word = chars 1171 1172 end = self._current + size 1173 size += 1 1174 1175 if end < self.size: 1176 char = self.sql[end] 1177 single_token = single_token or char in self.SINGLE_TOKENS 1178 is_space = char.isspace() 1179 1180 if not is_space or not prev_space: 1181 if is_space: 1182 char = " " 1183 chars += char 1184 prev_space = is_space 1185 skip = False 1186 else: 1187 skip = True 1188 else: 1189 char = "" 1190 break 1191 1192 if word: 1193 if self._scan_string(word): 1194 return 1195 if self._scan_comment(word): 1196 return 1197 if prev_space or single_token or not char: 1198 self._advance(size - 1) 1199 word = word.upper() 1200 self._add(self.KEYWORDS[word], text=word) 1201 return 1202 1203 if self._char in self.SINGLE_TOKENS: 1204 self._add(self.SINGLE_TOKENS[self._char], text=self._char) 1205 return 1206 1207 self._scan_var() 1208 1209 def _scan_comment(self, comment_start: str) -> bool: 1210 if comment_start not in self._COMMENTS: 1211 return False 1212 1213 comment_start_line = self._line 1214 comment_start_size = len(comment_start) 1215 comment_end = self._COMMENTS[comment_start] 1216 1217 if comment_end: 1218 # Skip the comment's start delimiter 1219 self._advance(comment_start_size) 1220 1221 comment_count = 1 1222 comment_end_size = len(comment_end) 1223 1224 while not self._end: 1225 if self._chars(comment_end_size) == comment_end: 1226 comment_count -= 1 1227 if not comment_count: 1228 break 1229 1230 self._advance(alnum=True) 1231 1232 # Nested comments are allowed by some dialects, e.g. databricks, duckdb, postgres 1233 if ( 1234 self.NESTED_COMMENTS 1235 and not self._end 1236 and self._chars(comment_end_size) == comment_start 1237 ): 1238 self._advance(comment_start_size) 1239 comment_count += 1 1240 1241 self._comments.append(self._text[comment_start_size : -comment_end_size + 1]) 1242 self._advance(comment_end_size - 1) 1243 else: 1244 while not self._end and self.WHITE_SPACE.get(self._peek) is not TokenType.BREAK: 1245 self._advance(alnum=True) 1246 self._comments.append(self._text[comment_start_size:]) 1247 1248 if ( 1249 comment_start == self.HINT_START 1250 and self.tokens 1251 and self.tokens[-1].token_type in self.TOKENS_PRECEDING_HINT 1252 ): 1253 self._add(TokenType.HINT) 1254 1255 # Leading comment is attached to the succeeding token, whilst trailing comment to the preceding. 1256 # Multiple consecutive comments are preserved by appending them to the current comments list. 1257 if comment_start_line == self._prev_token_line: 1258 self.tokens[-1].comments.extend(self._comments) 1259 self._comments = [] 1260 self._prev_token_line = self._line 1261 1262 return True 1263 1264 def _scan_number(self) -> None: 1265 if self._char == "0": 1266 peek = self._peek.upper() 1267 if peek == "B": 1268 return self._scan_bits() if self.BIT_STRINGS else self._add(TokenType.NUMBER) 1269 elif peek == "X": 1270 return self._scan_hex() if self.HEX_STRINGS else self._add(TokenType.NUMBER) 1271 1272 decimal = False 1273 scientific = 0 1274 1275 while True: 1276 if self._peek.isdigit(): 1277 self._advance() 1278 elif self._peek == "." and not decimal: 1279 if self.tokens and self.tokens[-1].token_type == TokenType.PARAMETER: 1280 return self._add(TokenType.NUMBER) 1281 decimal = True 1282 self._advance() 1283 elif self._peek in ("-", "+") and scientific == 1: 1284 scientific += 1 1285 self._advance() 1286 elif self._peek.upper() == "E" and not scientific: 1287 scientific += 1 1288 self._advance() 1289 elif self._peek.isidentifier(): 1290 number_text = self._text 1291 literal = "" 1292 1293 while self._peek.strip() and self._peek not in self.SINGLE_TOKENS: 1294 literal += self._peek 1295 self._advance() 1296 1297 token_type = self.KEYWORDS.get(self.NUMERIC_LITERALS.get(literal.upper(), "")) 1298 1299 if token_type: 1300 self._add(TokenType.NUMBER, number_text) 1301 self._add(TokenType.DCOLON, "::") 1302 return self._add(token_type, literal) 1303 elif self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT: 1304 return self._add(TokenType.VAR) 1305 1306 self._advance(-len(literal)) 1307 return self._add(TokenType.NUMBER, number_text) 1308 else: 1309 return self._add(TokenType.NUMBER) 1310 1311 def _scan_bits(self) -> None: 1312 self._advance() 1313 value = self._extract_value() 1314 try: 1315 # If `value` can't be converted to a binary, fallback to tokenizing it as an identifier 1316 int(value, 2) 1317 self._add(TokenType.BIT_STRING, value[2:]) # Drop the 0b 1318 except ValueError: 1319 self._add(TokenType.IDENTIFIER) 1320 1321 def _scan_hex(self) -> None: 1322 self._advance() 1323 value = self._extract_value() 1324 try: 1325 # If `value` can't be converted to a hex, fallback to tokenizing it as an identifier 1326 int(value, 16) 1327 self._add(TokenType.HEX_STRING, value[2:]) # Drop the 0x 1328 except ValueError: 1329 self._add(TokenType.IDENTIFIER) 1330 1331 def _extract_value(self) -> str: 1332 while True: 1333 char = self._peek.strip() 1334 if char and char not in self.SINGLE_TOKENS: 1335 self._advance(alnum=True) 1336 else: 1337 break 1338 1339 return self._text 1340 1341 def _scan_string(self, start: str) -> bool: 1342 base = None 1343 token_type = TokenType.STRING 1344 1345 if start in self._QUOTES: 1346 end = self._QUOTES[start] 1347 elif start in self._FORMAT_STRINGS: 1348 end, token_type = self._FORMAT_STRINGS[start] 1349 1350 if token_type == TokenType.HEX_STRING: 1351 base = 16 1352 elif token_type == TokenType.BIT_STRING: 1353 base = 2 1354 elif token_type == TokenType.HEREDOC_STRING: 1355 self._advance() 1356 1357 if self._char == end: 1358 tag = "" 1359 else: 1360 tag = self._extract_string( 1361 end, 1362 raw_string=True, 1363 raise_unmatched=not self.HEREDOC_TAG_IS_IDENTIFIER, 1364 ) 1365 1366 if tag and self.HEREDOC_TAG_IS_IDENTIFIER and (self._end or not tag.isidentifier()): 1367 if not self._end: 1368 self._advance(-1) 1369 1370 self._advance(-len(tag)) 1371 self._add(self.HEREDOC_STRING_ALTERNATIVE) 1372 return True 1373 1374 end = f"{start}{tag}{end}" 1375 else: 1376 return False 1377 1378 self._advance(len(start)) 1379 text = self._extract_string(end, raw_string=token_type == TokenType.RAW_STRING) 1380 1381 if base: 1382 try: 1383 int(text, base) 1384 except Exception: 1385 raise TokenError( 1386 f"Numeric string contains invalid characters from {self._line}:{self._start}" 1387 ) 1388 1389 self._add(token_type, text) 1390 return True 1391 1392 def _scan_identifier(self, identifier_end: str) -> None: 1393 self._advance() 1394 text = self._extract_string( 1395 identifier_end, escapes=self._IDENTIFIER_ESCAPES | {identifier_end} 1396 ) 1397 self._add(TokenType.IDENTIFIER, text) 1398 1399 def _scan_var(self) -> None: 1400 while True: 1401 char = self._peek.strip() 1402 if char and (char in self.VAR_SINGLE_TOKENS or char not in self.SINGLE_TOKENS): 1403 self._advance(alnum=True) 1404 else: 1405 break 1406 1407 self._add( 1408 TokenType.VAR 1409 if self.tokens and self.tokens[-1].token_type == TokenType.PARAMETER 1410 else self.KEYWORDS.get(self._text.upper(), TokenType.VAR) 1411 ) 1412 1413 def _extract_string( 1414 self, 1415 delimiter: str, 1416 escapes: t.Optional[t.Set[str]] = None, 1417 raw_string: bool = False, 1418 raise_unmatched: bool = True, 1419 ) -> str: 1420 text = "" 1421 delim_size = len(delimiter) 1422 escapes = self._STRING_ESCAPES if escapes is None else escapes 1423 1424 while True: 1425 if ( 1426 not raw_string 1427 and self.dialect.UNESCAPED_SEQUENCES 1428 and self._peek 1429 and self._char in self.STRING_ESCAPES 1430 ): 1431 unescaped_sequence = self.dialect.UNESCAPED_SEQUENCES.get(self._char + self._peek) 1432 if unescaped_sequence: 1433 self._advance(2) 1434 text += unescaped_sequence 1435 continue 1436 if ( 1437 (self.STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS or not raw_string) 1438 and self._char in escapes 1439 and (self._peek == delimiter or self._peek in escapes) 1440 and (self._char not in self._QUOTES or self._char == self._peek) 1441 ): 1442 if self._peek == delimiter: 1443 text += self._peek 1444 else: 1445 text += self._char + self._peek 1446 1447 if self._current + 1 < self.size: 1448 self._advance(2) 1449 else: 1450 raise TokenError(f"Missing {delimiter} from {self._line}:{self._current}") 1451 else: 1452 if self._chars(delim_size) == delimiter: 1453 if delim_size > 1: 1454 self._advance(delim_size - 1) 1455 break 1456 1457 if self._end: 1458 if not raise_unmatched: 1459 return text + self._char 1460 1461 raise TokenError(f"Missing {delimiter} from {self._line}:{self._start}") 1462 1463 current = self._current - 1 1464 self._advance(alnum=True) 1465 text += self.sql[current : self._current - 1] 1466 1467 return text 1468 1469 def tokenize_rs(self, sql: str) -> t.List[Token]: 1470 if not self._RS_TOKENIZER: 1471 raise SqlglotError("Rust tokenizer is not available") 1472 1473 try: 1474 tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings) 1475 for token in tokens: 1476 token.token_type = _ALL_TOKEN_TYPES[token.token_type_index] 1477 return tokens 1478 except Exception as e: 1479 raise TokenError(str(e))
29class TokenType(AutoName): 30 L_PAREN = auto() 31 R_PAREN = auto() 32 L_BRACKET = auto() 33 R_BRACKET = auto() 34 L_BRACE = auto() 35 R_BRACE = auto() 36 COMMA = auto() 37 DOT = auto() 38 DASH = auto() 39 PLUS = auto() 40 COLON = auto() 41 DCOLON = auto() 42 DQMARK = auto() 43 SEMICOLON = auto() 44 STAR = auto() 45 BACKSLASH = auto() 46 SLASH = auto() 47 LT = auto() 48 LTE = auto() 49 GT = auto() 50 GTE = auto() 51 NOT = auto() 52 EQ = auto() 53 NEQ = auto() 54 NULLSAFE_EQ = auto() 55 COLON_EQ = auto() 56 AND = auto() 57 OR = auto() 58 AMP = auto() 59 DPIPE = auto() 60 PIPE = auto() 61 PIPE_SLASH = auto() 62 DPIPE_SLASH = auto() 63 CARET = auto() 64 CARET_AT = auto() 65 TILDA = auto() 66 ARROW = auto() 67 DARROW = auto() 68 FARROW = auto() 69 HASH = auto() 70 HASH_ARROW = auto() 71 DHASH_ARROW = auto() 72 LR_ARROW = auto() 73 DAT = auto() 74 LT_AT = auto() 75 AT_GT = auto() 76 DOLLAR = auto() 77 PARAMETER = auto() 78 SESSION_PARAMETER = auto() 79 DAMP = auto() 80 XOR = auto() 81 DSTAR = auto() 82 83 BLOCK_START = auto() 84 BLOCK_END = auto() 85 86 SPACE = auto() 87 BREAK = auto() 88 89 STRING = auto() 90 NUMBER = auto() 91 IDENTIFIER = auto() 92 DATABASE = auto() 93 COLUMN = auto() 94 COLUMN_DEF = auto() 95 SCHEMA = auto() 96 TABLE = auto() 97 WAREHOUSE = auto() 98 STREAMLIT = auto() 99 VAR = auto() 100 BIT_STRING = auto() 101 HEX_STRING = auto() 102 BYTE_STRING = auto() 103 NATIONAL_STRING = auto() 104 RAW_STRING = auto() 105 HEREDOC_STRING = auto() 106 UNICODE_STRING = auto() 107 108 # types 109 BIT = auto() 110 BOOLEAN = auto() 111 TINYINT = auto() 112 UTINYINT = auto() 113 SMALLINT = auto() 114 USMALLINT = auto() 115 MEDIUMINT = auto() 116 UMEDIUMINT = auto() 117 INT = auto() 118 UINT = auto() 119 BIGINT = auto() 120 UBIGINT = auto() 121 INT128 = auto() 122 UINT128 = auto() 123 INT256 = auto() 124 UINT256 = auto() 125 FLOAT = auto() 126 DOUBLE = auto() 127 DECIMAL = auto() 128 DECIMAL32 = auto() 129 DECIMAL64 = auto() 130 DECIMAL128 = auto() 131 DECIMAL256 = auto() 132 UDECIMAL = auto() 133 BIGDECIMAL = auto() 134 CHAR = auto() 135 NCHAR = auto() 136 VARCHAR = auto() 137 NVARCHAR = auto() 138 BPCHAR = auto() 139 TEXT = auto() 140 MEDIUMTEXT = auto() 141 LONGTEXT = auto() 142 MEDIUMBLOB = auto() 143 LONGBLOB = auto() 144 TINYBLOB = auto() 145 TINYTEXT = auto() 146 NAME = auto() 147 BINARY = auto() 148 VARBINARY = auto() 149 JSON = auto() 150 JSONB = auto() 151 TIME = auto() 152 TIMETZ = auto() 153 TIMESTAMP = auto() 154 TIMESTAMPTZ = auto() 155 TIMESTAMPLTZ = auto() 156 TIMESTAMPNTZ = auto() 157 TIMESTAMP_S = auto() 158 TIMESTAMP_MS = auto() 159 TIMESTAMP_NS = auto() 160 DATETIME = auto() 161 DATETIME2 = auto() 162 DATETIME64 = auto() 163 SMALLDATETIME = auto() 164 DATE = auto() 165 DATE32 = auto() 166 INT4RANGE = auto() 167 INT4MULTIRANGE = auto() 168 INT8RANGE = auto() 169 INT8MULTIRANGE = auto() 170 NUMRANGE = auto() 171 NUMMULTIRANGE = auto() 172 TSRANGE = auto() 173 TSMULTIRANGE = auto() 174 TSTZRANGE = auto() 175 TSTZMULTIRANGE = auto() 176 DATERANGE = auto() 177 DATEMULTIRANGE = auto() 178 UUID = auto() 179 GEOGRAPHY = auto() 180 NULLABLE = auto() 181 GEOMETRY = auto() 182 POINT = auto() 183 RING = auto() 184 LINESTRING = auto() 185 MULTILINESTRING = auto() 186 POLYGON = auto() 187 MULTIPOLYGON = auto() 188 HLLSKETCH = auto() 189 HSTORE = auto() 190 SUPER = auto() 191 SERIAL = auto() 192 SMALLSERIAL = auto() 193 BIGSERIAL = auto() 194 XML = auto() 195 YEAR = auto() 196 UNIQUEIDENTIFIER = auto() 197 USERDEFINED = auto() 198 MONEY = auto() 199 SMALLMONEY = auto() 200 ROWVERSION = auto() 201 IMAGE = auto() 202 VARIANT = auto() 203 OBJECT = auto() 204 INET = auto() 205 IPADDRESS = auto() 206 IPPREFIX = auto() 207 IPV4 = auto() 208 IPV6 = auto() 209 ENUM = auto() 210 ENUM8 = auto() 211 ENUM16 = auto() 212 FIXEDSTRING = auto() 213 LOWCARDINALITY = auto() 214 NESTED = auto() 215 AGGREGATEFUNCTION = auto() 216 SIMPLEAGGREGATEFUNCTION = auto() 217 TDIGEST = auto() 218 UNKNOWN = auto() 219 VECTOR = auto() 220 221 # keywords 222 ALIAS = auto() 223 ALTER = auto() 224 ALWAYS = auto() 225 ALL = auto() 226 ANTI = auto() 227 ANY = auto() 228 APPLY = auto() 229 ARRAY = auto() 230 ASC = auto() 231 ASOF = auto() 232 ATTACH = auto() 233 AUTO_INCREMENT = auto() 234 BEGIN = auto() 235 BETWEEN = auto() 236 BULK_COLLECT_INTO = auto() 237 CACHE = auto() 238 CASE = auto() 239 CHARACTER_SET = auto() 240 CLUSTER_BY = auto() 241 COLLATE = auto() 242 COMMAND = auto() 243 COMMENT = auto() 244 COMMIT = auto() 245 CONNECT_BY = auto() 246 CONSTRAINT = auto() 247 COPY = auto() 248 CREATE = auto() 249 CROSS = auto() 250 CUBE = auto() 251 CURRENT_DATE = auto() 252 CURRENT_DATETIME = auto() 253 CURRENT_TIME = auto() 254 CURRENT_TIMESTAMP = auto() 255 CURRENT_USER = auto() 256 DECLARE = auto() 257 DEFAULT = auto() 258 DELETE = auto() 259 DESC = auto() 260 DESCRIBE = auto() 261 DETACH = auto() 262 DICTIONARY = auto() 263 DISTINCT = auto() 264 DISTRIBUTE_BY = auto() 265 DIV = auto() 266 DROP = auto() 267 ELSE = auto() 268 END = auto() 269 ESCAPE = auto() 270 EXCEPT = auto() 271 EXECUTE = auto() 272 EXISTS = auto() 273 FALSE = auto() 274 FETCH = auto() 275 FILTER = auto() 276 FINAL = auto() 277 FIRST = auto() 278 FOR = auto() 279 FORCE = auto() 280 FOREIGN_KEY = auto() 281 FORMAT = auto() 282 FROM = auto() 283 FULL = auto() 284 FUNCTION = auto() 285 GLOB = auto() 286 GLOBAL = auto() 287 GRANT = auto() 288 GROUP_BY = auto() 289 GROUPING_SETS = auto() 290 HAVING = auto() 291 HINT = auto() 292 IGNORE = auto() 293 ILIKE = auto() 294 ILIKE_ANY = auto() 295 IN = auto() 296 INDEX = auto() 297 INNER = auto() 298 INSERT = auto() 299 INTERSECT = auto() 300 INTERVAL = auto() 301 INTO = auto() 302 INTRODUCER = auto() 303 IRLIKE = auto() 304 IS = auto() 305 ISNULL = auto() 306 JOIN = auto() 307 JOIN_MARKER = auto() 308 KEEP = auto() 309 KEY = auto() 310 KILL = auto() 311 LANGUAGE = auto() 312 LATERAL = auto() 313 LEFT = auto() 314 LIKE = auto() 315 LIKE_ANY = auto() 316 LIMIT = auto() 317 LIST = auto() 318 LOAD = auto() 319 LOCK = auto() 320 MAP = auto() 321 MATCH_CONDITION = auto() 322 MATCH_RECOGNIZE = auto() 323 MEMBER_OF = auto() 324 MERGE = auto() 325 MOD = auto() 326 MODEL = auto() 327 NATURAL = auto() 328 NEXT = auto() 329 NOTNULL = auto() 330 NULL = auto() 331 OBJECT_IDENTIFIER = auto() 332 OFFSET = auto() 333 ON = auto() 334 ONLY = auto() 335 OPERATOR = auto() 336 ORDER_BY = auto() 337 ORDER_SIBLINGS_BY = auto() 338 ORDERED = auto() 339 ORDINALITY = auto() 340 OUTER = auto() 341 OVER = auto() 342 OVERLAPS = auto() 343 OVERWRITE = auto() 344 PARTITION = auto() 345 PARTITION_BY = auto() 346 PERCENT = auto() 347 PIVOT = auto() 348 PLACEHOLDER = auto() 349 POSITIONAL = auto() 350 PRAGMA = auto() 351 PREWHERE = auto() 352 PRIMARY_KEY = auto() 353 PROCEDURE = auto() 354 PROPERTIES = auto() 355 PSEUDO_TYPE = auto() 356 QUALIFY = auto() 357 QUOTE = auto() 358 RANGE = auto() 359 RECURSIVE = auto() 360 REFRESH = auto() 361 RENAME = auto() 362 REPLACE = auto() 363 RETURNING = auto() 364 REFERENCES = auto() 365 RIGHT = auto() 366 RLIKE = auto() 367 ROLLBACK = auto() 368 ROLLUP = auto() 369 ROW = auto() 370 ROWS = auto() 371 SELECT = auto() 372 SEMI = auto() 373 SEPARATOR = auto() 374 SEQUENCE = auto() 375 SERDE_PROPERTIES = auto() 376 SET = auto() 377 SETTINGS = auto() 378 SHOW = auto() 379 SIMILAR_TO = auto() 380 SOME = auto() 381 SORT_BY = auto() 382 START_WITH = auto() 383 STORAGE_INTEGRATION = auto() 384 STRAIGHT_JOIN = auto() 385 STRUCT = auto() 386 SUMMARIZE = auto() 387 TABLE_SAMPLE = auto() 388 TAG = auto() 389 TEMPORARY = auto() 390 TOP = auto() 391 THEN = auto() 392 TRUE = auto() 393 TRUNCATE = auto() 394 UNCACHE = auto() 395 UNION = auto() 396 UNNEST = auto() 397 UNPIVOT = auto() 398 UPDATE = auto() 399 USE = auto() 400 USING = auto() 401 VALUES = auto() 402 VIEW = auto() 403 VOLATILE = auto() 404 WHEN = auto() 405 WHERE = auto() 406 WINDOW = auto() 407 WITH = auto() 408 UNIQUE = auto() 409 VERSION_SNAPSHOT = auto() 410 TIMESTAMP_SNAPSHOT = auto() 411 OPTION = auto() 412 SINK = auto() 413 SOURCE = auto()
An enumeration.
L_PAREN =
<TokenType.L_PAREN: 'L_PAREN'>
R_PAREN =
<TokenType.R_PAREN: 'R_PAREN'>
L_BRACKET =
<TokenType.L_BRACKET: 'L_BRACKET'>
R_BRACKET =
<TokenType.R_BRACKET: 'R_BRACKET'>
L_BRACE =
<TokenType.L_BRACE: 'L_BRACE'>
R_BRACE =
<TokenType.R_BRACE: 'R_BRACE'>
COMMA =
<TokenType.COMMA: 'COMMA'>
DOT =
<TokenType.DOT: 'DOT'>
DASH =
<TokenType.DASH: 'DASH'>
PLUS =
<TokenType.PLUS: 'PLUS'>
COLON =
<TokenType.COLON: 'COLON'>
DCOLON =
<TokenType.DCOLON: 'DCOLON'>
DQMARK =
<TokenType.DQMARK: 'DQMARK'>
SEMICOLON =
<TokenType.SEMICOLON: 'SEMICOLON'>
STAR =
<TokenType.STAR: 'STAR'>
BACKSLASH =
<TokenType.BACKSLASH: 'BACKSLASH'>
SLASH =
<TokenType.SLASH: 'SLASH'>
LT =
<TokenType.LT: 'LT'>
LTE =
<TokenType.LTE: 'LTE'>
GT =
<TokenType.GT: 'GT'>
GTE =
<TokenType.GTE: 'GTE'>
NOT =
<TokenType.NOT: 'NOT'>
EQ =
<TokenType.EQ: 'EQ'>
NEQ =
<TokenType.NEQ: 'NEQ'>
NULLSAFE_EQ =
<TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>
COLON_EQ =
<TokenType.COLON_EQ: 'COLON_EQ'>
AND =
<TokenType.AND: 'AND'>
OR =
<TokenType.OR: 'OR'>
AMP =
<TokenType.AMP: 'AMP'>
DPIPE =
<TokenType.DPIPE: 'DPIPE'>
PIPE =
<TokenType.PIPE: 'PIPE'>
PIPE_SLASH =
<TokenType.PIPE_SLASH: 'PIPE_SLASH'>
DPIPE_SLASH =
<TokenType.DPIPE_SLASH: 'DPIPE_SLASH'>
CARET =
<TokenType.CARET: 'CARET'>
CARET_AT =
<TokenType.CARET_AT: 'CARET_AT'>
TILDA =
<TokenType.TILDA: 'TILDA'>
ARROW =
<TokenType.ARROW: 'ARROW'>
DARROW =
<TokenType.DARROW: 'DARROW'>
FARROW =
<TokenType.FARROW: 'FARROW'>
HASH =
<TokenType.HASH: 'HASH'>
HASH_ARROW =
<TokenType.HASH_ARROW: 'HASH_ARROW'>
DHASH_ARROW =
<TokenType.DHASH_ARROW: 'DHASH_ARROW'>
LR_ARROW =
<TokenType.LR_ARROW: 'LR_ARROW'>
DAT =
<TokenType.DAT: 'DAT'>
LT_AT =
<TokenType.LT_AT: 'LT_AT'>
AT_GT =
<TokenType.AT_GT: 'AT_GT'>
DOLLAR =
<TokenType.DOLLAR: 'DOLLAR'>
PARAMETER =
<TokenType.PARAMETER: 'PARAMETER'>
SESSION_PARAMETER =
<TokenType.SESSION_PARAMETER: 'SESSION_PARAMETER'>
DAMP =
<TokenType.DAMP: 'DAMP'>
XOR =
<TokenType.XOR: 'XOR'>
DSTAR =
<TokenType.DSTAR: 'DSTAR'>
BLOCK_START =
<TokenType.BLOCK_START: 'BLOCK_START'>
BLOCK_END =
<TokenType.BLOCK_END: 'BLOCK_END'>
SPACE =
<TokenType.SPACE: 'SPACE'>
BREAK =
<TokenType.BREAK: 'BREAK'>
STRING =
<TokenType.STRING: 'STRING'>
NUMBER =
<TokenType.NUMBER: 'NUMBER'>
IDENTIFIER =
<TokenType.IDENTIFIER: 'IDENTIFIER'>
DATABASE =
<TokenType.DATABASE: 'DATABASE'>
COLUMN =
<TokenType.COLUMN: 'COLUMN'>
COLUMN_DEF =
<TokenType.COLUMN_DEF: 'COLUMN_DEF'>
SCHEMA =
<TokenType.SCHEMA: 'SCHEMA'>
TABLE =
<TokenType.TABLE: 'TABLE'>
WAREHOUSE =
<TokenType.WAREHOUSE: 'WAREHOUSE'>
STREAMLIT =
<TokenType.STREAMLIT: 'STREAMLIT'>
VAR =
<TokenType.VAR: 'VAR'>
BIT_STRING =
<TokenType.BIT_STRING: 'BIT_STRING'>
HEX_STRING =
<TokenType.HEX_STRING: 'HEX_STRING'>
BYTE_STRING =
<TokenType.BYTE_STRING: 'BYTE_STRING'>
NATIONAL_STRING =
<TokenType.NATIONAL_STRING: 'NATIONAL_STRING'>
RAW_STRING =
<TokenType.RAW_STRING: 'RAW_STRING'>
HEREDOC_STRING =
<TokenType.HEREDOC_STRING: 'HEREDOC_STRING'>
UNICODE_STRING =
<TokenType.UNICODE_STRING: 'UNICODE_STRING'>
BIT =
<TokenType.BIT: 'BIT'>
BOOLEAN =
<TokenType.BOOLEAN: 'BOOLEAN'>
TINYINT =
<TokenType.TINYINT: 'TINYINT'>
UTINYINT =
<TokenType.UTINYINT: 'UTINYINT'>
SMALLINT =
<TokenType.SMALLINT: 'SMALLINT'>
USMALLINT =
<TokenType.USMALLINT: 'USMALLINT'>
MEDIUMINT =
<TokenType.MEDIUMINT: 'MEDIUMINT'>
UMEDIUMINT =
<TokenType.UMEDIUMINT: 'UMEDIUMINT'>
INT =
<TokenType.INT: 'INT'>
UINT =
<TokenType.UINT: 'UINT'>
BIGINT =
<TokenType.BIGINT: 'BIGINT'>
UBIGINT =
<TokenType.UBIGINT: 'UBIGINT'>
INT128 =
<TokenType.INT128: 'INT128'>
UINT128 =
<TokenType.UINT128: 'UINT128'>
INT256 =
<TokenType.INT256: 'INT256'>
UINT256 =
<TokenType.UINT256: 'UINT256'>
FLOAT =
<TokenType.FLOAT: 'FLOAT'>
DOUBLE =
<TokenType.DOUBLE: 'DOUBLE'>
DECIMAL =
<TokenType.DECIMAL: 'DECIMAL'>
DECIMAL32 =
<TokenType.DECIMAL32: 'DECIMAL32'>
DECIMAL64 =
<TokenType.DECIMAL64: 'DECIMAL64'>
DECIMAL128 =
<TokenType.DECIMAL128: 'DECIMAL128'>
DECIMAL256 =
<TokenType.DECIMAL256: 'DECIMAL256'>
UDECIMAL =
<TokenType.UDECIMAL: 'UDECIMAL'>
BIGDECIMAL =
<TokenType.BIGDECIMAL: 'BIGDECIMAL'>
CHAR =
<TokenType.CHAR: 'CHAR'>
NCHAR =
<TokenType.NCHAR: 'NCHAR'>
VARCHAR =
<TokenType.VARCHAR: 'VARCHAR'>
NVARCHAR =
<TokenType.NVARCHAR: 'NVARCHAR'>
BPCHAR =
<TokenType.BPCHAR: 'BPCHAR'>
TEXT =
<TokenType.TEXT: 'TEXT'>
MEDIUMTEXT =
<TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT =
<TokenType.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB =
<TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB =
<TokenType.LONGBLOB: 'LONGBLOB'>
TINYBLOB =
<TokenType.TINYBLOB: 'TINYBLOB'>
TINYTEXT =
<TokenType.TINYTEXT: 'TINYTEXT'>
NAME =
<TokenType.NAME: 'NAME'>
BINARY =
<TokenType.BINARY: 'BINARY'>
VARBINARY =
<TokenType.VARBINARY: 'VARBINARY'>
JSON =
<TokenType.JSON: 'JSON'>
JSONB =
<TokenType.JSONB: 'JSONB'>
TIME =
<TokenType.TIME: 'TIME'>
TIMETZ =
<TokenType.TIMETZ: 'TIMETZ'>
TIMESTAMP =
<TokenType.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ =
<TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ =
<TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPNTZ =
<TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>
TIMESTAMP_S =
<TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>
TIMESTAMP_MS =
<TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>
TIMESTAMP_NS =
<TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>
DATETIME =
<TokenType.DATETIME: 'DATETIME'>
DATETIME2 =
<TokenType.DATETIME2: 'DATETIME2'>
DATETIME64 =
<TokenType.DATETIME64: 'DATETIME64'>
SMALLDATETIME =
<TokenType.SMALLDATETIME: 'SMALLDATETIME'>
DATE =
<TokenType.DATE: 'DATE'>
DATE32 =
<TokenType.DATE32: 'DATE32'>
INT4RANGE =
<TokenType.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE =
<TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE =
<TokenType.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE =
<TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE =
<TokenType.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE =
<TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE =
<TokenType.TSRANGE: 'TSRANGE'>
TSMULTIRANGE =
<TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE =
<TokenType.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE =
<TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE =
<TokenType.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE =
<TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>
UUID =
<TokenType.UUID: 'UUID'>
GEOGRAPHY =
<TokenType.GEOGRAPHY: 'GEOGRAPHY'>
NULLABLE =
<TokenType.NULLABLE: 'NULLABLE'>
GEOMETRY =
<TokenType.GEOMETRY: 'GEOMETRY'>
POINT =
<TokenType.POINT: 'POINT'>
RING =
<TokenType.RING: 'RING'>
LINESTRING =
<TokenType.LINESTRING: 'LINESTRING'>
MULTILINESTRING =
<TokenType.MULTILINESTRING: 'MULTILINESTRING'>
POLYGON =
<TokenType.POLYGON: 'POLYGON'>
MULTIPOLYGON =
<TokenType.MULTIPOLYGON: 'MULTIPOLYGON'>
HLLSKETCH =
<TokenType.HLLSKETCH: 'HLLSKETCH'>
HSTORE =
<TokenType.HSTORE: 'HSTORE'>
SUPER =
<TokenType.SUPER: 'SUPER'>
SERIAL =
<TokenType.SERIAL: 'SERIAL'>
SMALLSERIAL =
<TokenType.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL =
<TokenType.BIGSERIAL: 'BIGSERIAL'>
XML =
<TokenType.XML: 'XML'>
YEAR =
<TokenType.YEAR: 'YEAR'>
UNIQUEIDENTIFIER =
<TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
USERDEFINED =
<TokenType.USERDEFINED: 'USERDEFINED'>
MONEY =
<TokenType.MONEY: 'MONEY'>
SMALLMONEY =
<TokenType.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION =
<TokenType.ROWVERSION: 'ROWVERSION'>
IMAGE =
<TokenType.IMAGE: 'IMAGE'>
VARIANT =
<TokenType.VARIANT: 'VARIANT'>
OBJECT =
<TokenType.OBJECT: 'OBJECT'>
INET =
<TokenType.INET: 'INET'>
IPADDRESS =
<TokenType.IPADDRESS: 'IPADDRESS'>
IPPREFIX =
<TokenType.IPPREFIX: 'IPPREFIX'>
IPV4 =
<TokenType.IPV4: 'IPV4'>
IPV6 =
<TokenType.IPV6: 'IPV6'>
ENUM =
<TokenType.ENUM: 'ENUM'>
ENUM8 =
<TokenType.ENUM8: 'ENUM8'>
ENUM16 =
<TokenType.ENUM16: 'ENUM16'>
FIXEDSTRING =
<TokenType.FIXEDSTRING: 'FIXEDSTRING'>
LOWCARDINALITY =
<TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>
NESTED =
<TokenType.NESTED: 'NESTED'>
AGGREGATEFUNCTION =
<TokenType.AGGREGATEFUNCTION: 'AGGREGATEFUNCTION'>
SIMPLEAGGREGATEFUNCTION =
<TokenType.SIMPLEAGGREGATEFUNCTION: 'SIMPLEAGGREGATEFUNCTION'>
TDIGEST =
<TokenType.TDIGEST: 'TDIGEST'>
UNKNOWN =
<TokenType.UNKNOWN: 'UNKNOWN'>
VECTOR =
<TokenType.VECTOR: 'VECTOR'>
ALIAS =
<TokenType.ALIAS: 'ALIAS'>
ALTER =
<TokenType.ALTER: 'ALTER'>
ALWAYS =
<TokenType.ALWAYS: 'ALWAYS'>
ALL =
<TokenType.ALL: 'ALL'>
ANTI =
<TokenType.ANTI: 'ANTI'>
ANY =
<TokenType.ANY: 'ANY'>
APPLY =
<TokenType.APPLY: 'APPLY'>
ARRAY =
<TokenType.ARRAY: 'ARRAY'>
ASC =
<TokenType.ASC: 'ASC'>
ASOF =
<TokenType.ASOF: 'ASOF'>
ATTACH =
<TokenType.ATTACH: 'ATTACH'>
AUTO_INCREMENT =
<TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>
BEGIN =
<TokenType.BEGIN: 'BEGIN'>
BETWEEN =
<TokenType.BETWEEN: 'BETWEEN'>
BULK_COLLECT_INTO =
<TokenType.BULK_COLLECT_INTO: 'BULK_COLLECT_INTO'>
CACHE =
<TokenType.CACHE: 'CACHE'>
CASE =
<TokenType.CASE: 'CASE'>
CHARACTER_SET =
<TokenType.CHARACTER_SET: 'CHARACTER_SET'>
CLUSTER_BY =
<TokenType.CLUSTER_BY: 'CLUSTER_BY'>
COLLATE =
<TokenType.COLLATE: 'COLLATE'>
COMMAND =
<TokenType.COMMAND: 'COMMAND'>
COMMENT =
<TokenType.COMMENT: 'COMMENT'>
COMMIT =
<TokenType.COMMIT: 'COMMIT'>
CONNECT_BY =
<TokenType.CONNECT_BY: 'CONNECT_BY'>
CONSTRAINT =
<TokenType.CONSTRAINT: 'CONSTRAINT'>
COPY =
<TokenType.COPY: 'COPY'>
CREATE =
<TokenType.CREATE: 'CREATE'>
CROSS =
<TokenType.CROSS: 'CROSS'>
CUBE =
<TokenType.CUBE: 'CUBE'>
CURRENT_DATE =
<TokenType.CURRENT_DATE: 'CURRENT_DATE'>
CURRENT_DATETIME =
<TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>
CURRENT_TIME =
<TokenType.CURRENT_TIME: 'CURRENT_TIME'>
CURRENT_TIMESTAMP =
<TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>
CURRENT_USER =
<TokenType.CURRENT_USER: 'CURRENT_USER'>
DECLARE =
<TokenType.DECLARE: 'DECLARE'>
DEFAULT =
<TokenType.DEFAULT: 'DEFAULT'>
DELETE =
<TokenType.DELETE: 'DELETE'>
DESC =
<TokenType.DESC: 'DESC'>
DESCRIBE =
<TokenType.DESCRIBE: 'DESCRIBE'>
DETACH =
<TokenType.DETACH: 'DETACH'>
DICTIONARY =
<TokenType.DICTIONARY: 'DICTIONARY'>
DISTINCT =
<TokenType.DISTINCT: 'DISTINCT'>
DISTRIBUTE_BY =
<TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>
DIV =
<TokenType.DIV: 'DIV'>
DROP =
<TokenType.DROP: 'DROP'>
ELSE =
<TokenType.ELSE: 'ELSE'>
END =
<TokenType.END: 'END'>
ESCAPE =
<TokenType.ESCAPE: 'ESCAPE'>
EXCEPT =
<TokenType.EXCEPT: 'EXCEPT'>
EXECUTE =
<TokenType.EXECUTE: 'EXECUTE'>
EXISTS =
<TokenType.EXISTS: 'EXISTS'>
FALSE =
<TokenType.FALSE: 'FALSE'>
FETCH =
<TokenType.FETCH: 'FETCH'>
FILTER =
<TokenType.FILTER: 'FILTER'>
FINAL =
<TokenType.FINAL: 'FINAL'>
FIRST =
<TokenType.FIRST: 'FIRST'>
FOR =
<TokenType.FOR: 'FOR'>
FORCE =
<TokenType.FORCE: 'FORCE'>
FOREIGN_KEY =
<TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>
FORMAT =
<TokenType.FORMAT: 'FORMAT'>
FROM =
<TokenType.FROM: 'FROM'>
FULL =
<TokenType.FULL: 'FULL'>
FUNCTION =
<TokenType.FUNCTION: 'FUNCTION'>
GLOB =
<TokenType.GLOB: 'GLOB'>
GLOBAL =
<TokenType.GLOBAL: 'GLOBAL'>
GRANT =
<TokenType.GRANT: 'GRANT'>
GROUP_BY =
<TokenType.GROUP_BY: 'GROUP_BY'>
GROUPING_SETS =
<TokenType.GROUPING_SETS: 'GROUPING_SETS'>
HAVING =
<TokenType.HAVING: 'HAVING'>
HINT =
<TokenType.HINT: 'HINT'>
IGNORE =
<TokenType.IGNORE: 'IGNORE'>
ILIKE =
<TokenType.ILIKE: 'ILIKE'>
ILIKE_ANY =
<TokenType.ILIKE_ANY: 'ILIKE_ANY'>
IN =
<TokenType.IN: 'IN'>
INDEX =
<TokenType.INDEX: 'INDEX'>
INNER =
<TokenType.INNER: 'INNER'>
INSERT =
<TokenType.INSERT: 'INSERT'>
INTERSECT =
<TokenType.INTERSECT: 'INTERSECT'>
INTERVAL =
<TokenType.INTERVAL: 'INTERVAL'>
INTO =
<TokenType.INTO: 'INTO'>
INTRODUCER =
<TokenType.INTRODUCER: 'INTRODUCER'>
IRLIKE =
<TokenType.IRLIKE: 'IRLIKE'>
IS =
<TokenType.IS: 'IS'>
ISNULL =
<TokenType.ISNULL: 'ISNULL'>
JOIN =
<TokenType.JOIN: 'JOIN'>
JOIN_MARKER =
<TokenType.JOIN_MARKER: 'JOIN_MARKER'>
KEEP =
<TokenType.KEEP: 'KEEP'>
KEY =
<TokenType.KEY: 'KEY'>
KILL =
<TokenType.KILL: 'KILL'>
LANGUAGE =
<TokenType.LANGUAGE: 'LANGUAGE'>
LATERAL =
<TokenType.LATERAL: 'LATERAL'>
LEFT =
<TokenType.LEFT: 'LEFT'>
LIKE =
<TokenType.LIKE: 'LIKE'>
LIKE_ANY =
<TokenType.LIKE_ANY: 'LIKE_ANY'>
LIMIT =
<TokenType.LIMIT: 'LIMIT'>
LIST =
<TokenType.LIST: 'LIST'>
LOAD =
<TokenType.LOAD: 'LOAD'>
LOCK =
<TokenType.LOCK: 'LOCK'>
MAP =
<TokenType.MAP: 'MAP'>
MATCH_CONDITION =
<TokenType.MATCH_CONDITION: 'MATCH_CONDITION'>
MATCH_RECOGNIZE =
<TokenType.MATCH_RECOGNIZE: 'MATCH_RECOGNIZE'>
MEMBER_OF =
<TokenType.MEMBER_OF: 'MEMBER_OF'>
MERGE =
<TokenType.MERGE: 'MERGE'>
MOD =
<TokenType.MOD: 'MOD'>
MODEL =
<TokenType.MODEL: 'MODEL'>
NATURAL =
<TokenType.NATURAL: 'NATURAL'>
NEXT =
<TokenType.NEXT: 'NEXT'>
NOTNULL =
<TokenType.NOTNULL: 'NOTNULL'>
NULL =
<TokenType.NULL: 'NULL'>
OBJECT_IDENTIFIER =
<TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>
OFFSET =
<TokenType.OFFSET: 'OFFSET'>
ON =
<TokenType.ON: 'ON'>
ONLY =
<TokenType.ONLY: 'ONLY'>
OPERATOR =
<TokenType.OPERATOR: 'OPERATOR'>
ORDER_BY =
<TokenType.ORDER_BY: 'ORDER_BY'>
ORDER_SIBLINGS_BY =
<TokenType.ORDER_SIBLINGS_BY: 'ORDER_SIBLINGS_BY'>
ORDERED =
<TokenType.ORDERED: 'ORDERED'>
ORDINALITY =
<TokenType.ORDINALITY: 'ORDINALITY'>
OUTER =
<TokenType.OUTER: 'OUTER'>
OVER =
<TokenType.OVER: 'OVER'>
OVERLAPS =
<TokenType.OVERLAPS: 'OVERLAPS'>
OVERWRITE =
<TokenType.OVERWRITE: 'OVERWRITE'>
PARTITION =
<TokenType.PARTITION: 'PARTITION'>
PARTITION_BY =
<TokenType.PARTITION_BY: 'PARTITION_BY'>
PERCENT =
<TokenType.PERCENT: 'PERCENT'>
PIVOT =
<TokenType.PIVOT: 'PIVOT'>
PLACEHOLDER =
<TokenType.PLACEHOLDER: 'PLACEHOLDER'>
POSITIONAL =
<TokenType.POSITIONAL: 'POSITIONAL'>
PRAGMA =
<TokenType.PRAGMA: 'PRAGMA'>
PREWHERE =
<TokenType.PREWHERE: 'PREWHERE'>
PRIMARY_KEY =
<TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>
PROCEDURE =
<TokenType.PROCEDURE: 'PROCEDURE'>
PROPERTIES =
<TokenType.PROPERTIES: 'PROPERTIES'>
PSEUDO_TYPE =
<TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>
QUALIFY =
<TokenType.QUALIFY: 'QUALIFY'>
QUOTE =
<TokenType.QUOTE: 'QUOTE'>
RANGE =
<TokenType.RANGE: 'RANGE'>
RECURSIVE =
<TokenType.RECURSIVE: 'RECURSIVE'>
REFRESH =
<TokenType.REFRESH: 'REFRESH'>
RENAME =
<TokenType.RENAME: 'RENAME'>
REPLACE =
<TokenType.REPLACE: 'REPLACE'>
RETURNING =
<TokenType.RETURNING: 'RETURNING'>
REFERENCES =
<TokenType.REFERENCES: 'REFERENCES'>
RIGHT =
<TokenType.RIGHT: 'RIGHT'>
RLIKE =
<TokenType.RLIKE: 'RLIKE'>
ROLLBACK =
<TokenType.ROLLBACK: 'ROLLBACK'>
ROLLUP =
<TokenType.ROLLUP: 'ROLLUP'>
ROW =
<TokenType.ROW: 'ROW'>
ROWS =
<TokenType.ROWS: 'ROWS'>
SELECT =
<TokenType.SELECT: 'SELECT'>
SEMI =
<TokenType.SEMI: 'SEMI'>
SEPARATOR =
<TokenType.SEPARATOR: 'SEPARATOR'>
SEQUENCE =
<TokenType.SEQUENCE: 'SEQUENCE'>
SERDE_PROPERTIES =
<TokenType.SERDE_PROPERTIES: 'SERDE_PROPERTIES'>
SET =
<TokenType.SET: 'SET'>
SETTINGS =
<TokenType.SETTINGS: 'SETTINGS'>
SHOW =
<TokenType.SHOW: 'SHOW'>
SIMILAR_TO =
<TokenType.SIMILAR_TO: 'SIMILAR_TO'>
SOME =
<TokenType.SOME: 'SOME'>
SORT_BY =
<TokenType.SORT_BY: 'SORT_BY'>
START_WITH =
<TokenType.START_WITH: 'START_WITH'>
STORAGE_INTEGRATION =
<TokenType.STORAGE_INTEGRATION: 'STORAGE_INTEGRATION'>
STRAIGHT_JOIN =
<TokenType.STRAIGHT_JOIN: 'STRAIGHT_JOIN'>
STRUCT =
<TokenType.STRUCT: 'STRUCT'>
SUMMARIZE =
<TokenType.SUMMARIZE: 'SUMMARIZE'>
TABLE_SAMPLE =
<TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>
TAG =
<TokenType.TAG: 'TAG'>
TEMPORARY =
<TokenType.TEMPORARY: 'TEMPORARY'>
TOP =
<TokenType.TOP: 'TOP'>
THEN =
<TokenType.THEN: 'THEN'>
TRUE =
<TokenType.TRUE: 'TRUE'>
TRUNCATE =
<TokenType.TRUNCATE: 'TRUNCATE'>
UNCACHE =
<TokenType.UNCACHE: 'UNCACHE'>
UNION =
<TokenType.UNION: 'UNION'>
UNNEST =
<TokenType.UNNEST: 'UNNEST'>
UNPIVOT =
<TokenType.UNPIVOT: 'UNPIVOT'>
UPDATE =
<TokenType.UPDATE: 'UPDATE'>
USE =
<TokenType.USE: 'USE'>
USING =
<TokenType.USING: 'USING'>
VALUES =
<TokenType.VALUES: 'VALUES'>
VIEW =
<TokenType.VIEW: 'VIEW'>
VOLATILE =
<TokenType.VOLATILE: 'VOLATILE'>
WHEN =
<TokenType.WHEN: 'WHEN'>
WHERE =
<TokenType.WHERE: 'WHERE'>
WINDOW =
<TokenType.WINDOW: 'WINDOW'>
WITH =
<TokenType.WITH: 'WITH'>
UNIQUE =
<TokenType.UNIQUE: 'UNIQUE'>
VERSION_SNAPSHOT =
<TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>
TIMESTAMP_SNAPSHOT =
<TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>
OPTION =
<TokenType.OPTION: 'OPTION'>
SINK =
<TokenType.SINK: 'SINK'>
SOURCE =
<TokenType.SOURCE: 'SOURCE'>
class
Token:
420class Token: 421 __slots__ = ("token_type", "text", "line", "col", "start", "end", "comments") 422 423 @classmethod 424 def number(cls, number: int) -> Token: 425 """Returns a NUMBER token with `number` as its text.""" 426 return cls(TokenType.NUMBER, str(number)) 427 428 @classmethod 429 def string(cls, string: str) -> Token: 430 """Returns a STRING token with `string` as its text.""" 431 return cls(TokenType.STRING, string) 432 433 @classmethod 434 def identifier(cls, identifier: str) -> Token: 435 """Returns an IDENTIFIER token with `identifier` as its text.""" 436 return cls(TokenType.IDENTIFIER, identifier) 437 438 @classmethod 439 def var(cls, var: str) -> Token: 440 """Returns an VAR token with `var` as its text.""" 441 return cls(TokenType.VAR, var) 442 443 def __init__( 444 self, 445 token_type: TokenType, 446 text: str, 447 line: int = 1, 448 col: int = 1, 449 start: int = 0, 450 end: int = 0, 451 comments: t.Optional[t.List[str]] = None, 452 ) -> None: 453 """Token initializer. 454 455 Args: 456 token_type: The TokenType Enum. 457 text: The text of the token. 458 line: The line that the token ends on. 459 col: The column that the token ends on. 460 start: The start index of the token. 461 end: The ending index of the token. 462 comments: The comments to attach to the token. 463 """ 464 self.token_type = token_type 465 self.text = text 466 self.line = line 467 self.col = col 468 self.start = start 469 self.end = end 470 self.comments = [] if comments is None else comments 471 472 def __repr__(self) -> str: 473 attributes = ", ".join(f"{k}: {getattr(self, k)}" for k in self.__slots__) 474 return f"<Token {attributes}>"
Token( token_type: TokenType, text: str, line: int = 1, col: int = 1, start: int = 0, end: int = 0, comments: Optional[List[str]] = None)
443 def __init__( 444 self, 445 token_type: TokenType, 446 text: str, 447 line: int = 1, 448 col: int = 1, 449 start: int = 0, 450 end: int = 0, 451 comments: t.Optional[t.List[str]] = None, 452 ) -> None: 453 """Token initializer. 454 455 Args: 456 token_type: The TokenType Enum. 457 text: The text of the token. 458 line: The line that the token ends on. 459 col: The column that the token ends on. 460 start: The start index of the token. 461 end: The ending index of the token. 462 comments: The comments to attach to the token. 463 """ 464 self.token_type = token_type 465 self.text = text 466 self.line = line 467 self.col = col 468 self.start = start 469 self.end = end 470 self.comments = [] if comments is None else comments
Token initializer.
Arguments:
- token_type: The TokenType Enum.
- text: The text of the token.
- line: The line that the token ends on.
- col: The column that the token ends on.
- start: The start index of the token.
- end: The ending index of the token.
- comments: The comments to attach to the token.
423 @classmethod 424 def number(cls, number: int) -> Token: 425 """Returns a NUMBER token with `number` as its text.""" 426 return cls(TokenType.NUMBER, str(number))
Returns a NUMBER token with number
as its text.
428 @classmethod 429 def string(cls, string: str) -> Token: 430 """Returns a STRING token with `string` as its text.""" 431 return cls(TokenType.STRING, string)
Returns a STRING token with string
as its text.
433 @classmethod 434 def identifier(cls, identifier: str) -> Token: 435 """Returns an IDENTIFIER token with `identifier` as its text.""" 436 return cls(TokenType.IDENTIFIER, identifier)
Returns an IDENTIFIER token with identifier
as its text.
class
Tokenizer:
584class Tokenizer(metaclass=_Tokenizer): 585 SINGLE_TOKENS = { 586 "(": TokenType.L_PAREN, 587 ")": TokenType.R_PAREN, 588 "[": TokenType.L_BRACKET, 589 "]": TokenType.R_BRACKET, 590 "{": TokenType.L_BRACE, 591 "}": TokenType.R_BRACE, 592 "&": TokenType.AMP, 593 "^": TokenType.CARET, 594 ":": TokenType.COLON, 595 ",": TokenType.COMMA, 596 ".": TokenType.DOT, 597 "-": TokenType.DASH, 598 "=": TokenType.EQ, 599 ">": TokenType.GT, 600 "<": TokenType.LT, 601 "%": TokenType.MOD, 602 "!": TokenType.NOT, 603 "|": TokenType.PIPE, 604 "+": TokenType.PLUS, 605 ";": TokenType.SEMICOLON, 606 "/": TokenType.SLASH, 607 "\\": TokenType.BACKSLASH, 608 "*": TokenType.STAR, 609 "~": TokenType.TILDA, 610 "?": TokenType.PLACEHOLDER, 611 "@": TokenType.PARAMETER, 612 "#": TokenType.HASH, 613 # Used for breaking a var like x'y' but nothing else the token type doesn't matter 614 "'": TokenType.UNKNOWN, 615 "`": TokenType.UNKNOWN, 616 '"': TokenType.UNKNOWN, 617 } 618 619 BIT_STRINGS: t.List[str | t.Tuple[str, str]] = [] 620 BYTE_STRINGS: t.List[str | t.Tuple[str, str]] = [] 621 HEX_STRINGS: t.List[str | t.Tuple[str, str]] = [] 622 RAW_STRINGS: t.List[str | t.Tuple[str, str]] = [] 623 HEREDOC_STRINGS: t.List[str | t.Tuple[str, str]] = [] 624 UNICODE_STRINGS: t.List[str | t.Tuple[str, str]] = [] 625 IDENTIFIERS: t.List[str | t.Tuple[str, str]] = ['"'] 626 QUOTES: t.List[t.Tuple[str, str] | str] = ["'"] 627 STRING_ESCAPES = ["'"] 628 VAR_SINGLE_TOKENS: t.Set[str] = set() 629 630 # The strings in this list can always be used as escapes, regardless of the surrounding 631 # identifier delimiters. By default, the closing delimiter is assumed to also act as an 632 # identifier escape, e.g. if we use double-quotes, then they also act as escapes: "x""" 633 IDENTIFIER_ESCAPES: t.List[str] = [] 634 635 # Whether the heredoc tags follow the same lexical rules as unquoted identifiers 636 HEREDOC_TAG_IS_IDENTIFIER = False 637 638 # Token that we'll generate as a fallback if the heredoc prefix doesn't correspond to a heredoc 639 HEREDOC_STRING_ALTERNATIVE = TokenType.VAR 640 641 # Whether string escape characters function as such when placed within raw strings 642 STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS = True 643 644 NESTED_COMMENTS = True 645 646 HINT_START = "/*+" 647 648 TOKENS_PRECEDING_HINT = {TokenType.SELECT, TokenType.INSERT, TokenType.UPDATE, TokenType.DELETE} 649 650 # Autofilled 651 _COMMENTS: t.Dict[str, str] = {} 652 _FORMAT_STRINGS: t.Dict[str, t.Tuple[str, TokenType]] = {} 653 _IDENTIFIERS: t.Dict[str, str] = {} 654 _IDENTIFIER_ESCAPES: t.Set[str] = set() 655 _QUOTES: t.Dict[str, str] = {} 656 _STRING_ESCAPES: t.Set[str] = set() 657 _KEYWORD_TRIE: t.Dict = {} 658 _RS_TOKENIZER: t.Optional[t.Any] = None 659 660 KEYWORDS: t.Dict[str, TokenType] = { 661 **{f"{{%{postfix}": TokenType.BLOCK_START for postfix in ("", "+", "-")}, 662 **{f"{prefix}%}}": TokenType.BLOCK_END for prefix in ("", "+", "-")}, 663 **{f"{{{{{postfix}": TokenType.BLOCK_START for postfix in ("+", "-")}, 664 **{f"{prefix}}}}}": TokenType.BLOCK_END for prefix in ("+", "-")}, 665 HINT_START: TokenType.HINT, 666 "==": TokenType.EQ, 667 "::": TokenType.DCOLON, 668 "||": TokenType.DPIPE, 669 ">=": TokenType.GTE, 670 "<=": TokenType.LTE, 671 "<>": TokenType.NEQ, 672 "!=": TokenType.NEQ, 673 ":=": TokenType.COLON_EQ, 674 "<=>": TokenType.NULLSAFE_EQ, 675 "->": TokenType.ARROW, 676 "->>": TokenType.DARROW, 677 "=>": TokenType.FARROW, 678 "#>": TokenType.HASH_ARROW, 679 "#>>": TokenType.DHASH_ARROW, 680 "<->": TokenType.LR_ARROW, 681 "&&": TokenType.DAMP, 682 "??": TokenType.DQMARK, 683 "~~~": TokenType.GLOB, 684 "~~": TokenType.LIKE, 685 "~~*": TokenType.ILIKE, 686 "~*": TokenType.IRLIKE, 687 "ALL": TokenType.ALL, 688 "ALWAYS": TokenType.ALWAYS, 689 "AND": TokenType.AND, 690 "ANTI": TokenType.ANTI, 691 "ANY": TokenType.ANY, 692 "ASC": TokenType.ASC, 693 "AS": TokenType.ALIAS, 694 "ASOF": TokenType.ASOF, 695 "AUTOINCREMENT": TokenType.AUTO_INCREMENT, 696 "AUTO_INCREMENT": TokenType.AUTO_INCREMENT, 697 "BEGIN": TokenType.BEGIN, 698 "BETWEEN": TokenType.BETWEEN, 699 "CACHE": TokenType.CACHE, 700 "UNCACHE": TokenType.UNCACHE, 701 "CASE": TokenType.CASE, 702 "CHARACTER SET": TokenType.CHARACTER_SET, 703 "CLUSTER BY": TokenType.CLUSTER_BY, 704 "COLLATE": TokenType.COLLATE, 705 "COLUMN": TokenType.COLUMN, 706 "COMMIT": TokenType.COMMIT, 707 "CONNECT BY": TokenType.CONNECT_BY, 708 "CONSTRAINT": TokenType.CONSTRAINT, 709 "COPY": TokenType.COPY, 710 "CREATE": TokenType.CREATE, 711 "CROSS": TokenType.CROSS, 712 "CUBE": TokenType.CUBE, 713 "CURRENT_DATE": TokenType.CURRENT_DATE, 714 "CURRENT_TIME": TokenType.CURRENT_TIME, 715 "CURRENT_TIMESTAMP": TokenType.CURRENT_TIMESTAMP, 716 "CURRENT_USER": TokenType.CURRENT_USER, 717 "DATABASE": TokenType.DATABASE, 718 "DEFAULT": TokenType.DEFAULT, 719 "DELETE": TokenType.DELETE, 720 "DESC": TokenType.DESC, 721 "DESCRIBE": TokenType.DESCRIBE, 722 "DISTINCT": TokenType.DISTINCT, 723 "DISTRIBUTE BY": TokenType.DISTRIBUTE_BY, 724 "DIV": TokenType.DIV, 725 "DROP": TokenType.DROP, 726 "ELSE": TokenType.ELSE, 727 "END": TokenType.END, 728 "ENUM": TokenType.ENUM, 729 "ESCAPE": TokenType.ESCAPE, 730 "EXCEPT": TokenType.EXCEPT, 731 "EXECUTE": TokenType.EXECUTE, 732 "EXISTS": TokenType.EXISTS, 733 "FALSE": TokenType.FALSE, 734 "FETCH": TokenType.FETCH, 735 "FILTER": TokenType.FILTER, 736 "FIRST": TokenType.FIRST, 737 "FULL": TokenType.FULL, 738 "FUNCTION": TokenType.FUNCTION, 739 "FOR": TokenType.FOR, 740 "FOREIGN KEY": TokenType.FOREIGN_KEY, 741 "FORMAT": TokenType.FORMAT, 742 "FROM": TokenType.FROM, 743 "GEOGRAPHY": TokenType.GEOGRAPHY, 744 "GEOMETRY": TokenType.GEOMETRY, 745 "GLOB": TokenType.GLOB, 746 "GROUP BY": TokenType.GROUP_BY, 747 "GROUPING SETS": TokenType.GROUPING_SETS, 748 "HAVING": TokenType.HAVING, 749 "ILIKE": TokenType.ILIKE, 750 "IN": TokenType.IN, 751 "INDEX": TokenType.INDEX, 752 "INET": TokenType.INET, 753 "INNER": TokenType.INNER, 754 "INSERT": TokenType.INSERT, 755 "INTERVAL": TokenType.INTERVAL, 756 "INTERSECT": TokenType.INTERSECT, 757 "INTO": TokenType.INTO, 758 "IS": TokenType.IS, 759 "ISNULL": TokenType.ISNULL, 760 "JOIN": TokenType.JOIN, 761 "KEEP": TokenType.KEEP, 762 "KILL": TokenType.KILL, 763 "LATERAL": TokenType.LATERAL, 764 "LEFT": TokenType.LEFT, 765 "LIKE": TokenType.LIKE, 766 "LIMIT": TokenType.LIMIT, 767 "LOAD": TokenType.LOAD, 768 "LOCK": TokenType.LOCK, 769 "MERGE": TokenType.MERGE, 770 "NATURAL": TokenType.NATURAL, 771 "NEXT": TokenType.NEXT, 772 "NOT": TokenType.NOT, 773 "NOTNULL": TokenType.NOTNULL, 774 "NULL": TokenType.NULL, 775 "OBJECT": TokenType.OBJECT, 776 "OFFSET": TokenType.OFFSET, 777 "ON": TokenType.ON, 778 "OR": TokenType.OR, 779 "XOR": TokenType.XOR, 780 "ORDER BY": TokenType.ORDER_BY, 781 "ORDINALITY": TokenType.ORDINALITY, 782 "OUTER": TokenType.OUTER, 783 "OVER": TokenType.OVER, 784 "OVERLAPS": TokenType.OVERLAPS, 785 "OVERWRITE": TokenType.OVERWRITE, 786 "PARTITION": TokenType.PARTITION, 787 "PARTITION BY": TokenType.PARTITION_BY, 788 "PARTITIONED BY": TokenType.PARTITION_BY, 789 "PARTITIONED_BY": TokenType.PARTITION_BY, 790 "PERCENT": TokenType.PERCENT, 791 "PIVOT": TokenType.PIVOT, 792 "PRAGMA": TokenType.PRAGMA, 793 "PRIMARY KEY": TokenType.PRIMARY_KEY, 794 "PROCEDURE": TokenType.PROCEDURE, 795 "QUALIFY": TokenType.QUALIFY, 796 "RANGE": TokenType.RANGE, 797 "RECURSIVE": TokenType.RECURSIVE, 798 "REGEXP": TokenType.RLIKE, 799 "RENAME": TokenType.RENAME, 800 "REPLACE": TokenType.REPLACE, 801 "RETURNING": TokenType.RETURNING, 802 "REFERENCES": TokenType.REFERENCES, 803 "RIGHT": TokenType.RIGHT, 804 "RLIKE": TokenType.RLIKE, 805 "ROLLBACK": TokenType.ROLLBACK, 806 "ROLLUP": TokenType.ROLLUP, 807 "ROW": TokenType.ROW, 808 "ROWS": TokenType.ROWS, 809 "SCHEMA": TokenType.SCHEMA, 810 "SELECT": TokenType.SELECT, 811 "SEMI": TokenType.SEMI, 812 "SET": TokenType.SET, 813 "SETTINGS": TokenType.SETTINGS, 814 "SHOW": TokenType.SHOW, 815 "SIMILAR TO": TokenType.SIMILAR_TO, 816 "SOME": TokenType.SOME, 817 "SORT BY": TokenType.SORT_BY, 818 "START WITH": TokenType.START_WITH, 819 "STRAIGHT_JOIN": TokenType.STRAIGHT_JOIN, 820 "TABLE": TokenType.TABLE, 821 "TABLESAMPLE": TokenType.TABLE_SAMPLE, 822 "TEMP": TokenType.TEMPORARY, 823 "TEMPORARY": TokenType.TEMPORARY, 824 "THEN": TokenType.THEN, 825 "TRUE": TokenType.TRUE, 826 "TRUNCATE": TokenType.TRUNCATE, 827 "UNION": TokenType.UNION, 828 "UNKNOWN": TokenType.UNKNOWN, 829 "UNNEST": TokenType.UNNEST, 830 "UNPIVOT": TokenType.UNPIVOT, 831 "UPDATE": TokenType.UPDATE, 832 "USE": TokenType.USE, 833 "USING": TokenType.USING, 834 "UUID": TokenType.UUID, 835 "VALUES": TokenType.VALUES, 836 "VIEW": TokenType.VIEW, 837 "VOLATILE": TokenType.VOLATILE, 838 "WHEN": TokenType.WHEN, 839 "WHERE": TokenType.WHERE, 840 "WINDOW": TokenType.WINDOW, 841 "WITH": TokenType.WITH, 842 "APPLY": TokenType.APPLY, 843 "ARRAY": TokenType.ARRAY, 844 "BIT": TokenType.BIT, 845 "BOOL": TokenType.BOOLEAN, 846 "BOOLEAN": TokenType.BOOLEAN, 847 "BYTE": TokenType.TINYINT, 848 "MEDIUMINT": TokenType.MEDIUMINT, 849 "INT1": TokenType.TINYINT, 850 "TINYINT": TokenType.TINYINT, 851 "INT16": TokenType.SMALLINT, 852 "SHORT": TokenType.SMALLINT, 853 "SMALLINT": TokenType.SMALLINT, 854 "INT128": TokenType.INT128, 855 "HUGEINT": TokenType.INT128, 856 "UHUGEINT": TokenType.UINT128, 857 "INT2": TokenType.SMALLINT, 858 "INTEGER": TokenType.INT, 859 "INT": TokenType.INT, 860 "INT4": TokenType.INT, 861 "INT32": TokenType.INT, 862 "INT64": TokenType.BIGINT, 863 "LONG": TokenType.BIGINT, 864 "BIGINT": TokenType.BIGINT, 865 "INT8": TokenType.TINYINT, 866 "UINT": TokenType.UINT, 867 "DEC": TokenType.DECIMAL, 868 "DECIMAL": TokenType.DECIMAL, 869 "DECIMAL32": TokenType.DECIMAL32, 870 "DECIMAL64": TokenType.DECIMAL64, 871 "DECIMAL128": TokenType.DECIMAL128, 872 "DECIMAL256": TokenType.DECIMAL256, 873 "BIGDECIMAL": TokenType.BIGDECIMAL, 874 "BIGNUMERIC": TokenType.BIGDECIMAL, 875 "LIST": TokenType.LIST, 876 "MAP": TokenType.MAP, 877 "NULLABLE": TokenType.NULLABLE, 878 "NUMBER": TokenType.DECIMAL, 879 "NUMERIC": TokenType.DECIMAL, 880 "FIXED": TokenType.DECIMAL, 881 "REAL": TokenType.FLOAT, 882 "FLOAT": TokenType.FLOAT, 883 "FLOAT4": TokenType.FLOAT, 884 "FLOAT8": TokenType.DOUBLE, 885 "DOUBLE": TokenType.DOUBLE, 886 "DOUBLE PRECISION": TokenType.DOUBLE, 887 "JSON": TokenType.JSON, 888 "JSONB": TokenType.JSONB, 889 "CHAR": TokenType.CHAR, 890 "CHARACTER": TokenType.CHAR, 891 "NCHAR": TokenType.NCHAR, 892 "VARCHAR": TokenType.VARCHAR, 893 "VARCHAR2": TokenType.VARCHAR, 894 "NVARCHAR": TokenType.NVARCHAR, 895 "NVARCHAR2": TokenType.NVARCHAR, 896 "BPCHAR": TokenType.BPCHAR, 897 "STR": TokenType.TEXT, 898 "STRING": TokenType.TEXT, 899 "TEXT": TokenType.TEXT, 900 "LONGTEXT": TokenType.LONGTEXT, 901 "MEDIUMTEXT": TokenType.MEDIUMTEXT, 902 "TINYTEXT": TokenType.TINYTEXT, 903 "CLOB": TokenType.TEXT, 904 "LONGVARCHAR": TokenType.TEXT, 905 "BINARY": TokenType.BINARY, 906 "BLOB": TokenType.VARBINARY, 907 "LONGBLOB": TokenType.LONGBLOB, 908 "MEDIUMBLOB": TokenType.MEDIUMBLOB, 909 "TINYBLOB": TokenType.TINYBLOB, 910 "BYTEA": TokenType.VARBINARY, 911 "VARBINARY": TokenType.VARBINARY, 912 "TIME": TokenType.TIME, 913 "TIMETZ": TokenType.TIMETZ, 914 "TIMESTAMP": TokenType.TIMESTAMP, 915 "TIMESTAMPTZ": TokenType.TIMESTAMPTZ, 916 "TIMESTAMPLTZ": TokenType.TIMESTAMPLTZ, 917 "TIMESTAMP_LTZ": TokenType.TIMESTAMPLTZ, 918 "TIMESTAMPNTZ": TokenType.TIMESTAMPNTZ, 919 "TIMESTAMP_NTZ": TokenType.TIMESTAMPNTZ, 920 "DATE": TokenType.DATE, 921 "DATETIME": TokenType.DATETIME, 922 "INT4RANGE": TokenType.INT4RANGE, 923 "INT4MULTIRANGE": TokenType.INT4MULTIRANGE, 924 "INT8RANGE": TokenType.INT8RANGE, 925 "INT8MULTIRANGE": TokenType.INT8MULTIRANGE, 926 "NUMRANGE": TokenType.NUMRANGE, 927 "NUMMULTIRANGE": TokenType.NUMMULTIRANGE, 928 "TSRANGE": TokenType.TSRANGE, 929 "TSMULTIRANGE": TokenType.TSMULTIRANGE, 930 "TSTZRANGE": TokenType.TSTZRANGE, 931 "TSTZMULTIRANGE": TokenType.TSTZMULTIRANGE, 932 "DATERANGE": TokenType.DATERANGE, 933 "DATEMULTIRANGE": TokenType.DATEMULTIRANGE, 934 "UNIQUE": TokenType.UNIQUE, 935 "VECTOR": TokenType.VECTOR, 936 "STRUCT": TokenType.STRUCT, 937 "SEQUENCE": TokenType.SEQUENCE, 938 "VARIANT": TokenType.VARIANT, 939 "ALTER": TokenType.ALTER, 940 "ANALYZE": TokenType.COMMAND, 941 "CALL": TokenType.COMMAND, 942 "COMMENT": TokenType.COMMENT, 943 "EXPLAIN": TokenType.COMMAND, 944 "GRANT": TokenType.GRANT, 945 "OPTIMIZE": TokenType.COMMAND, 946 "PREPARE": TokenType.COMMAND, 947 "VACUUM": TokenType.COMMAND, 948 "USER-DEFINED": TokenType.USERDEFINED, 949 "FOR VERSION": TokenType.VERSION_SNAPSHOT, 950 "FOR TIMESTAMP": TokenType.TIMESTAMP_SNAPSHOT, 951 } 952 953 WHITE_SPACE: t.Dict[t.Optional[str], TokenType] = { 954 " ": TokenType.SPACE, 955 "\t": TokenType.SPACE, 956 "\n": TokenType.BREAK, 957 "\r": TokenType.BREAK, 958 } 959 960 COMMANDS = { 961 TokenType.COMMAND, 962 TokenType.EXECUTE, 963 TokenType.FETCH, 964 TokenType.SHOW, 965 TokenType.RENAME, 966 } 967 968 COMMAND_PREFIX_TOKENS = {TokenType.SEMICOLON, TokenType.BEGIN} 969 970 # Handle numeric literals like in hive (3L = BIGINT) 971 NUMERIC_LITERALS: t.Dict[str, str] = {} 972 973 COMMENTS = ["--", ("/*", "*/")] 974 975 __slots__ = ( 976 "sql", 977 "size", 978 "tokens", 979 "dialect", 980 "_start", 981 "_current", 982 "_line", 983 "_col", 984 "_comments", 985 "_char", 986 "_end", 987 "_peek", 988 "_prev_token_line", 989 "_rs_dialect_settings", 990 ) 991 992 def __init__(self, dialect: DialectType = None) -> None: 993 from sqlglot.dialects import Dialect 994 995 self.dialect = Dialect.get_or_raise(dialect) 996 997 if USE_RS_TOKENIZER: 998 self._rs_dialect_settings = RsTokenizerDialectSettings( 999 unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES, 1000 identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT, 1001 ) 1002 1003 self.reset() 1004 1005 def reset(self) -> None: 1006 self.sql = "" 1007 self.size = 0 1008 self.tokens: t.List[Token] = [] 1009 self._start = 0 1010 self._current = 0 1011 self._line = 1 1012 self._col = 0 1013 self._comments: t.List[str] = [] 1014 1015 self._char = "" 1016 self._end = False 1017 self._peek = "" 1018 self._prev_token_line = -1 1019 1020 def tokenize(self, sql: str) -> t.List[Token]: 1021 """Returns a list of tokens corresponding to the SQL string `sql`.""" 1022 if USE_RS_TOKENIZER: 1023 return self.tokenize_rs(sql) 1024 1025 self.reset() 1026 self.sql = sql 1027 self.size = len(sql) 1028 1029 try: 1030 self._scan() 1031 except Exception as e: 1032 start = max(self._current - 50, 0) 1033 end = min(self._current + 50, self.size - 1) 1034 context = self.sql[start:end] 1035 raise TokenError(f"Error tokenizing '{context}'") from e 1036 1037 return self.tokens 1038 1039 def _scan(self, until: t.Optional[t.Callable] = None) -> None: 1040 while self.size and not self._end: 1041 current = self._current 1042 1043 # Skip spaces here rather than iteratively calling advance() for performance reasons 1044 while current < self.size: 1045 char = self.sql[current] 1046 1047 if char.isspace() and (char == " " or char == "\t"): 1048 current += 1 1049 else: 1050 break 1051 1052 offset = current - self._current if current > self._current else 1 1053 1054 self._start = current 1055 self._advance(offset) 1056 1057 if not self._char.isspace(): 1058 if self._char.isdigit(): 1059 self._scan_number() 1060 elif self._char in self._IDENTIFIERS: 1061 self._scan_identifier(self._IDENTIFIERS[self._char]) 1062 else: 1063 self._scan_keywords() 1064 1065 if until and until(): 1066 break 1067 1068 if self.tokens and self._comments: 1069 self.tokens[-1].comments.extend(self._comments) 1070 1071 def _chars(self, size: int) -> str: 1072 if size == 1: 1073 return self._char 1074 1075 start = self._current - 1 1076 end = start + size 1077 1078 return self.sql[start:end] if end <= self.size else "" 1079 1080 def _advance(self, i: int = 1, alnum: bool = False) -> None: 1081 if self.WHITE_SPACE.get(self._char) is TokenType.BREAK: 1082 # Ensures we don't count an extra line if we get a \r\n line break sequence 1083 if not (self._char == "\r" and self._peek == "\n"): 1084 self._col = 1 1085 self._line += 1 1086 else: 1087 self._col += i 1088 1089 self._current += i 1090 self._end = self._current >= self.size 1091 self._char = self.sql[self._current - 1] 1092 self._peek = "" if self._end else self.sql[self._current] 1093 1094 if alnum and self._char.isalnum(): 1095 # Here we use local variables instead of attributes for better performance 1096 _col = self._col 1097 _current = self._current 1098 _end = self._end 1099 _peek = self._peek 1100 1101 while _peek.isalnum(): 1102 _col += 1 1103 _current += 1 1104 _end = _current >= self.size 1105 _peek = "" if _end else self.sql[_current] 1106 1107 self._col = _col 1108 self._current = _current 1109 self._end = _end 1110 self._peek = _peek 1111 self._char = self.sql[_current - 1] 1112 1113 @property 1114 def _text(self) -> str: 1115 return self.sql[self._start : self._current] 1116 1117 def _add(self, token_type: TokenType, text: t.Optional[str] = None) -> None: 1118 self._prev_token_line = self._line 1119 1120 if self._comments and token_type == TokenType.SEMICOLON and self.tokens: 1121 self.tokens[-1].comments.extend(self._comments) 1122 self._comments = [] 1123 1124 self.tokens.append( 1125 Token( 1126 token_type, 1127 text=self._text if text is None else text, 1128 line=self._line, 1129 col=self._col, 1130 start=self._start, 1131 end=self._current - 1, 1132 comments=self._comments, 1133 ) 1134 ) 1135 self._comments = [] 1136 1137 # If we have either a semicolon or a begin token before the command's token, we'll parse 1138 # whatever follows the command's token as a string 1139 if ( 1140 token_type in self.COMMANDS 1141 and self._peek != ";" 1142 and (len(self.tokens) == 1 or self.tokens[-2].token_type in self.COMMAND_PREFIX_TOKENS) 1143 ): 1144 start = self._current 1145 tokens = len(self.tokens) 1146 self._scan(lambda: self._peek == ";") 1147 self.tokens = self.tokens[:tokens] 1148 text = self.sql[start : self._current].strip() 1149 if text: 1150 self._add(TokenType.STRING, text) 1151 1152 def _scan_keywords(self) -> None: 1153 size = 0 1154 word = None 1155 chars = self._text 1156 char = chars 1157 prev_space = False 1158 skip = False 1159 trie = self._KEYWORD_TRIE 1160 single_token = char in self.SINGLE_TOKENS 1161 1162 while chars: 1163 if skip: 1164 result = TrieResult.PREFIX 1165 else: 1166 result, trie = in_trie(trie, char.upper()) 1167 1168 if result == TrieResult.FAILED: 1169 break 1170 if result == TrieResult.EXISTS: 1171 word = chars 1172 1173 end = self._current + size 1174 size += 1 1175 1176 if end < self.size: 1177 char = self.sql[end] 1178 single_token = single_token or char in self.SINGLE_TOKENS 1179 is_space = char.isspace() 1180 1181 if not is_space or not prev_space: 1182 if is_space: 1183 char = " " 1184 chars += char 1185 prev_space = is_space 1186 skip = False 1187 else: 1188 skip = True 1189 else: 1190 char = "" 1191 break 1192 1193 if word: 1194 if self._scan_string(word): 1195 return 1196 if self._scan_comment(word): 1197 return 1198 if prev_space or single_token or not char: 1199 self._advance(size - 1) 1200 word = word.upper() 1201 self._add(self.KEYWORDS[word], text=word) 1202 return 1203 1204 if self._char in self.SINGLE_TOKENS: 1205 self._add(self.SINGLE_TOKENS[self._char], text=self._char) 1206 return 1207 1208 self._scan_var() 1209 1210 def _scan_comment(self, comment_start: str) -> bool: 1211 if comment_start not in self._COMMENTS: 1212 return False 1213 1214 comment_start_line = self._line 1215 comment_start_size = len(comment_start) 1216 comment_end = self._COMMENTS[comment_start] 1217 1218 if comment_end: 1219 # Skip the comment's start delimiter 1220 self._advance(comment_start_size) 1221 1222 comment_count = 1 1223 comment_end_size = len(comment_end) 1224 1225 while not self._end: 1226 if self._chars(comment_end_size) == comment_end: 1227 comment_count -= 1 1228 if not comment_count: 1229 break 1230 1231 self._advance(alnum=True) 1232 1233 # Nested comments are allowed by some dialects, e.g. databricks, duckdb, postgres 1234 if ( 1235 self.NESTED_COMMENTS 1236 and not self._end 1237 and self._chars(comment_end_size) == comment_start 1238 ): 1239 self._advance(comment_start_size) 1240 comment_count += 1 1241 1242 self._comments.append(self._text[comment_start_size : -comment_end_size + 1]) 1243 self._advance(comment_end_size - 1) 1244 else: 1245 while not self._end and self.WHITE_SPACE.get(self._peek) is not TokenType.BREAK: 1246 self._advance(alnum=True) 1247 self._comments.append(self._text[comment_start_size:]) 1248 1249 if ( 1250 comment_start == self.HINT_START 1251 and self.tokens 1252 and self.tokens[-1].token_type in self.TOKENS_PRECEDING_HINT 1253 ): 1254 self._add(TokenType.HINT) 1255 1256 # Leading comment is attached to the succeeding token, whilst trailing comment to the preceding. 1257 # Multiple consecutive comments are preserved by appending them to the current comments list. 1258 if comment_start_line == self._prev_token_line: 1259 self.tokens[-1].comments.extend(self._comments) 1260 self._comments = [] 1261 self._prev_token_line = self._line 1262 1263 return True 1264 1265 def _scan_number(self) -> None: 1266 if self._char == "0": 1267 peek = self._peek.upper() 1268 if peek == "B": 1269 return self._scan_bits() if self.BIT_STRINGS else self._add(TokenType.NUMBER) 1270 elif peek == "X": 1271 return self._scan_hex() if self.HEX_STRINGS else self._add(TokenType.NUMBER) 1272 1273 decimal = False 1274 scientific = 0 1275 1276 while True: 1277 if self._peek.isdigit(): 1278 self._advance() 1279 elif self._peek == "." and not decimal: 1280 if self.tokens and self.tokens[-1].token_type == TokenType.PARAMETER: 1281 return self._add(TokenType.NUMBER) 1282 decimal = True 1283 self._advance() 1284 elif self._peek in ("-", "+") and scientific == 1: 1285 scientific += 1 1286 self._advance() 1287 elif self._peek.upper() == "E" and not scientific: 1288 scientific += 1 1289 self._advance() 1290 elif self._peek.isidentifier(): 1291 number_text = self._text 1292 literal = "" 1293 1294 while self._peek.strip() and self._peek not in self.SINGLE_TOKENS: 1295 literal += self._peek 1296 self._advance() 1297 1298 token_type = self.KEYWORDS.get(self.NUMERIC_LITERALS.get(literal.upper(), "")) 1299 1300 if token_type: 1301 self._add(TokenType.NUMBER, number_text) 1302 self._add(TokenType.DCOLON, "::") 1303 return self._add(token_type, literal) 1304 elif self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT: 1305 return self._add(TokenType.VAR) 1306 1307 self._advance(-len(literal)) 1308 return self._add(TokenType.NUMBER, number_text) 1309 else: 1310 return self._add(TokenType.NUMBER) 1311 1312 def _scan_bits(self) -> None: 1313 self._advance() 1314 value = self._extract_value() 1315 try: 1316 # If `value` can't be converted to a binary, fallback to tokenizing it as an identifier 1317 int(value, 2) 1318 self._add(TokenType.BIT_STRING, value[2:]) # Drop the 0b 1319 except ValueError: 1320 self._add(TokenType.IDENTIFIER) 1321 1322 def _scan_hex(self) -> None: 1323 self._advance() 1324 value = self._extract_value() 1325 try: 1326 # If `value` can't be converted to a hex, fallback to tokenizing it as an identifier 1327 int(value, 16) 1328 self._add(TokenType.HEX_STRING, value[2:]) # Drop the 0x 1329 except ValueError: 1330 self._add(TokenType.IDENTIFIER) 1331 1332 def _extract_value(self) -> str: 1333 while True: 1334 char = self._peek.strip() 1335 if char and char not in self.SINGLE_TOKENS: 1336 self._advance(alnum=True) 1337 else: 1338 break 1339 1340 return self._text 1341 1342 def _scan_string(self, start: str) -> bool: 1343 base = None 1344 token_type = TokenType.STRING 1345 1346 if start in self._QUOTES: 1347 end = self._QUOTES[start] 1348 elif start in self._FORMAT_STRINGS: 1349 end, token_type = self._FORMAT_STRINGS[start] 1350 1351 if token_type == TokenType.HEX_STRING: 1352 base = 16 1353 elif token_type == TokenType.BIT_STRING: 1354 base = 2 1355 elif token_type == TokenType.HEREDOC_STRING: 1356 self._advance() 1357 1358 if self._char == end: 1359 tag = "" 1360 else: 1361 tag = self._extract_string( 1362 end, 1363 raw_string=True, 1364 raise_unmatched=not self.HEREDOC_TAG_IS_IDENTIFIER, 1365 ) 1366 1367 if tag and self.HEREDOC_TAG_IS_IDENTIFIER and (self._end or not tag.isidentifier()): 1368 if not self._end: 1369 self._advance(-1) 1370 1371 self._advance(-len(tag)) 1372 self._add(self.HEREDOC_STRING_ALTERNATIVE) 1373 return True 1374 1375 end = f"{start}{tag}{end}" 1376 else: 1377 return False 1378 1379 self._advance(len(start)) 1380 text = self._extract_string(end, raw_string=token_type == TokenType.RAW_STRING) 1381 1382 if base: 1383 try: 1384 int(text, base) 1385 except Exception: 1386 raise TokenError( 1387 f"Numeric string contains invalid characters from {self._line}:{self._start}" 1388 ) 1389 1390 self._add(token_type, text) 1391 return True 1392 1393 def _scan_identifier(self, identifier_end: str) -> None: 1394 self._advance() 1395 text = self._extract_string( 1396 identifier_end, escapes=self._IDENTIFIER_ESCAPES | {identifier_end} 1397 ) 1398 self._add(TokenType.IDENTIFIER, text) 1399 1400 def _scan_var(self) -> None: 1401 while True: 1402 char = self._peek.strip() 1403 if char and (char in self.VAR_SINGLE_TOKENS or char not in self.SINGLE_TOKENS): 1404 self._advance(alnum=True) 1405 else: 1406 break 1407 1408 self._add( 1409 TokenType.VAR 1410 if self.tokens and self.tokens[-1].token_type == TokenType.PARAMETER 1411 else self.KEYWORDS.get(self._text.upper(), TokenType.VAR) 1412 ) 1413 1414 def _extract_string( 1415 self, 1416 delimiter: str, 1417 escapes: t.Optional[t.Set[str]] = None, 1418 raw_string: bool = False, 1419 raise_unmatched: bool = True, 1420 ) -> str: 1421 text = "" 1422 delim_size = len(delimiter) 1423 escapes = self._STRING_ESCAPES if escapes is None else escapes 1424 1425 while True: 1426 if ( 1427 not raw_string 1428 and self.dialect.UNESCAPED_SEQUENCES 1429 and self._peek 1430 and self._char in self.STRING_ESCAPES 1431 ): 1432 unescaped_sequence = self.dialect.UNESCAPED_SEQUENCES.get(self._char + self._peek) 1433 if unescaped_sequence: 1434 self._advance(2) 1435 text += unescaped_sequence 1436 continue 1437 if ( 1438 (self.STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS or not raw_string) 1439 and self._char in escapes 1440 and (self._peek == delimiter or self._peek in escapes) 1441 and (self._char not in self._QUOTES or self._char == self._peek) 1442 ): 1443 if self._peek == delimiter: 1444 text += self._peek 1445 else: 1446 text += self._char + self._peek 1447 1448 if self._current + 1 < self.size: 1449 self._advance(2) 1450 else: 1451 raise TokenError(f"Missing {delimiter} from {self._line}:{self._current}") 1452 else: 1453 if self._chars(delim_size) == delimiter: 1454 if delim_size > 1: 1455 self._advance(delim_size - 1) 1456 break 1457 1458 if self._end: 1459 if not raise_unmatched: 1460 return text + self._char 1461 1462 raise TokenError(f"Missing {delimiter} from {self._line}:{self._start}") 1463 1464 current = self._current - 1 1465 self._advance(alnum=True) 1466 text += self.sql[current : self._current - 1] 1467 1468 return text 1469 1470 def tokenize_rs(self, sql: str) -> t.List[Token]: 1471 if not self._RS_TOKENIZER: 1472 raise SqlglotError("Rust tokenizer is not available") 1473 1474 try: 1475 tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings) 1476 for token in tokens: 1477 token.token_type = _ALL_TOKEN_TYPES[token.token_type_index] 1478 return tokens 1479 except Exception as e: 1480 raise TokenError(str(e))
Tokenizer( dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None)
992 def __init__(self, dialect: DialectType = None) -> None: 993 from sqlglot.dialects import Dialect 994 995 self.dialect = Dialect.get_or_raise(dialect) 996 997 if USE_RS_TOKENIZER: 998 self._rs_dialect_settings = RsTokenizerDialectSettings( 999 unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES, 1000 identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT, 1001 ) 1002 1003 self.reset()
SINGLE_TOKENS =
{'(': <TokenType.L_PAREN: 'L_PAREN'>, ')': <TokenType.R_PAREN: 'R_PAREN'>, '[': <TokenType.L_BRACKET: 'L_BRACKET'>, ']': <TokenType.R_BRACKET: 'R_BRACKET'>, '{': <TokenType.L_BRACE: 'L_BRACE'>, '}': <TokenType.R_BRACE: 'R_BRACE'>, '&': <TokenType.AMP: 'AMP'>, '^': <TokenType.CARET: 'CARET'>, ':': <TokenType.COLON: 'COLON'>, ',': <TokenType.COMMA: 'COMMA'>, '.': <TokenType.DOT: 'DOT'>, '-': <TokenType.DASH: 'DASH'>, '=': <TokenType.EQ: 'EQ'>, '>': <TokenType.GT: 'GT'>, '<': <TokenType.LT: 'LT'>, '%': <TokenType.MOD: 'MOD'>, '!': <TokenType.NOT: 'NOT'>, '|': <TokenType.PIPE: 'PIPE'>, '+': <TokenType.PLUS: 'PLUS'>, ';': <TokenType.SEMICOLON: 'SEMICOLON'>, '/': <TokenType.SLASH: 'SLASH'>, '\\': <TokenType.BACKSLASH: 'BACKSLASH'>, '*': <TokenType.STAR: 'STAR'>, '~': <TokenType.TILDA: 'TILDA'>, '?': <TokenType.PLACEHOLDER: 'PLACEHOLDER'>, '@': <TokenType.PARAMETER: 'PARAMETER'>, '#': <TokenType.HASH: 'HASH'>, "'": <TokenType.UNKNOWN: 'UNKNOWN'>, '`': <TokenType.UNKNOWN: 'UNKNOWN'>, '"': <TokenType.UNKNOWN: 'UNKNOWN'>}
HEREDOC_STRING_ALTERNATIVE =
<TokenType.VAR: 'VAR'>
TOKENS_PRECEDING_HINT =
{<TokenType.DELETE: 'DELETE'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.INSERT: 'INSERT'>, <TokenType.SELECT: 'SELECT'>}
KEYWORDS: Dict[str, TokenType] =
{'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, ':=': <TokenType.COLON_EQ: 'COLON_EQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, '??': <TokenType.DQMARK: 'DQMARK'>, '~~~': <TokenType.GLOB: 'GLOB'>, '~~': <TokenType.LIKE: 'LIKE'>, '~~*': <TokenType.ILIKE: 'ILIKE'>, '~*': <TokenType.IRLIKE: 'IRLIKE'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'COPY': <TokenType.COPY: 'COPY'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ENUM': <TokenType.ENUM: 'ENUM'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'KILL': <TokenType.KILL: 'KILL'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'RENAME': <TokenType.RENAME: 'RENAME'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'START WITH': <TokenType.START_WITH: 'START_WITH'>, 'STRAIGHT_JOIN': <TokenType.STRAIGHT_JOIN: 'STRAIGHT_JOIN'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'TRUNCATE': <TokenType.TRUNCATE: 'TRUNCATE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'MEDIUMINT': <TokenType.MEDIUMINT: 'MEDIUMINT'>, 'INT1': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'INT16': <TokenType.SMALLINT: 'SMALLINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT128': <TokenType.INT128: 'INT128'>, 'HUGEINT': <TokenType.INT128: 'INT128'>, 'UHUGEINT': <TokenType.UINT128: 'UINT128'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'INT32': <TokenType.INT: 'INT'>, 'INT64': <TokenType.BIGINT: 'BIGINT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.TINYINT: 'TINYINT'>, 'UINT': <TokenType.UINT: 'UINT'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL32': <TokenType.DECIMAL32: 'DECIMAL32'>, 'DECIMAL64': <TokenType.DECIMAL64: 'DECIMAL64'>, 'DECIMAL128': <TokenType.DECIMAL128: 'DECIMAL128'>, 'DECIMAL256': <TokenType.DECIMAL256: 'DECIMAL256'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'LIST': <TokenType.LIST: 'LIST'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'JSONB': <TokenType.JSONB: 'JSONB'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'BPCHAR': <TokenType.BPCHAR: 'BPCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMP_LTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMPNTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'TIMESTAMP_NTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'VECTOR': <TokenType.VECTOR: 'VECTOR'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'SEQUENCE': <TokenType.SEQUENCE: 'SEQUENCE'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.GRANT: 'GRANT'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>}
WHITE_SPACE: Dict[Optional[str], TokenType] =
{' ': <TokenType.SPACE: 'SPACE'>, '\t': <TokenType.SPACE: 'SPACE'>, '\n': <TokenType.BREAK: 'BREAK'>, '\r': <TokenType.BREAK: 'BREAK'>}
COMMANDS =
{<TokenType.EXECUTE: 'EXECUTE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.FETCH: 'FETCH'>, <TokenType.RENAME: 'RENAME'>, <TokenType.SHOW: 'SHOW'>}
COMMAND_PREFIX_TOKENS =
{<TokenType.SEMICOLON: 'SEMICOLON'>, <TokenType.BEGIN: 'BEGIN'>}
def
reset(self) -> None:
1005 def reset(self) -> None: 1006 self.sql = "" 1007 self.size = 0 1008 self.tokens: t.List[Token] = [] 1009 self._start = 0 1010 self._current = 0 1011 self._line = 1 1012 self._col = 0 1013 self._comments: t.List[str] = [] 1014 1015 self._char = "" 1016 self._end = False 1017 self._peek = "" 1018 self._prev_token_line = -1
1020 def tokenize(self, sql: str) -> t.List[Token]: 1021 """Returns a list of tokens corresponding to the SQL string `sql`.""" 1022 if USE_RS_TOKENIZER: 1023 return self.tokenize_rs(sql) 1024 1025 self.reset() 1026 self.sql = sql 1027 self.size = len(sql) 1028 1029 try: 1030 self._scan() 1031 except Exception as e: 1032 start = max(self._current - 50, 0) 1033 end = min(self._current + 50, self.size - 1) 1034 context = self.sql[start:end] 1035 raise TokenError(f"Error tokenizing '{context}'") from e 1036 1037 return self.tokens
Returns a list of tokens corresponding to the SQL string sql
.
1470 def tokenize_rs(self, sql: str) -> t.List[Token]: 1471 if not self._RS_TOKENIZER: 1472 raise SqlglotError("Rust tokenizer is not available") 1473 1474 try: 1475 tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings) 1476 for token in tokens: 1477 token.token_type = _ALL_TOKEN_TYPES[token.token_type_index] 1478 return tokens 1479 except Exception as e: 1480 raise TokenError(str(e))