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

Returns a NUMBER token with number as its text.

@classmethod
def string(cls, string: str) -> Token:
407    @classmethod
408    def string(cls, string: str) -> Token:
409        """Returns a STRING token with `string` as its text."""
410        return cls(TokenType.STRING, string)

Returns a STRING token with string as its text.

@classmethod
def identifier(cls, identifier: str) -> Token:
412    @classmethod
413    def identifier(cls, identifier: str) -> Token:
414        """Returns an IDENTIFIER token with `identifier` as its text."""
415        return cls(TokenType.IDENTIFIER, identifier)

Returns an IDENTIFIER token with identifier as its text.

@classmethod
def var(cls, var: str) -> Token:
417    @classmethod
418    def var(cls, var: str) -> Token:
419        """Returns an VAR token with `var` as its text."""
420        return cls(TokenType.VAR, var)

Returns an VAR token with var as its text.

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

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

def tokenize_rs(self, sql: str) -> List[Token]:
1407    def tokenize_rs(self, sql: str) -> t.List[Token]:
1408        if not self._RS_TOKENIZER:
1409            raise SqlglotError("Rust tokenizer is not available")
1410
1411        try:
1412            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
1413            for token in tokens:
1414                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
1415            return tokens
1416        except Exception as e:
1417            raise TokenError(str(e))
size
sql
tokens