Edit on GitHub

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

Returns a NUMBER token with number as its text.

@classmethod
def string(cls, string: str) -> Token:
431    @classmethod
432    def string(cls, string: str) -> Token:
433        """Returns a STRING token with `string` as its text."""
434        return cls(TokenType.STRING, string)

Returns a STRING token with string as its text.

@classmethod
def identifier(cls, identifier: str) -> Token:
436    @classmethod
437    def identifier(cls, identifier: str) -> Token:
438        """Returns an IDENTIFIER token with `identifier` as its text."""
439        return cls(TokenType.IDENTIFIER, identifier)

Returns an IDENTIFIER token with identifier as its text.

@classmethod
def var(cls, var: str) -> Token:
441    @classmethod
442    def var(cls, var: str) -> Token:
443        """Returns an VAR token with `var` as its text."""
444        return cls(TokenType.VAR, var)

Returns an VAR token with var as its text.

token_type
text
line
col
start
end
comments
class Tokenizer:
 587class Tokenizer(metaclass=_Tokenizer):
 588    SINGLE_TOKENS = {
 589        "(": TokenType.L_PAREN,
 590        ")": TokenType.R_PAREN,
 591        "[": TokenType.L_BRACKET,
 592        "]": TokenType.R_BRACKET,
 593        "{": TokenType.L_BRACE,
 594        "}": TokenType.R_BRACE,
 595        "&": TokenType.AMP,
 596        "^": TokenType.CARET,
 597        ":": TokenType.COLON,
 598        ",": TokenType.COMMA,
 599        ".": TokenType.DOT,
 600        "-": TokenType.DASH,
 601        "=": TokenType.EQ,
 602        ">": TokenType.GT,
 603        "<": TokenType.LT,
 604        "%": TokenType.MOD,
 605        "!": TokenType.NOT,
 606        "|": TokenType.PIPE,
 607        "+": TokenType.PLUS,
 608        ";": TokenType.SEMICOLON,
 609        "/": TokenType.SLASH,
 610        "\\": TokenType.BACKSLASH,
 611        "*": TokenType.STAR,
 612        "~": TokenType.TILDA,
 613        "?": TokenType.PLACEHOLDER,
 614        "@": TokenType.PARAMETER,
 615        "#": TokenType.HASH,
 616        # Used for breaking a var like x'y' but nothing else the token type doesn't matter
 617        "'": TokenType.UNKNOWN,
 618        "`": TokenType.UNKNOWN,
 619        '"': TokenType.UNKNOWN,
 620    }
 621
 622    BIT_STRINGS: t.List[str | t.Tuple[str, str]] = []
 623    BYTE_STRINGS: t.List[str | t.Tuple[str, str]] = []
 624    HEX_STRINGS: t.List[str | t.Tuple[str, str]] = []
 625    RAW_STRINGS: t.List[str | t.Tuple[str, str]] = []
 626    HEREDOC_STRINGS: t.List[str | t.Tuple[str, str]] = []
 627    UNICODE_STRINGS: t.List[str | t.Tuple[str, str]] = []
 628    IDENTIFIERS: t.List[str | t.Tuple[str, str]] = ['"']
 629    QUOTES: t.List[t.Tuple[str, str] | str] = ["'"]
 630    STRING_ESCAPES = ["'"]
 631    VAR_SINGLE_TOKENS: t.Set[str] = set()
 632
 633    # The strings in this list can always be used as escapes, regardless of the surrounding
 634    # identifier delimiters. By default, the closing delimiter is assumed to also act as an
 635    # identifier escape, e.g. if we use double-quotes, then they also act as escapes: "x"""
 636    IDENTIFIER_ESCAPES: t.List[str] = []
 637
 638    # Whether the heredoc tags follow the same lexical rules as unquoted identifiers
 639    HEREDOC_TAG_IS_IDENTIFIER = False
 640
 641    # Token that we'll generate as a fallback if the heredoc prefix doesn't correspond to a heredoc
 642    HEREDOC_STRING_ALTERNATIVE = TokenType.VAR
 643
 644    # Whether string escape characters function as such when placed within raw strings
 645    STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS = True
 646
 647    NESTED_COMMENTS = True
 648
 649    HINT_START = "/*+"
 650
 651    TOKENS_PRECEDING_HINT = {TokenType.SELECT, TokenType.INSERT, TokenType.UPDATE, TokenType.DELETE}
 652
 653    # Autofilled
 654    _COMMENTS: t.Dict[str, str] = {}
 655    _FORMAT_STRINGS: t.Dict[str, t.Tuple[str, TokenType]] = {}
 656    _IDENTIFIERS: t.Dict[str, str] = {}
 657    _IDENTIFIER_ESCAPES: t.Set[str] = set()
 658    _QUOTES: t.Dict[str, str] = {}
 659    _STRING_ESCAPES: t.Set[str] = set()
 660    _KEYWORD_TRIE: t.Dict = {}
 661    _RS_TOKENIZER: t.Optional[t.Any] = None
 662
 663    KEYWORDS: t.Dict[str, TokenType] = {
 664        **{f"{{%{postfix}": TokenType.BLOCK_START for postfix in ("", "+", "-")},
 665        **{f"{prefix}%}}": TokenType.BLOCK_END for prefix in ("", "+", "-")},
 666        **{f"{{{{{postfix}": TokenType.BLOCK_START for postfix in ("+", "-")},
 667        **{f"{prefix}}}}}": TokenType.BLOCK_END for prefix in ("+", "-")},
 668        HINT_START: TokenType.HINT,
 669        "==": TokenType.EQ,
 670        "::": TokenType.DCOLON,
 671        "||": TokenType.DPIPE,
 672        ">=": TokenType.GTE,
 673        "<=": TokenType.LTE,
 674        "<>": TokenType.NEQ,
 675        "!=": TokenType.NEQ,
 676        ":=": TokenType.COLON_EQ,
 677        "<=>": TokenType.NULLSAFE_EQ,
 678        "->": TokenType.ARROW,
 679        "->>": TokenType.DARROW,
 680        "=>": TokenType.FARROW,
 681        "#>": TokenType.HASH_ARROW,
 682        "#>>": TokenType.DHASH_ARROW,
 683        "<->": TokenType.LR_ARROW,
 684        "&&": TokenType.DAMP,
 685        "??": TokenType.DQMARK,
 686        "~~~": TokenType.GLOB,
 687        "~~": TokenType.LIKE,
 688        "~~*": TokenType.ILIKE,
 689        "~*": TokenType.IRLIKE,
 690        "ALL": TokenType.ALL,
 691        "ALWAYS": TokenType.ALWAYS,
 692        "AND": TokenType.AND,
 693        "ANTI": TokenType.ANTI,
 694        "ANY": TokenType.ANY,
 695        "ASC": TokenType.ASC,
 696        "AS": TokenType.ALIAS,
 697        "ASOF": TokenType.ASOF,
 698        "AUTOINCREMENT": TokenType.AUTO_INCREMENT,
 699        "AUTO_INCREMENT": TokenType.AUTO_INCREMENT,
 700        "BEGIN": TokenType.BEGIN,
 701        "BETWEEN": TokenType.BETWEEN,
 702        "CACHE": TokenType.CACHE,
 703        "UNCACHE": TokenType.UNCACHE,
 704        "CASE": TokenType.CASE,
 705        "CHARACTER SET": TokenType.CHARACTER_SET,
 706        "CLUSTER BY": TokenType.CLUSTER_BY,
 707        "COLLATE": TokenType.COLLATE,
 708        "COLUMN": TokenType.COLUMN,
 709        "COMMIT": TokenType.COMMIT,
 710        "CONNECT BY": TokenType.CONNECT_BY,
 711        "CONSTRAINT": TokenType.CONSTRAINT,
 712        "COPY": TokenType.COPY,
 713        "CREATE": TokenType.CREATE,
 714        "CROSS": TokenType.CROSS,
 715        "CUBE": TokenType.CUBE,
 716        "CURRENT_DATE": TokenType.CURRENT_DATE,
 717        "CURRENT_TIME": TokenType.CURRENT_TIME,
 718        "CURRENT_TIMESTAMP": TokenType.CURRENT_TIMESTAMP,
 719        "CURRENT_USER": TokenType.CURRENT_USER,
 720        "DATABASE": TokenType.DATABASE,
 721        "DEFAULT": TokenType.DEFAULT,
 722        "DELETE": TokenType.DELETE,
 723        "DESC": TokenType.DESC,
 724        "DESCRIBE": TokenType.DESCRIBE,
 725        "DISTINCT": TokenType.DISTINCT,
 726        "DISTRIBUTE BY": TokenType.DISTRIBUTE_BY,
 727        "DIV": TokenType.DIV,
 728        "DROP": TokenType.DROP,
 729        "ELSE": TokenType.ELSE,
 730        "END": TokenType.END,
 731        "ENUM": TokenType.ENUM,
 732        "ESCAPE": TokenType.ESCAPE,
 733        "EXCEPT": TokenType.EXCEPT,
 734        "EXECUTE": TokenType.EXECUTE,
 735        "EXISTS": TokenType.EXISTS,
 736        "FALSE": TokenType.FALSE,
 737        "FETCH": TokenType.FETCH,
 738        "FILTER": TokenType.FILTER,
 739        "FIRST": TokenType.FIRST,
 740        "FULL": TokenType.FULL,
 741        "FUNCTION": TokenType.FUNCTION,
 742        "FOR": TokenType.FOR,
 743        "FOREIGN KEY": TokenType.FOREIGN_KEY,
 744        "FORMAT": TokenType.FORMAT,
 745        "FROM": TokenType.FROM,
 746        "GEOGRAPHY": TokenType.GEOGRAPHY,
 747        "GEOMETRY": TokenType.GEOMETRY,
 748        "GLOB": TokenType.GLOB,
 749        "GROUP BY": TokenType.GROUP_BY,
 750        "GROUPING SETS": TokenType.GROUPING_SETS,
 751        "HAVING": TokenType.HAVING,
 752        "ILIKE": TokenType.ILIKE,
 753        "IN": TokenType.IN,
 754        "INDEX": TokenType.INDEX,
 755        "INET": TokenType.INET,
 756        "INNER": TokenType.INNER,
 757        "INSERT": TokenType.INSERT,
 758        "INTERVAL": TokenType.INTERVAL,
 759        "INTERSECT": TokenType.INTERSECT,
 760        "INTO": TokenType.INTO,
 761        "IS": TokenType.IS,
 762        "ISNULL": TokenType.ISNULL,
 763        "JOIN": TokenType.JOIN,
 764        "KEEP": TokenType.KEEP,
 765        "KILL": TokenType.KILL,
 766        "LATERAL": TokenType.LATERAL,
 767        "LEFT": TokenType.LEFT,
 768        "LIKE": TokenType.LIKE,
 769        "LIMIT": TokenType.LIMIT,
 770        "LOAD": TokenType.LOAD,
 771        "LOCK": TokenType.LOCK,
 772        "MERGE": TokenType.MERGE,
 773        "NAMESPACE": TokenType.NAMESPACE,
 774        "NATURAL": TokenType.NATURAL,
 775        "NEXT": TokenType.NEXT,
 776        "NOT": TokenType.NOT,
 777        "NOTNULL": TokenType.NOTNULL,
 778        "NULL": TokenType.NULL,
 779        "OBJECT": TokenType.OBJECT,
 780        "OFFSET": TokenType.OFFSET,
 781        "ON": TokenType.ON,
 782        "OR": TokenType.OR,
 783        "XOR": TokenType.XOR,
 784        "ORDER BY": TokenType.ORDER_BY,
 785        "ORDINALITY": TokenType.ORDINALITY,
 786        "OUTER": TokenType.OUTER,
 787        "OVER": TokenType.OVER,
 788        "OVERLAPS": TokenType.OVERLAPS,
 789        "OVERWRITE": TokenType.OVERWRITE,
 790        "PARTITION": TokenType.PARTITION,
 791        "PARTITION BY": TokenType.PARTITION_BY,
 792        "PARTITIONED BY": TokenType.PARTITION_BY,
 793        "PARTITIONED_BY": TokenType.PARTITION_BY,
 794        "PERCENT": TokenType.PERCENT,
 795        "PIVOT": TokenType.PIVOT,
 796        "PRAGMA": TokenType.PRAGMA,
 797        "PRIMARY KEY": TokenType.PRIMARY_KEY,
 798        "PROCEDURE": TokenType.PROCEDURE,
 799        "QUALIFY": TokenType.QUALIFY,
 800        "RANGE": TokenType.RANGE,
 801        "RECURSIVE": TokenType.RECURSIVE,
 802        "REGEXP": TokenType.RLIKE,
 803        "RENAME": TokenType.RENAME,
 804        "REPLACE": TokenType.REPLACE,
 805        "RETURNING": TokenType.RETURNING,
 806        "REFERENCES": TokenType.REFERENCES,
 807        "RIGHT": TokenType.RIGHT,
 808        "RLIKE": TokenType.RLIKE,
 809        "ROLLBACK": TokenType.ROLLBACK,
 810        "ROLLUP": TokenType.ROLLUP,
 811        "ROW": TokenType.ROW,
 812        "ROWS": TokenType.ROWS,
 813        "SCHEMA": TokenType.SCHEMA,
 814        "SELECT": TokenType.SELECT,
 815        "SEMI": TokenType.SEMI,
 816        "SET": TokenType.SET,
 817        "SETTINGS": TokenType.SETTINGS,
 818        "SHOW": TokenType.SHOW,
 819        "SIMILAR TO": TokenType.SIMILAR_TO,
 820        "SOME": TokenType.SOME,
 821        "SORT BY": TokenType.SORT_BY,
 822        "START WITH": TokenType.START_WITH,
 823        "STRAIGHT_JOIN": TokenType.STRAIGHT_JOIN,
 824        "TABLE": TokenType.TABLE,
 825        "TABLESAMPLE": TokenType.TABLE_SAMPLE,
 826        "TEMP": TokenType.TEMPORARY,
 827        "TEMPORARY": TokenType.TEMPORARY,
 828        "THEN": TokenType.THEN,
 829        "TRUE": TokenType.TRUE,
 830        "TRUNCATE": TokenType.TRUNCATE,
 831        "UNION": TokenType.UNION,
 832        "UNKNOWN": TokenType.UNKNOWN,
 833        "UNNEST": TokenType.UNNEST,
 834        "UNPIVOT": TokenType.UNPIVOT,
 835        "UPDATE": TokenType.UPDATE,
 836        "USE": TokenType.USE,
 837        "USING": TokenType.USING,
 838        "UUID": TokenType.UUID,
 839        "VALUES": TokenType.VALUES,
 840        "VIEW": TokenType.VIEW,
 841        "VOLATILE": TokenType.VOLATILE,
 842        "WHEN": TokenType.WHEN,
 843        "WHERE": TokenType.WHERE,
 844        "WINDOW": TokenType.WINDOW,
 845        "WITH": TokenType.WITH,
 846        "APPLY": TokenType.APPLY,
 847        "ARRAY": TokenType.ARRAY,
 848        "BIT": TokenType.BIT,
 849        "BOOL": TokenType.BOOLEAN,
 850        "BOOLEAN": TokenType.BOOLEAN,
 851        "BYTE": TokenType.TINYINT,
 852        "MEDIUMINT": TokenType.MEDIUMINT,
 853        "INT1": TokenType.TINYINT,
 854        "TINYINT": TokenType.TINYINT,
 855        "INT16": TokenType.SMALLINT,
 856        "SHORT": TokenType.SMALLINT,
 857        "SMALLINT": TokenType.SMALLINT,
 858        "INT128": TokenType.INT128,
 859        "HUGEINT": TokenType.INT128,
 860        "UHUGEINT": TokenType.UINT128,
 861        "INT2": TokenType.SMALLINT,
 862        "INTEGER": TokenType.INT,
 863        "INT": TokenType.INT,
 864        "INT4": TokenType.INT,
 865        "INT32": TokenType.INT,
 866        "INT64": TokenType.BIGINT,
 867        "LONG": TokenType.BIGINT,
 868        "BIGINT": TokenType.BIGINT,
 869        "INT8": TokenType.TINYINT,
 870        "UINT": TokenType.UINT,
 871        "DEC": TokenType.DECIMAL,
 872        "DECIMAL": TokenType.DECIMAL,
 873        "DECIMAL32": TokenType.DECIMAL32,
 874        "DECIMAL64": TokenType.DECIMAL64,
 875        "DECIMAL128": TokenType.DECIMAL128,
 876        "DECIMAL256": TokenType.DECIMAL256,
 877        "BIGDECIMAL": TokenType.BIGDECIMAL,
 878        "BIGNUMERIC": TokenType.BIGDECIMAL,
 879        "LIST": TokenType.LIST,
 880        "MAP": TokenType.MAP,
 881        "NULLABLE": TokenType.NULLABLE,
 882        "NUMBER": TokenType.DECIMAL,
 883        "NUMERIC": TokenType.DECIMAL,
 884        "FIXED": TokenType.DECIMAL,
 885        "REAL": TokenType.FLOAT,
 886        "FLOAT": TokenType.FLOAT,
 887        "FLOAT4": TokenType.FLOAT,
 888        "FLOAT8": TokenType.DOUBLE,
 889        "DOUBLE": TokenType.DOUBLE,
 890        "DOUBLE PRECISION": TokenType.DOUBLE,
 891        "JSON": TokenType.JSON,
 892        "JSONB": TokenType.JSONB,
 893        "CHAR": TokenType.CHAR,
 894        "CHARACTER": TokenType.CHAR,
 895        "NCHAR": TokenType.NCHAR,
 896        "VARCHAR": TokenType.VARCHAR,
 897        "VARCHAR2": TokenType.VARCHAR,
 898        "NVARCHAR": TokenType.NVARCHAR,
 899        "NVARCHAR2": TokenType.NVARCHAR,
 900        "BPCHAR": TokenType.BPCHAR,
 901        "STR": TokenType.TEXT,
 902        "STRING": TokenType.TEXT,
 903        "TEXT": TokenType.TEXT,
 904        "LONGTEXT": TokenType.LONGTEXT,
 905        "MEDIUMTEXT": TokenType.MEDIUMTEXT,
 906        "TINYTEXT": TokenType.TINYTEXT,
 907        "CLOB": TokenType.TEXT,
 908        "LONGVARCHAR": TokenType.TEXT,
 909        "BINARY": TokenType.BINARY,
 910        "BLOB": TokenType.VARBINARY,
 911        "LONGBLOB": TokenType.LONGBLOB,
 912        "MEDIUMBLOB": TokenType.MEDIUMBLOB,
 913        "TINYBLOB": TokenType.TINYBLOB,
 914        "BYTEA": TokenType.VARBINARY,
 915        "VARBINARY": TokenType.VARBINARY,
 916        "TIME": TokenType.TIME,
 917        "TIMETZ": TokenType.TIMETZ,
 918        "TIMESTAMP": TokenType.TIMESTAMP,
 919        "TIMESTAMPTZ": TokenType.TIMESTAMPTZ,
 920        "TIMESTAMPLTZ": TokenType.TIMESTAMPLTZ,
 921        "TIMESTAMP_LTZ": TokenType.TIMESTAMPLTZ,
 922        "TIMESTAMPNTZ": TokenType.TIMESTAMPNTZ,
 923        "TIMESTAMP_NTZ": TokenType.TIMESTAMPNTZ,
 924        "DATE": TokenType.DATE,
 925        "DATETIME": TokenType.DATETIME,
 926        "INT4RANGE": TokenType.INT4RANGE,
 927        "INT4MULTIRANGE": TokenType.INT4MULTIRANGE,
 928        "INT8RANGE": TokenType.INT8RANGE,
 929        "INT8MULTIRANGE": TokenType.INT8MULTIRANGE,
 930        "NUMRANGE": TokenType.NUMRANGE,
 931        "NUMMULTIRANGE": TokenType.NUMMULTIRANGE,
 932        "TSRANGE": TokenType.TSRANGE,
 933        "TSMULTIRANGE": TokenType.TSMULTIRANGE,
 934        "TSTZRANGE": TokenType.TSTZRANGE,
 935        "TSTZMULTIRANGE": TokenType.TSTZMULTIRANGE,
 936        "DATERANGE": TokenType.DATERANGE,
 937        "DATEMULTIRANGE": TokenType.DATEMULTIRANGE,
 938        "UNIQUE": TokenType.UNIQUE,
 939        "VECTOR": TokenType.VECTOR,
 940        "STRUCT": TokenType.STRUCT,
 941        "SEQUENCE": TokenType.SEQUENCE,
 942        "VARIANT": TokenType.VARIANT,
 943        "ALTER": TokenType.ALTER,
 944        "ANALYZE": TokenType.ANALYZE,
 945        "CALL": TokenType.COMMAND,
 946        "COMMENT": TokenType.COMMENT,
 947        "EXPLAIN": TokenType.COMMAND,
 948        "GRANT": TokenType.GRANT,
 949        "OPTIMIZE": TokenType.COMMAND,
 950        "PREPARE": TokenType.COMMAND,
 951        "VACUUM": TokenType.COMMAND,
 952        "USER-DEFINED": TokenType.USERDEFINED,
 953        "FOR VERSION": TokenType.VERSION_SNAPSHOT,
 954        "FOR TIMESTAMP": TokenType.TIMESTAMP_SNAPSHOT,
 955    }
 956
 957    WHITE_SPACE: t.Dict[t.Optional[str], TokenType] = {
 958        " ": TokenType.SPACE,
 959        "\t": TokenType.SPACE,
 960        "\n": TokenType.BREAK,
 961        "\r": TokenType.BREAK,
 962    }
 963
 964    COMMANDS = {
 965        TokenType.COMMAND,
 966        TokenType.EXECUTE,
 967        TokenType.FETCH,
 968        TokenType.SHOW,
 969        TokenType.RENAME,
 970    }
 971
 972    COMMAND_PREFIX_TOKENS = {TokenType.SEMICOLON, TokenType.BEGIN}
 973
 974    # Handle numeric literals like in hive (3L = BIGINT)
 975    NUMERIC_LITERALS: t.Dict[str, str] = {}
 976
 977    COMMENTS = ["--", ("/*", "*/")]
 978
 979    __slots__ = (
 980        "sql",
 981        "size",
 982        "tokens",
 983        "dialect",
 984        "use_rs_tokenizer",
 985        "_start",
 986        "_current",
 987        "_line",
 988        "_col",
 989        "_comments",
 990        "_char",
 991        "_end",
 992        "_peek",
 993        "_prev_token_line",
 994        "_rs_dialect_settings",
 995    )
 996
 997    def __init__(
 998        self, dialect: DialectType = None, use_rs_tokenizer: t.Optional[bool] = None
 999    ) -> None:
1000        from sqlglot.dialects import Dialect
1001
1002        self.dialect = Dialect.get_or_raise(dialect)
1003
1004        # initialize `use_rs_tokenizer`, and allow it to be overwritten per Tokenizer instance
1005        self.use_rs_tokenizer = (
1006            use_rs_tokenizer if use_rs_tokenizer is not None else USE_RS_TOKENIZER
1007        )
1008
1009        if self.use_rs_tokenizer:
1010            self._rs_dialect_settings = RsTokenizerDialectSettings(
1011                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
1012                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
1013                numbers_can_be_underscore_separated=self.dialect.NUMBERS_CAN_BE_UNDERSCORE_SEPARATED,
1014            )
1015
1016        self.reset()
1017
1018    def reset(self) -> None:
1019        self.sql = ""
1020        self.size = 0
1021        self.tokens: t.List[Token] = []
1022        self._start = 0
1023        self._current = 0
1024        self._line = 1
1025        self._col = 0
1026        self._comments: t.List[str] = []
1027
1028        self._char = ""
1029        self._end = False
1030        self._peek = ""
1031        self._prev_token_line = -1
1032
1033    def tokenize(self, sql: str) -> t.List[Token]:
1034        """Returns a list of tokens corresponding to the SQL string `sql`."""
1035        if self.use_rs_tokenizer:
1036            return self.tokenize_rs(sql)
1037
1038        self.reset()
1039        self.sql = sql
1040        self.size = len(sql)
1041
1042        try:
1043            self._scan()
1044        except Exception as e:
1045            start = max(self._current - 50, 0)
1046            end = min(self._current + 50, self.size - 1)
1047            context = self.sql[start:end]
1048            raise TokenError(f"Error tokenizing '{context}'") from e
1049
1050        return self.tokens
1051
1052    def _scan(self, until: t.Optional[t.Callable] = None) -> None:
1053        while self.size and not self._end:
1054            current = self._current
1055
1056            # Skip spaces here rather than iteratively calling advance() for performance reasons
1057            while current < self.size:
1058                char = self.sql[current]
1059
1060                if char.isspace() and (char == " " or char == "\t"):
1061                    current += 1
1062                else:
1063                    break
1064
1065            offset = current - self._current if current > self._current else 1
1066
1067            self._start = current
1068            self._advance(offset)
1069
1070            if not self._char.isspace():
1071                if self._char.isdigit():
1072                    self._scan_number()
1073                elif self._char in self._IDENTIFIERS:
1074                    self._scan_identifier(self._IDENTIFIERS[self._char])
1075                else:
1076                    self._scan_keywords()
1077
1078            if until and until():
1079                break
1080
1081        if self.tokens and self._comments:
1082            self.tokens[-1].comments.extend(self._comments)
1083
1084    def _chars(self, size: int) -> str:
1085        if size == 1:
1086            return self._char
1087
1088        start = self._current - 1
1089        end = start + size
1090
1091        return self.sql[start:end] if end <= self.size else ""
1092
1093    def _advance(self, i: int = 1, alnum: bool = False) -> None:
1094        if self.WHITE_SPACE.get(self._char) is TokenType.BREAK:
1095            # Ensures we don't count an extra line if we get a \r\n line break sequence
1096            if not (self._char == "\r" and self._peek == "\n"):
1097                self._col = 1
1098                self._line += 1
1099        else:
1100            self._col += i
1101
1102        self._current += i
1103        self._end = self._current >= self.size
1104        self._char = self.sql[self._current - 1]
1105        self._peek = "" if self._end else self.sql[self._current]
1106
1107        if alnum and self._char.isalnum():
1108            # Here we use local variables instead of attributes for better performance
1109            _col = self._col
1110            _current = self._current
1111            _end = self._end
1112            _peek = self._peek
1113
1114            while _peek.isalnum():
1115                _col += 1
1116                _current += 1
1117                _end = _current >= self.size
1118                _peek = "" if _end else self.sql[_current]
1119
1120            self._col = _col
1121            self._current = _current
1122            self._end = _end
1123            self._peek = _peek
1124            self._char = self.sql[_current - 1]
1125
1126    @property
1127    def _text(self) -> str:
1128        return self.sql[self._start : self._current]
1129
1130    def _add(self, token_type: TokenType, text: t.Optional[str] = None) -> None:
1131        self._prev_token_line = self._line
1132
1133        if self._comments and token_type == TokenType.SEMICOLON and self.tokens:
1134            self.tokens[-1].comments.extend(self._comments)
1135            self._comments = []
1136
1137        self.tokens.append(
1138            Token(
1139                token_type,
1140                text=self._text if text is None else text,
1141                line=self._line,
1142                col=self._col,
1143                start=self._start,
1144                end=self._current - 1,
1145                comments=self._comments,
1146            )
1147        )
1148        self._comments = []
1149
1150        # If we have either a semicolon or a begin token before the command's token, we'll parse
1151        # whatever follows the command's token as a string
1152        if (
1153            token_type in self.COMMANDS
1154            and self._peek != ";"
1155            and (len(self.tokens) == 1 or self.tokens[-2].token_type in self.COMMAND_PREFIX_TOKENS)
1156        ):
1157            start = self._current
1158            tokens = len(self.tokens)
1159            self._scan(lambda: self._peek == ";")
1160            self.tokens = self.tokens[:tokens]
1161            text = self.sql[start : self._current].strip()
1162            if text:
1163                self._add(TokenType.STRING, text)
1164
1165    def _scan_keywords(self) -> None:
1166        size = 0
1167        word = None
1168        chars = self._text
1169        char = chars
1170        prev_space = False
1171        skip = False
1172        trie = self._KEYWORD_TRIE
1173        single_token = char in self.SINGLE_TOKENS
1174
1175        while chars:
1176            if skip:
1177                result = TrieResult.PREFIX
1178            else:
1179                result, trie = in_trie(trie, char.upper())
1180
1181            if result == TrieResult.FAILED:
1182                break
1183            if result == TrieResult.EXISTS:
1184                word = chars
1185
1186            end = self._current + size
1187            size += 1
1188
1189            if end < self.size:
1190                char = self.sql[end]
1191                single_token = single_token or char in self.SINGLE_TOKENS
1192                is_space = char.isspace()
1193
1194                if not is_space or not prev_space:
1195                    if is_space:
1196                        char = " "
1197                    chars += char
1198                    prev_space = is_space
1199                    skip = False
1200                else:
1201                    skip = True
1202            else:
1203                char = ""
1204                break
1205
1206        if word:
1207            if self._scan_string(word):
1208                return
1209            if self._scan_comment(word):
1210                return
1211            if prev_space or single_token or not char:
1212                self._advance(size - 1)
1213                word = word.upper()
1214                self._add(self.KEYWORDS[word], text=word)
1215                return
1216
1217        if self._char in self.SINGLE_TOKENS:
1218            self._add(self.SINGLE_TOKENS[self._char], text=self._char)
1219            return
1220
1221        self._scan_var()
1222
1223    def _scan_comment(self, comment_start: str) -> bool:
1224        if comment_start not in self._COMMENTS:
1225            return False
1226
1227        comment_start_line = self._line
1228        comment_start_size = len(comment_start)
1229        comment_end = self._COMMENTS[comment_start]
1230
1231        if comment_end:
1232            # Skip the comment's start delimiter
1233            self._advance(comment_start_size)
1234
1235            comment_count = 1
1236            comment_end_size = len(comment_end)
1237
1238            while not self._end:
1239                if self._chars(comment_end_size) == comment_end:
1240                    comment_count -= 1
1241                    if not comment_count:
1242                        break
1243
1244                self._advance(alnum=True)
1245
1246                # Nested comments are allowed by some dialects, e.g. databricks, duckdb, postgres
1247                if (
1248                    self.NESTED_COMMENTS
1249                    and not self._end
1250                    and self._chars(comment_end_size) == comment_start
1251                ):
1252                    self._advance(comment_start_size)
1253                    comment_count += 1
1254
1255            self._comments.append(self._text[comment_start_size : -comment_end_size + 1])
1256            self._advance(comment_end_size - 1)
1257        else:
1258            while not self._end and self.WHITE_SPACE.get(self._peek) is not TokenType.BREAK:
1259                self._advance(alnum=True)
1260            self._comments.append(self._text[comment_start_size:])
1261
1262        if (
1263            comment_start == self.HINT_START
1264            and self.tokens
1265            and self.tokens[-1].token_type in self.TOKENS_PRECEDING_HINT
1266        ):
1267            self._add(TokenType.HINT)
1268
1269        # Leading comment is attached to the succeeding token, whilst trailing comment to the preceding.
1270        # Multiple consecutive comments are preserved by appending them to the current comments list.
1271        if comment_start_line == self._prev_token_line:
1272            self.tokens[-1].comments.extend(self._comments)
1273            self._comments = []
1274            self._prev_token_line = self._line
1275
1276        return True
1277
1278    def _scan_number(self) -> None:
1279        if self._char == "0":
1280            peek = self._peek.upper()
1281            if peek == "B":
1282                return self._scan_bits() if self.BIT_STRINGS else self._add(TokenType.NUMBER)
1283            elif peek == "X":
1284                return self._scan_hex() if self.HEX_STRINGS else self._add(TokenType.NUMBER)
1285
1286        decimal = False
1287        scientific = 0
1288
1289        while True:
1290            if self._peek.isdigit():
1291                self._advance()
1292            elif self._peek == "." and not decimal:
1293                if self.tokens and self.tokens[-1].token_type == TokenType.PARAMETER:
1294                    return self._add(TokenType.NUMBER)
1295                decimal = True
1296                self._advance()
1297            elif self._peek in ("-", "+") and scientific == 1:
1298                scientific += 1
1299                self._advance()
1300            elif self._peek.upper() == "E" and not scientific:
1301                scientific += 1
1302                self._advance()
1303            elif self._peek.isidentifier():
1304                number_text = self._text
1305                literal = ""
1306
1307                while self._peek.strip() and self._peek not in self.SINGLE_TOKENS:
1308                    literal += self._peek
1309                    self._advance()
1310
1311                token_type = self.KEYWORDS.get(self.NUMERIC_LITERALS.get(literal.upper(), ""))
1312
1313                if token_type:
1314                    self._add(TokenType.NUMBER, number_text)
1315                    self._add(TokenType.DCOLON, "::")
1316                    return self._add(token_type, literal)
1317                else:
1318                    replaced = literal.replace("_", "")
1319                    if self.dialect.NUMBERS_CAN_BE_UNDERSCORE_SEPARATED and replaced.isdigit():
1320                        return self._add(TokenType.NUMBER, number_text + replaced)
1321                    if self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT:
1322                        return self._add(TokenType.VAR)
1323
1324                self._advance(-len(literal))
1325                return self._add(TokenType.NUMBER, number_text)
1326            else:
1327                return self._add(TokenType.NUMBER)
1328
1329    def _scan_bits(self) -> None:
1330        self._advance()
1331        value = self._extract_value()
1332        try:
1333            # If `value` can't be converted to a binary, fallback to tokenizing it as an identifier
1334            int(value, 2)
1335            self._add(TokenType.BIT_STRING, value[2:])  # Drop the 0b
1336        except ValueError:
1337            self._add(TokenType.IDENTIFIER)
1338
1339    def _scan_hex(self) -> None:
1340        self._advance()
1341        value = self._extract_value()
1342        try:
1343            # If `value` can't be converted to a hex, fallback to tokenizing it as an identifier
1344            int(value, 16)
1345            self._add(TokenType.HEX_STRING, value[2:])  # Drop the 0x
1346        except ValueError:
1347            self._add(TokenType.IDENTIFIER)
1348
1349    def _extract_value(self) -> str:
1350        while True:
1351            char = self._peek.strip()
1352            if char and char not in self.SINGLE_TOKENS:
1353                self._advance(alnum=True)
1354            else:
1355                break
1356
1357        return self._text
1358
1359    def _scan_string(self, start: str) -> bool:
1360        base = None
1361        token_type = TokenType.STRING
1362
1363        if start in self._QUOTES:
1364            end = self._QUOTES[start]
1365        elif start in self._FORMAT_STRINGS:
1366            end, token_type = self._FORMAT_STRINGS[start]
1367
1368            if token_type == TokenType.HEX_STRING:
1369                base = 16
1370            elif token_type == TokenType.BIT_STRING:
1371                base = 2
1372            elif token_type == TokenType.HEREDOC_STRING:
1373                self._advance()
1374
1375                if self._char == end:
1376                    tag = ""
1377                else:
1378                    tag = self._extract_string(
1379                        end,
1380                        raw_string=True,
1381                        raise_unmatched=not self.HEREDOC_TAG_IS_IDENTIFIER,
1382                    )
1383
1384                if tag and self.HEREDOC_TAG_IS_IDENTIFIER and (self._end or not tag.isidentifier()):
1385                    if not self._end:
1386                        self._advance(-1)
1387
1388                    self._advance(-len(tag))
1389                    self._add(self.HEREDOC_STRING_ALTERNATIVE)
1390                    return True
1391
1392                end = f"{start}{tag}{end}"
1393        else:
1394            return False
1395
1396        self._advance(len(start))
1397        text = self._extract_string(end, raw_string=token_type == TokenType.RAW_STRING)
1398
1399        if base:
1400            try:
1401                int(text, base)
1402            except Exception:
1403                raise TokenError(
1404                    f"Numeric string contains invalid characters from {self._line}:{self._start}"
1405                )
1406
1407        self._add(token_type, text)
1408        return True
1409
1410    def _scan_identifier(self, identifier_end: str) -> None:
1411        self._advance()
1412        text = self._extract_string(
1413            identifier_end, escapes=self._IDENTIFIER_ESCAPES | {identifier_end}
1414        )
1415        self._add(TokenType.IDENTIFIER, text)
1416
1417    def _scan_var(self) -> None:
1418        while True:
1419            char = self._peek.strip()
1420            if char and (char in self.VAR_SINGLE_TOKENS or char not in self.SINGLE_TOKENS):
1421                self._advance(alnum=True)
1422            else:
1423                break
1424
1425        self._add(
1426            TokenType.VAR
1427            if self.tokens and self.tokens[-1].token_type == TokenType.PARAMETER
1428            else self.KEYWORDS.get(self._text.upper(), TokenType.VAR)
1429        )
1430
1431    def _extract_string(
1432        self,
1433        delimiter: str,
1434        escapes: t.Optional[t.Set[str]] = None,
1435        raw_string: bool = False,
1436        raise_unmatched: bool = True,
1437    ) -> str:
1438        text = ""
1439        delim_size = len(delimiter)
1440        escapes = self._STRING_ESCAPES if escapes is None else escapes
1441
1442        while True:
1443            if (
1444                not raw_string
1445                and self.dialect.UNESCAPED_SEQUENCES
1446                and self._peek
1447                and self._char in self.STRING_ESCAPES
1448            ):
1449                unescaped_sequence = self.dialect.UNESCAPED_SEQUENCES.get(self._char + self._peek)
1450                if unescaped_sequence:
1451                    self._advance(2)
1452                    text += unescaped_sequence
1453                    continue
1454            if (
1455                (self.STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS or not raw_string)
1456                and self._char in escapes
1457                and (self._peek == delimiter or self._peek in escapes)
1458                and (self._char not in self._QUOTES or self._char == self._peek)
1459            ):
1460                if self._peek == delimiter:
1461                    text += self._peek
1462                else:
1463                    text += self._char + self._peek
1464
1465                if self._current + 1 < self.size:
1466                    self._advance(2)
1467                else:
1468                    raise TokenError(f"Missing {delimiter} from {self._line}:{self._current}")
1469            else:
1470                if self._chars(delim_size) == delimiter:
1471                    if delim_size > 1:
1472                        self._advance(delim_size - 1)
1473                    break
1474
1475                if self._end:
1476                    if not raise_unmatched:
1477                        return text + self._char
1478
1479                    raise TokenError(f"Missing {delimiter} from {self._line}:{self._start}")
1480
1481                current = self._current - 1
1482                self._advance(alnum=True)
1483                text += self.sql[current : self._current - 1]
1484
1485        return text
1486
1487    def tokenize_rs(self, sql: str) -> t.List[Token]:
1488        if not self._RS_TOKENIZER:
1489            raise SqlglotError("Rust tokenizer is not available")
1490
1491        try:
1492            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
1493            for token in tokens:
1494                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
1495            return tokens
1496        except Exception as e:
1497            raise TokenError(str(e))
Tokenizer( dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, use_rs_tokenizer: Optional[bool] = None)
 997    def __init__(
 998        self, dialect: DialectType = None, use_rs_tokenizer: t.Optional[bool] = None
 999    ) -> None:
1000        from sqlglot.dialects import Dialect
1001
1002        self.dialect = Dialect.get_or_raise(dialect)
1003
1004        # initialize `use_rs_tokenizer`, and allow it to be overwritten per Tokenizer instance
1005        self.use_rs_tokenizer = (
1006            use_rs_tokenizer if use_rs_tokenizer is not None else USE_RS_TOKENIZER
1007        )
1008
1009        if self.use_rs_tokenizer:
1010            self._rs_dialect_settings = RsTokenizerDialectSettings(
1011                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
1012                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
1013                numbers_can_be_underscore_separated=self.dialect.NUMBERS_CAN_BE_UNDERSCORE_SEPARATED,
1014            )
1015
1016        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'>}
BIT_STRINGS: List[Union[str, Tuple[str, str]]] = []
BYTE_STRINGS: List[Union[str, Tuple[str, str]]] = []
HEX_STRINGS: List[Union[str, Tuple[str, str]]] = []
RAW_STRINGS: List[Union[str, Tuple[str, str]]] = []
HEREDOC_STRINGS: List[Union[str, Tuple[str, str]]] = []
UNICODE_STRINGS: List[Union[str, Tuple[str, str]]] = []
IDENTIFIERS: List[Union[str, Tuple[str, str]]] = ['"']
QUOTES: List[Union[str, Tuple[str, str]]] = ["'"]
STRING_ESCAPES = ["'"]
VAR_SINGLE_TOKENS: Set[str] = set()
IDENTIFIER_ESCAPES: List[str] = []
HEREDOC_TAG_IS_IDENTIFIER = False
HEREDOC_STRING_ALTERNATIVE = <TokenType.VAR: 'VAR'>
STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS = True
NESTED_COMMENTS = True
HINT_START = '/*+'
TOKENS_PRECEDING_HINT = {<TokenType.DELETE: 'DELETE'>, <TokenType.SELECT: 'SELECT'>, <TokenType.INSERT: 'INSERT'>, <TokenType.UPDATE: 'UPDATE'>}
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'>, 'NAMESPACE': <TokenType.NAMESPACE: 'NAMESPACE'>, '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.ANALYZE: 'ANALYZE'>, '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.COMMAND: 'COMMAND'>, <TokenType.RENAME: 'RENAME'>, <TokenType.FETCH: 'FETCH'>, <TokenType.SHOW: 'SHOW'>, <TokenType.EXECUTE: 'EXECUTE'>}
COMMAND_PREFIX_TOKENS = {<TokenType.SEMICOLON: 'SEMICOLON'>, <TokenType.BEGIN: 'BEGIN'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
use_rs_tokenizer
def reset(self) -> None:
1018    def reset(self) -> None:
1019        self.sql = ""
1020        self.size = 0
1021        self.tokens: t.List[Token] = []
1022        self._start = 0
1023        self._current = 0
1024        self._line = 1
1025        self._col = 0
1026        self._comments: t.List[str] = []
1027
1028        self._char = ""
1029        self._end = False
1030        self._peek = ""
1031        self._prev_token_line = -1
def tokenize(self, sql: str) -> List[Token]:
1033    def tokenize(self, sql: str) -> t.List[Token]:
1034        """Returns a list of tokens corresponding to the SQL string `sql`."""
1035        if self.use_rs_tokenizer:
1036            return self.tokenize_rs(sql)
1037
1038        self.reset()
1039        self.sql = sql
1040        self.size = len(sql)
1041
1042        try:
1043            self._scan()
1044        except Exception as e:
1045            start = max(self._current - 50, 0)
1046            end = min(self._current + 50, self.size - 1)
1047            context = self.sql[start:end]
1048            raise TokenError(f"Error tokenizing '{context}'") from e
1049
1050        return self.tokens

Returns a list of tokens corresponding to the SQL string sql.

def tokenize_rs(self, sql: str) -> List[Token]:
1487    def tokenize_rs(self, sql: str) -> t.List[Token]:
1488        if not self._RS_TOKENIZER:
1489            raise SqlglotError("Rust tokenizer is not available")
1490
1491        try:
1492            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
1493            for token in tokens:
1494                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
1495            return tokens
1496        except Exception as e:
1497            raise TokenError(str(e))
size
sql
tokens