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

Returns a NUMBER token with number as its text.

@classmethod
def string(cls, string: str) -> Token:
396    @classmethod
397    def string(cls, string: str) -> Token:
398        """Returns a STRING token with `string` as its text."""
399        return cls(TokenType.STRING, string)

Returns a STRING token with string as its text.

@classmethod
def identifier(cls, identifier: str) -> Token:
401    @classmethod
402    def identifier(cls, identifier: str) -> Token:
403        """Returns an IDENTIFIER token with `identifier` as its text."""
404        return cls(TokenType.IDENTIFIER, identifier)

Returns an IDENTIFIER token with identifier as its text.

@classmethod
def var(cls, var: str) -> Token:
406    @classmethod
407    def var(cls, var: str) -> Token:
408        """Returns an VAR token with `var` as its text."""
409        return cls(TokenType.VAR, var)

Returns an VAR token with var as its text.

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

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

def tokenize_rs(self, sql: str) -> List[Token]:
1379    def tokenize_rs(self, sql: str) -> t.List[Token]:
1380        if not self._RS_TOKENIZER:
1381            raise SqlglotError("Rust tokenizer is not available")
1382
1383        try:
1384            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
1385            for token in tokens:
1386                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
1387            return tokens
1388        except Exception as e:
1389            raise TokenError(str(e))
size
sql
tokens