Edit on GitHub

# sqlglot.tokens

View Source

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

class TokenType(sqlglot.helper.AutoName): View Source

     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    DOTCOLON = auto()
     42    DCOLON = auto()
     43    DQMARK = auto()
     44    SEMICOLON = auto()
     45    STAR = auto()
     46    BACKSLASH = auto()
     47    SLASH = auto()
     48    LT = auto()
     49    LTE = auto()
     50    GT = auto()
     51    GTE = auto()
     52    NOT = auto()
     53    EQ = auto()
     54    NEQ = auto()
     55    NULLSAFE_EQ = auto()
     56    COLON_EQ = auto()
     57    AND = auto()
     58    OR = auto()
     59    AMP = auto()
     60    DPIPE = auto()
     61    PIPE_GT = auto()
     62    PIPE = auto()
     63    PIPE_SLASH = auto()
     64    DPIPE_SLASH = auto()
     65    CARET = auto()
     66    CARET_AT = auto()
     67    TILDA = auto()
     68    ARROW = auto()
     69    DARROW = auto()
     70    FARROW = auto()
     71    HASH = auto()
     72    HASH_ARROW = auto()
     73    DHASH_ARROW = auto()
     74    LR_ARROW = auto()
     75    DAT = auto()
     76    LT_AT = auto()
     77    AT_GT = auto()
     78    DOLLAR = auto()
     79    PARAMETER = auto()
     80    SESSION_PARAMETER = auto()
     81    DAMP = auto()
     82    XOR = auto()
     83    DSTAR = auto()
     84
     85    URI_START = auto()
     86
     87    BLOCK_START = auto()
     88    BLOCK_END = auto()
     89
     90    SPACE = auto()
     91    BREAK = auto()
     92
     93    STRING = auto()
     94    NUMBER = auto()
     95    IDENTIFIER = auto()
     96    DATABASE = auto()
     97    COLUMN = auto()
     98    COLUMN_DEF = auto()
     99    SCHEMA = auto()
    100    TABLE = auto()
    101    WAREHOUSE = auto()
    102    STAGE = auto()
    103    STREAMLIT = auto()
    104    VAR = auto()
    105    BIT_STRING = auto()
    106    HEX_STRING = auto()
    107    BYTE_STRING = auto()
    108    NATIONAL_STRING = auto()
    109    RAW_STRING = auto()
    110    HEREDOC_STRING = auto()
    111    UNICODE_STRING = auto()
    112
    113    # types
    114    BIT = auto()
    115    BOOLEAN = auto()
    116    TINYINT = auto()
    117    UTINYINT = auto()
    118    SMALLINT = auto()
    119    USMALLINT = auto()
    120    MEDIUMINT = auto()
    121    UMEDIUMINT = auto()
    122    INT = auto()
    123    UINT = auto()
    124    BIGINT = auto()
    125    UBIGINT = auto()
    126    INT128 = auto()
    127    UINT128 = auto()
    128    INT256 = auto()
    129    UINT256 = auto()
    130    FLOAT = auto()
    131    DOUBLE = auto()
    132    UDOUBLE = auto()
    133    DECIMAL = auto()
    134    DECIMAL32 = auto()
    135    DECIMAL64 = auto()
    136    DECIMAL128 = auto()
    137    DECIMAL256 = auto()
    138    UDECIMAL = auto()
    139    BIGDECIMAL = auto()
    140    CHAR = auto()
    141    NCHAR = auto()
    142    VARCHAR = auto()
    143    NVARCHAR = auto()
    144    BPCHAR = auto()
    145    TEXT = auto()
    146    MEDIUMTEXT = auto()
    147    LONGTEXT = auto()
    148    BLOB = auto()
    149    MEDIUMBLOB = auto()
    150    LONGBLOB = auto()
    151    TINYBLOB = auto()
    152    TINYTEXT = auto()
    153    NAME = auto()
    154    BINARY = auto()
    155    VARBINARY = auto()
    156    JSON = auto()
    157    JSONB = auto()
    158    TIME = auto()
    159    TIMETZ = auto()
    160    TIMESTAMP = auto()
    161    TIMESTAMPTZ = auto()
    162    TIMESTAMPLTZ = auto()
    163    TIMESTAMPNTZ = auto()
    164    TIMESTAMP_S = auto()
    165    TIMESTAMP_MS = auto()
    166    TIMESTAMP_NS = auto()
    167    DATETIME = auto()
    168    DATETIME2 = auto()
    169    DATETIME64 = auto()
    170    SMALLDATETIME = auto()
    171    DATE = auto()
    172    DATE32 = auto()
    173    INT4RANGE = auto()
    174    INT4MULTIRANGE = auto()
    175    INT8RANGE = auto()
    176    INT8MULTIRANGE = auto()
    177    NUMRANGE = auto()
    178    NUMMULTIRANGE = auto()
    179    TSRANGE = auto()
    180    TSMULTIRANGE = auto()
    181    TSTZRANGE = auto()
    182    TSTZMULTIRANGE = auto()
    183    DATERANGE = auto()
    184    DATEMULTIRANGE = auto()
    185    UUID = auto()
    186    GEOGRAPHY = auto()
    187    NULLABLE = auto()
    188    GEOMETRY = auto()
    189    POINT = auto()
    190    RING = auto()
    191    LINESTRING = auto()
    192    MULTILINESTRING = auto()
    193    POLYGON = auto()
    194    MULTIPOLYGON = auto()
    195    HLLSKETCH = auto()
    196    HSTORE = auto()
    197    SUPER = auto()
    198    SERIAL = auto()
    199    SMALLSERIAL = auto()
    200    BIGSERIAL = auto()
    201    XML = auto()
    202    YEAR = auto()
    203    USERDEFINED = auto()
    204    MONEY = auto()
    205    SMALLMONEY = auto()
    206    ROWVERSION = auto()
    207    IMAGE = auto()
    208    VARIANT = auto()
    209    OBJECT = auto()
    210    INET = auto()
    211    IPADDRESS = auto()
    212    IPPREFIX = auto()
    213    IPV4 = auto()
    214    IPV6 = auto()
    215    ENUM = auto()
    216    ENUM8 = auto()
    217    ENUM16 = auto()
    218    FIXEDSTRING = auto()
    219    LOWCARDINALITY = auto()
    220    NESTED = auto()
    221    AGGREGATEFUNCTION = auto()
    222    SIMPLEAGGREGATEFUNCTION = auto()
    223    TDIGEST = auto()
    224    UNKNOWN = auto()
    225    VECTOR = auto()
    226    DYNAMIC = auto()
    227    VOID = auto()
    228
    229    # keywords
    230    ALIAS = auto()
    231    ALTER = auto()
    232    ALWAYS = auto()
    233    ALL = auto()
    234    ANTI = auto()
    235    ANY = auto()
    236    APPLY = auto()
    237    ARRAY = auto()
    238    ASC = auto()
    239    ASOF = auto()
    240    ATTACH = auto()
    241    AUTO_INCREMENT = auto()
    242    BEGIN = auto()
    243    BETWEEN = auto()
    244    BULK_COLLECT_INTO = auto()
    245    CACHE = auto()
    246    CASE = auto()
    247    CHARACTER_SET = auto()
    248    CLUSTER_BY = auto()
    249    COLLATE = auto()
    250    COMMAND = auto()
    251    COMMENT = auto()
    252    COMMIT = auto()
    253    CONNECT_BY = auto()
    254    CONSTRAINT = auto()
    255    COPY = auto()
    256    CREATE = auto()
    257    CROSS = auto()
    258    CUBE = auto()
    259    CURRENT_DATE = auto()
    260    CURRENT_DATETIME = auto()
    261    CURRENT_SCHEMA = auto()
    262    CURRENT_TIME = auto()
    263    CURRENT_TIMESTAMP = auto()
    264    CURRENT_USER = auto()
    265    DECLARE = auto()
    266    DEFAULT = auto()
    267    DELETE = auto()
    268    DESC = auto()
    269    DESCRIBE = auto()
    270    DETACH = auto()
    271    DICTIONARY = auto()
    272    DISTINCT = auto()
    273    DISTRIBUTE_BY = auto()
    274    DIV = auto()
    275    DROP = auto()
    276    ELSE = auto()
    277    END = auto()
    278    ESCAPE = auto()
    279    EXCEPT = auto()
    280    EXECUTE = auto()
    281    EXISTS = auto()
    282    FALSE = auto()
    283    FETCH = auto()
    284    FILE_FORMAT = auto()
    285    FILTER = auto()
    286    FINAL = auto()
    287    FIRST = auto()
    288    FOR = auto()
    289    FORCE = auto()
    290    FOREIGN_KEY = auto()
    291    FORMAT = auto()
    292    FROM = auto()
    293    FULL = auto()
    294    FUNCTION = auto()
    295    GET = auto()
    296    GLOB = auto()
    297    GLOBAL = auto()
    298    GRANT = auto()
    299    GROUP_BY = auto()
    300    GROUPING_SETS = auto()
    301    HAVING = auto()
    302    HINT = auto()
    303    IGNORE = auto()
    304    ILIKE = auto()
    305    ILIKE_ANY = auto()
    306    IN = auto()
    307    INDEX = auto()
    308    INNER = auto()
    309    INSERT = auto()
    310    INTERSECT = auto()
    311    INTERVAL = auto()
    312    INTO = auto()
    313    INTRODUCER = auto()
    314    IRLIKE = auto()
    315    IS = auto()
    316    ISNULL = auto()
    317    JOIN = auto()
    318    JOIN_MARKER = auto()
    319    KEEP = auto()
    320    KEY = auto()
    321    KILL = auto()
    322    LANGUAGE = auto()
    323    LATERAL = auto()
    324    LEFT = auto()
    325    LIKE = auto()
    326    LIKE_ANY = auto()
    327    LIMIT = auto()
    328    LIST = auto()
    329    LOAD = auto()
    330    LOCK = auto()
    331    MAP = auto()
    332    MATCH_CONDITION = auto()
    333    MATCH_RECOGNIZE = auto()
    334    MEMBER_OF = auto()
    335    MERGE = auto()
    336    MOD = auto()
    337    MODEL = auto()
    338    NATURAL = auto()
    339    NEXT = auto()
    340    NOTHING = auto()
    341    NOTNULL = auto()
    342    NULL = auto()
    343    OBJECT_IDENTIFIER = auto()
    344    OFFSET = auto()
    345    ON = auto()
    346    ONLY = auto()
    347    OPERATOR = auto()
    348    ORDER_BY = auto()
    349    ORDER_SIBLINGS_BY = auto()
    350    ORDERED = auto()
    351    ORDINALITY = auto()
    352    OUTER = auto()
    353    OVER = auto()
    354    OVERLAPS = auto()
    355    OVERWRITE = auto()
    356    PARTITION = auto()
    357    PARTITION_BY = auto()
    358    PERCENT = auto()
    359    PIVOT = auto()
    360    PLACEHOLDER = auto()
    361    POSITIONAL = auto()
    362    PRAGMA = auto()
    363    PREWHERE = auto()
    364    PRIMARY_KEY = auto()
    365    PROCEDURE = auto()
    366    PROPERTIES = auto()
    367    PSEUDO_TYPE = auto()
    368    PUT = auto()
    369    QUALIFY = auto()
    370    QUOTE = auto()
    371    RANGE = auto()
    372    RECURSIVE = auto()
    373    REFRESH = auto()
    374    RENAME = auto()
    375    REPLACE = auto()
    376    RETURNING = auto()
    377    REFERENCES = auto()
    378    RIGHT = auto()
    379    RLIKE = auto()
    380    ROLLBACK = auto()
    381    ROLLUP = auto()
    382    ROW = auto()
    383    ROWS = auto()
    384    SELECT = auto()
    385    SEMI = auto()
    386    SEPARATOR = auto()
    387    SEQUENCE = auto()
    388    SERDE_PROPERTIES = auto()
    389    SET = auto()
    390    SETTINGS = auto()
    391    SHOW = auto()
    392    SIMILAR_TO = auto()
    393    SOME = auto()
    394    SORT_BY = auto()
    395    START_WITH = auto()
    396    STORAGE_INTEGRATION = auto()
    397    STRAIGHT_JOIN = auto()
    398    STRUCT = auto()
    399    SUMMARIZE = auto()
    400    TABLE_SAMPLE = auto()
    401    TAG = auto()
    402    TEMPORARY = auto()
    403    TOP = auto()
    404    THEN = auto()
    405    TRUE = auto()
    406    TRUNCATE = auto()
    407    UNCACHE = auto()
    408    UNION = auto()
    409    UNNEST = auto()
    410    UNPIVOT = auto()
    411    UPDATE = auto()
    412    USE = auto()
    413    USING = auto()
    414    VALUES = auto()
    415    VIEW = auto()
    416    VOLATILE = auto()
    417    WHEN = auto()
    418    WHERE = auto()
    419    WINDOW = auto()
    420    WITH = auto()
    421    UNIQUE = auto()
    422    VERSION_SNAPSHOT = auto()
    423    TIMESTAMP_SNAPSHOT = auto()
    424    OPTION = auto()
    425    SINK = auto()
    426    SOURCE = auto()
    427    ANALYZE = auto()
    428    NAMESPACE = auto()
    429    EXPORT = auto()
    430
    431    # sentinel
    432    HIVE_TOKEN_STREAM = 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'>
DOTCOLON = <TokenType.DOTCOLON: 'DOTCOLON'>
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_GT = <TokenType.PIPE_GT: 'PIPE_GT'>
PIPE = <TokenType.PIPE: 'PIPE'>
PIPE_SLASH = <TokenType.PIPE_SLASH: 'PIPE_SLASH'>
DPIPE_SLASH = <TokenType.DPIPE_SLASH: 'DPIPE_SLASH'>
CARET = <TokenType.CARET: 'CARET'>
CARET_AT = <TokenType.CARET_AT: 'CARET_AT'>
TILDA = <TokenType.TILDA: 'TILDA'>
ARROW = <TokenType.ARROW: 'ARROW'>
DARROW = <TokenType.DARROW: 'DARROW'>
FARROW = <TokenType.FARROW: 'FARROW'>
HASH = <TokenType.HASH: 'HASH'>
HASH_ARROW = <TokenType.HASH_ARROW: 'HASH_ARROW'>
DHASH_ARROW = <TokenType.DHASH_ARROW: 'DHASH_ARROW'>
LR_ARROW = <TokenType.LR_ARROW: 'LR_ARROW'>
DAT = <TokenType.DAT: 'DAT'>
LT_AT = <TokenType.LT_AT: 'LT_AT'>
AT_GT = <TokenType.AT_GT: 'AT_GT'>
DOLLAR = <TokenType.DOLLAR: 'DOLLAR'>
PARAMETER = <TokenType.PARAMETER: 'PARAMETER'>
SESSION_PARAMETER = <TokenType.SESSION_PARAMETER: 'SESSION_PARAMETER'>
DAMP = <TokenType.DAMP: 'DAMP'>
XOR = <TokenType.XOR: 'XOR'>
DSTAR = <TokenType.DSTAR: 'DSTAR'>
URI_START = <TokenType.URI_START: 'URI_START'>
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'>
STAGE = <TokenType.STAGE: 'STAGE'>
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'>
UDOUBLE = <TokenType.UDOUBLE: 'UDOUBLE'>
DECIMAL = <TokenType.DECIMAL: 'DECIMAL'>
DECIMAL32 = <TokenType.DECIMAL32: 'DECIMAL32'>
DECIMAL64 = <TokenType.DECIMAL64: 'DECIMAL64'>
DECIMAL128 = <TokenType.DECIMAL128: 'DECIMAL128'>
DECIMAL256 = <TokenType.DECIMAL256: 'DECIMAL256'>
UDECIMAL = <TokenType.UDECIMAL: 'UDECIMAL'>
BIGDECIMAL = <TokenType.BIGDECIMAL: 'BIGDECIMAL'>
CHAR = <TokenType.CHAR: 'CHAR'>
NCHAR = <TokenType.NCHAR: 'NCHAR'>
VARCHAR = <TokenType.VARCHAR: 'VARCHAR'>
NVARCHAR = <TokenType.NVARCHAR: 'NVARCHAR'>
BPCHAR = <TokenType.BPCHAR: 'BPCHAR'>
TEXT = <TokenType.TEXT: 'TEXT'>
MEDIUMTEXT = <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <TokenType.LONGTEXT: 'LONGTEXT'>
BLOB = <TokenType.BLOB: 'BLOB'>
MEDIUMBLOB = <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <TokenType.LONGBLOB: 'LONGBLOB'>
TINYBLOB = <TokenType.TINYBLOB: 'TINYBLOB'>
TINYTEXT = <TokenType.TINYTEXT: 'TINYTEXT'>
NAME = <TokenType.NAME: 'NAME'>
BINARY = <TokenType.BINARY: 'BINARY'>
VARBINARY = <TokenType.VARBINARY: 'VARBINARY'>
JSON = <TokenType.JSON: 'JSON'>
JSONB = <TokenType.JSONB: 'JSONB'>
TIME = <TokenType.TIME: 'TIME'>
TIMETZ = <TokenType.TIMETZ: 'TIMETZ'>
TIMESTAMP = <TokenType.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPNTZ = <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>
TIMESTAMP_S = <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>
TIMESTAMP_MS = <TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>
TIMESTAMP_NS = <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>
DATETIME = <TokenType.DATETIME: 'DATETIME'>
DATETIME2 = <TokenType.DATETIME2: 'DATETIME2'>
DATETIME64 = <TokenType.DATETIME64: 'DATETIME64'>
SMALLDATETIME = <TokenType.SMALLDATETIME: 'SMALLDATETIME'>
DATE = <TokenType.DATE: 'DATE'>
DATE32 = <TokenType.DATE32: 'DATE32'>
INT4RANGE = <TokenType.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <TokenType.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <TokenType.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <TokenType.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <TokenType.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <TokenType.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>
UUID = <TokenType.UUID: 'UUID'>
GEOGRAPHY = <TokenType.GEOGRAPHY: 'GEOGRAPHY'>
NULLABLE = <TokenType.NULLABLE: 'NULLABLE'>
GEOMETRY = <TokenType.GEOMETRY: 'GEOMETRY'>
POINT = <TokenType.POINT: 'POINT'>
RING = <TokenType.RING: 'RING'>
LINESTRING = <TokenType.LINESTRING: 'LINESTRING'>
MULTILINESTRING = <TokenType.MULTILINESTRING: 'MULTILINESTRING'>
POLYGON = <TokenType.POLYGON: 'POLYGON'>
MULTIPOLYGON = <TokenType.MULTIPOLYGON: 'MULTIPOLYGON'>
HLLSKETCH = <TokenType.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <TokenType.HSTORE: 'HSTORE'>
SUPER = <TokenType.SUPER: 'SUPER'>
SERIAL = <TokenType.SERIAL: 'SERIAL'>
SMALLSERIAL = <TokenType.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <TokenType.BIGSERIAL: 'BIGSERIAL'>
XML = <TokenType.XML: 'XML'>
YEAR = <TokenType.YEAR: 'YEAR'>
USERDEFINED = <TokenType.USERDEFINED: 'USERDEFINED'>
MONEY = <TokenType.MONEY: 'MONEY'>
SMALLMONEY = <TokenType.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <TokenType.ROWVERSION: 'ROWVERSION'>
IMAGE = <TokenType.IMAGE: 'IMAGE'>
VARIANT = <TokenType.VARIANT: 'VARIANT'>
OBJECT = <TokenType.OBJECT: 'OBJECT'>
INET = <TokenType.INET: 'INET'>
IPADDRESS = <TokenType.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <TokenType.IPPREFIX: 'IPPREFIX'>
IPV4 = <TokenType.IPV4: 'IPV4'>
IPV6 = <TokenType.IPV6: 'IPV6'>
ENUM = <TokenType.ENUM: 'ENUM'>
ENUM8 = <TokenType.ENUM8: 'ENUM8'>
ENUM16 = <TokenType.ENUM16: 'ENUM16'>
FIXEDSTRING = <TokenType.FIXEDSTRING: 'FIXEDSTRING'>
LOWCARDINALITY = <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>
NESTED = <TokenType.NESTED: 'NESTED'>
AGGREGATEFUNCTION = <TokenType.AGGREGATEFUNCTION: 'AGGREGATEFUNCTION'>
SIMPLEAGGREGATEFUNCTION = <TokenType.SIMPLEAGGREGATEFUNCTION: 'SIMPLEAGGREGATEFUNCTION'>
TDIGEST = <TokenType.TDIGEST: 'TDIGEST'>
UNKNOWN = <TokenType.UNKNOWN: 'UNKNOWN'>
VECTOR = <TokenType.VECTOR: 'VECTOR'>
DYNAMIC = <TokenType.DYNAMIC: 'DYNAMIC'>
VOID = <TokenType.VOID: 'VOID'>
ALIAS = <TokenType.ALIAS: 'ALIAS'>
ALTER = <TokenType.ALTER: 'ALTER'>
ALWAYS = <TokenType.ALWAYS: 'ALWAYS'>
ALL = <TokenType.ALL: 'ALL'>
ANTI = <TokenType.ANTI: 'ANTI'>
ANY = <TokenType.ANY: 'ANY'>
APPLY = <TokenType.APPLY: 'APPLY'>
ARRAY = <TokenType.ARRAY: 'ARRAY'>
ASC = <TokenType.ASC: 'ASC'>
ASOF = <TokenType.ASOF: 'ASOF'>
ATTACH = <TokenType.ATTACH: 'ATTACH'>
AUTO_INCREMENT = <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>
BEGIN = <TokenType.BEGIN: 'BEGIN'>
BETWEEN = <TokenType.BETWEEN: 'BETWEEN'>
BULK_COLLECT_INTO = <TokenType.BULK_COLLECT_INTO: 'BULK_COLLECT_INTO'>
CACHE = <TokenType.CACHE: 'CACHE'>
CASE = <TokenType.CASE: 'CASE'>
CHARACTER_SET = <TokenType.CHARACTER_SET: 'CHARACTER_SET'>
CLUSTER_BY = <TokenType.CLUSTER_BY: 'CLUSTER_BY'>
COLLATE = <TokenType.COLLATE: 'COLLATE'>
COMMAND = <TokenType.COMMAND: 'COMMAND'>
COMMENT = <TokenType.COMMENT: 'COMMENT'>
COMMIT = <TokenType.COMMIT: 'COMMIT'>
CONNECT_BY = <TokenType.CONNECT_BY: 'CONNECT_BY'>
CONSTRAINT = <TokenType.CONSTRAINT: 'CONSTRAINT'>
COPY = <TokenType.COPY: 'COPY'>
CREATE = <TokenType.CREATE: 'CREATE'>
CROSS = <TokenType.CROSS: 'CROSS'>
CUBE = <TokenType.CUBE: 'CUBE'>
CURRENT_DATE = <TokenType.CURRENT_DATE: 'CURRENT_DATE'>
CURRENT_DATETIME = <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>
CURRENT_SCHEMA = <TokenType.CURRENT_SCHEMA: 'CURRENT_SCHEMA'>
CURRENT_TIME = <TokenType.CURRENT_TIME: 'CURRENT_TIME'>
CURRENT_TIMESTAMP = <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>
CURRENT_USER = <TokenType.CURRENT_USER: 'CURRENT_USER'>
DECLARE = <TokenType.DECLARE: 'DECLARE'>
DEFAULT = <TokenType.DEFAULT: 'DEFAULT'>
DELETE = <TokenType.DELETE: 'DELETE'>
DESC = <TokenType.DESC: 'DESC'>
DESCRIBE = <TokenType.DESCRIBE: 'DESCRIBE'>
DETACH = <TokenType.DETACH: 'DETACH'>
DICTIONARY = <TokenType.DICTIONARY: 'DICTIONARY'>
DISTINCT = <TokenType.DISTINCT: 'DISTINCT'>
DISTRIBUTE_BY = <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>
DIV = <TokenType.DIV: 'DIV'>
DROP = <TokenType.DROP: 'DROP'>
ELSE = <TokenType.ELSE: 'ELSE'>
END = <TokenType.END: 'END'>
ESCAPE = <TokenType.ESCAPE: 'ESCAPE'>
EXCEPT = <TokenType.EXCEPT: 'EXCEPT'>
EXECUTE = <TokenType.EXECUTE: 'EXECUTE'>
EXISTS = <TokenType.EXISTS: 'EXISTS'>
FALSE = <TokenType.FALSE: 'FALSE'>
FETCH = <TokenType.FETCH: 'FETCH'>
FILE_FORMAT = <TokenType.FILE_FORMAT: 'FILE_FORMAT'>
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'>
GET = <TokenType.GET: 'GET'>
GLOB = <TokenType.GLOB: 'GLOB'>
GLOBAL = <TokenType.GLOBAL: 'GLOBAL'>
GRANT = <TokenType.GRANT: 'GRANT'>
GROUP_BY = <TokenType.GROUP_BY: 'GROUP_BY'>
GROUPING_SETS = <TokenType.GROUPING_SETS: 'GROUPING_SETS'>
HAVING = <TokenType.HAVING: 'HAVING'>
HINT = <TokenType.HINT: 'HINT'>
IGNORE = <TokenType.IGNORE: 'IGNORE'>
ILIKE = <TokenType.ILIKE: 'ILIKE'>
ILIKE_ANY = <TokenType.ILIKE_ANY: 'ILIKE_ANY'>
IN = <TokenType.IN: 'IN'>
INDEX = <TokenType.INDEX: 'INDEX'>
INNER = <TokenType.INNER: 'INNER'>
INSERT = <TokenType.INSERT: 'INSERT'>
INTERSECT = <TokenType.INTERSECT: 'INTERSECT'>
INTERVAL = <TokenType.INTERVAL: 'INTERVAL'>
INTO = <TokenType.INTO: 'INTO'>
INTRODUCER = <TokenType.INTRODUCER: 'INTRODUCER'>
IRLIKE = <TokenType.IRLIKE: 'IRLIKE'>
IS = <TokenType.IS: 'IS'>
ISNULL = <TokenType.ISNULL: 'ISNULL'>
JOIN = <TokenType.JOIN: 'JOIN'>
JOIN_MARKER = <TokenType.JOIN_MARKER: 'JOIN_MARKER'>
KEEP = <TokenType.KEEP: 'KEEP'>
KEY = <TokenType.KEY: 'KEY'>
KILL = <TokenType.KILL: 'KILL'>
LANGUAGE = <TokenType.LANGUAGE: 'LANGUAGE'>
LATERAL = <TokenType.LATERAL: 'LATERAL'>
LEFT = <TokenType.LEFT: 'LEFT'>
LIKE = <TokenType.LIKE: 'LIKE'>
LIKE_ANY = <TokenType.LIKE_ANY: 'LIKE_ANY'>
LIMIT = <TokenType.LIMIT: 'LIMIT'>
LIST = <TokenType.LIST: 'LIST'>
LOAD = <TokenType.LOAD: 'LOAD'>
LOCK = <TokenType.LOCK: 'LOCK'>
MAP = <TokenType.MAP: 'MAP'>
MATCH_CONDITION = <TokenType.MATCH_CONDITION: 'MATCH_CONDITION'>
MATCH_RECOGNIZE = <TokenType.MATCH_RECOGNIZE: 'MATCH_RECOGNIZE'>
MEMBER_OF = <TokenType.MEMBER_OF: 'MEMBER_OF'>
MERGE = <TokenType.MERGE: 'MERGE'>
MOD = <TokenType.MOD: 'MOD'>
MODEL = <TokenType.MODEL: 'MODEL'>
NATURAL = <TokenType.NATURAL: 'NATURAL'>
NEXT = <TokenType.NEXT: 'NEXT'>
NOTHING = <TokenType.NOTHING: 'NOTHING'>
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'>
PUT = <TokenType.PUT: 'PUT'>
QUALIFY = <TokenType.QUALIFY: 'QUALIFY'>
QUOTE = <TokenType.QUOTE: 'QUOTE'>
RANGE = <TokenType.RANGE: 'RANGE'>
RECURSIVE = <TokenType.RECURSIVE: 'RECURSIVE'>
REFRESH = <TokenType.REFRESH: 'REFRESH'>
RENAME = <TokenType.RENAME: 'RENAME'>
REPLACE = <TokenType.REPLACE: 'REPLACE'>
RETURNING = <TokenType.RETURNING: 'RETURNING'>
REFERENCES = <TokenType.REFERENCES: 'REFERENCES'>
RIGHT = <TokenType.RIGHT: 'RIGHT'>
RLIKE = <TokenType.RLIKE: 'RLIKE'>
ROLLBACK = <TokenType.ROLLBACK: 'ROLLBACK'>
ROLLUP = <TokenType.ROLLUP: 'ROLLUP'>
ROW = <TokenType.ROW: 'ROW'>
ROWS = <TokenType.ROWS: 'ROWS'>
SELECT = <TokenType.SELECT: 'SELECT'>
SEMI = <TokenType.SEMI: 'SEMI'>
SEPARATOR = <TokenType.SEPARATOR: 'SEPARATOR'>
SEQUENCE = <TokenType.SEQUENCE: 'SEQUENCE'>
SERDE_PROPERTIES = <TokenType.SERDE_PROPERTIES: 'SERDE_PROPERTIES'>
SET = <TokenType.SET: 'SET'>
SETTINGS = <TokenType.SETTINGS: 'SETTINGS'>
SHOW = <TokenType.SHOW: 'SHOW'>
SIMILAR_TO = <TokenType.SIMILAR_TO: 'SIMILAR_TO'>
SOME = <TokenType.SOME: 'SOME'>
SORT_BY = <TokenType.SORT_BY: 'SORT_BY'>
START_WITH = <TokenType.START_WITH: 'START_WITH'>
STORAGE_INTEGRATION = <TokenType.STORAGE_INTEGRATION: 'STORAGE_INTEGRATION'>
STRAIGHT_JOIN = <TokenType.STRAIGHT_JOIN: 'STRAIGHT_JOIN'>
STRUCT = <TokenType.STRUCT: 'STRUCT'>
SUMMARIZE = <TokenType.SUMMARIZE: 'SUMMARIZE'>
TABLE_SAMPLE = <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>
TAG = <TokenType.TAG: 'TAG'>
TEMPORARY = <TokenType.TEMPORARY: 'TEMPORARY'>
TOP = <TokenType.TOP: 'TOP'>
THEN = <TokenType.THEN: 'THEN'>
TRUE = <TokenType.TRUE: 'TRUE'>
TRUNCATE = <TokenType.TRUNCATE: 'TRUNCATE'>
UNCACHE = <TokenType.UNCACHE: 'UNCACHE'>
UNION = <TokenType.UNION: 'UNION'>
UNNEST = <TokenType.UNNEST: 'UNNEST'>
UNPIVOT = <TokenType.UNPIVOT: 'UNPIVOT'>
UPDATE = <TokenType.UPDATE: 'UPDATE'>
USE = <TokenType.USE: 'USE'>
USING = <TokenType.USING: 'USING'>
VALUES = <TokenType.VALUES: 'VALUES'>
VIEW = <TokenType.VIEW: 'VIEW'>
VOLATILE = <TokenType.VOLATILE: 'VOLATILE'>
WHEN = <TokenType.WHEN: 'WHEN'>
WHERE = <TokenType.WHERE: 'WHERE'>
WINDOW = <TokenType.WINDOW: 'WINDOW'>
WITH = <TokenType.WITH: 'WITH'>
UNIQUE = <TokenType.UNIQUE: 'UNIQUE'>
VERSION_SNAPSHOT = <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>
TIMESTAMP_SNAPSHOT = <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>
OPTION = <TokenType.OPTION: 'OPTION'>
SINK = <TokenType.SINK: 'SINK'>
SOURCE = <TokenType.SOURCE: 'SOURCE'>
ANALYZE = <TokenType.ANALYZE: 'ANALYZE'>
NAMESPACE = <TokenType.NAMESPACE: 'NAMESPACE'>
EXPORT = <TokenType.EXPORT: 'EXPORT'>
HIVE_TOKEN_STREAM = <TokenType.HIVE_TOKEN_STREAM: 'HIVE_TOKEN_STREAM'>
class Token: View Source

    439class Token:
    440    __slots__ = ("token_type", "text", "line", "col", "start", "end", "comments")
    441
    442    @classmethod
    443    def number(cls, number: int) -> Token:
    444        """Returns a NUMBER token with `number` as its text."""
    445        return cls(TokenType.NUMBER, str(number))
    446
    447    @classmethod
    448    def string(cls, string: str) -> Token:
    449        """Returns a STRING token with `string` as its text."""
    450        return cls(TokenType.STRING, string)
    451
    452    @classmethod
    453    def identifier(cls, identifier: str) -> Token:
    454        """Returns an IDENTIFIER token with `identifier` as its text."""
    455        return cls(TokenType.IDENTIFIER, identifier)
    456
    457    @classmethod
    458    def var(cls, var: str) -> Token:
    459        """Returns an VAR token with `var` as its text."""
    460        return cls(TokenType.VAR, var)
    461
    462    def __init__(
    463        self,
    464        token_type: TokenType,
    465        text: str,
    466        line: int = 1,
    467        col: int = 1,
    468        start: int = 0,
    469        end: int = 0,
    470        comments: t.Optional[t.List[str]] = None,
    471    ) -> None:
    472        """Token initializer.
    473
    474        Args:
    475            token_type: The TokenType Enum.
    476            text: The text of the token.
    477            line: The line that the token ends on.
    478            col: The column that the token ends on.
    479            start: The start index of the token.
    480            end: The ending index of the token.
    481            comments: The comments to attach to the token.
    482        """
    483        self.token_type = token_type
    484        self.text = text
    485        self.line = line
    486        self.col = col
    487        self.start = start
    488        self.end = end
    489        self.comments = [] if comments is None else comments
    490
    491    def __repr__(self) -> str:
    492        attributes = ", ".join(f"{k}: {getattr(self, k)}" for k in self.__slots__)
    493        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) View Source

    462    def __init__(
    463        self,
    464        token_type: TokenType,
    465        text: str,
    466        line: int = 1,
    467        col: int = 1,
    468        start: int = 0,
    469        end: int = 0,
    470        comments: t.Optional[t.List[str]] = None,
    471    ) -> None:
    472        """Token initializer.
    473
    474        Args:
    475            token_type: The TokenType Enum.
    476            text: The text of the token.
    477            line: The line that the token ends on.
    478            col: The column that the token ends on.
    479            start: The start index of the token.
    480            end: The ending index of the token.
    481            comments: The comments to attach to the token.
    482        """
    483        self.token_type = token_type
    484        self.text = text
    485        self.line = line
    486        self.col = col
    487        self.start = start
    488        self.end = end
    489        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: View Source

    442    @classmethod
    443    def number(cls, number: int) -> Token:
    444        """Returns a NUMBER token with `number` as its text."""
    445        return cls(TokenType.NUMBER, str(number))

Returns a NUMBER token with `number` as its text.

@classmethod
def string(cls, string: str) -> Token: View Source

    447    @classmethod
    448    def string(cls, string: str) -> Token:
    449        """Returns a STRING token with `string` as its text."""
    450        return cls(TokenType.STRING, string)

Returns a STRING token with `string` as its text.

@classmethod
def identifier(cls, identifier: str) -> Token: View Source

    452    @classmethod
    453    def identifier(cls, identifier: str) -> Token:
    454        """Returns an IDENTIFIER token with `identifier` as its text."""
    455        return cls(TokenType.IDENTIFIER, identifier)

Returns an IDENTIFIER token with `identifier` as its text.

@classmethod
def var(cls, var: str) -> Token: View Source

    457    @classmethod
    458    def var(cls, var: str) -> Token:
    459        """Returns an VAR token with `var` as its text."""
    460        return cls(TokenType.VAR, var)

Returns an VAR token with `var` as its text.

token_type
text
line
col
start
end
comments
class Tokenizer: View Source

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

Tokenizer( dialect: Union[str, sqlglot.dialects.Dialect, Type[sqlglot.dialects.Dialect], NoneType] = None, use_rs_tokenizer: Optional[bool] = None, **opts: Any) View Source

    1020    def __init__(
    1021        self,
    1022        dialect: DialectType = None,
    1023        use_rs_tokenizer: t.Optional[bool] = None,
    1024        **opts: t.Any,
    1025    ) -> None:
    1026        from sqlglot.dialects import Dialect
    1027
    1028        self.dialect = Dialect.get_or_raise(dialect)
    1029
    1030        # initialize `use_rs_tokenizer`, and allow it to be overwritten per Tokenizer instance
    1031        self.use_rs_tokenizer = (
    1032            use_rs_tokenizer if use_rs_tokenizer is not None else USE_RS_TOKENIZER
    1033        )
    1034
    1035        if self.use_rs_tokenizer:
    1036            self._rs_dialect_settings = RsTokenizerDialectSettings(
    1037                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
    1038                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    1039                numbers_can_be_underscore_separated=self.dialect.NUMBERS_CAN_BE_UNDERSCORE_SEPARATED,
    1040            )
    1041
    1042        self.reset()

SINGLE_TOKENS = {'(': <TokenType.L_PAREN: 'L_PAREN'>, ')': <TokenType.R_PAREN: 'R_PAREN'>, '[': <TokenType.L_BRACKET: 'L_BRACKET'>, ']': <TokenType.R_BRACKET: 'R_BRACKET'>, '{': <TokenType.L_BRACE: 'L_BRACE'>, '}': <TokenType.R_BRACE: 'R_BRACE'>, '&': <TokenType.AMP: 'AMP'>, '^': <TokenType.CARET: 'CARET'>, ':': <TokenType.COLON: 'COLON'>, ',': <TokenType.COMMA: 'COMMA'>, '.': <TokenType.DOT: 'DOT'>, '-': <TokenType.DASH: 'DASH'>, '=': <TokenType.EQ: 'EQ'>, '>': <TokenType.GT: 'GT'>, '<': <TokenType.LT: 'LT'>, '%': <TokenType.MOD: 'MOD'>, '!': <TokenType.NOT: 'NOT'>, '|': <TokenType.PIPE: 'PIPE'>, '+': <TokenType.PLUS: 'PLUS'>, ';': <TokenType.SEMICOLON: 'SEMICOLON'>, '/': <TokenType.SLASH: 'SLASH'>, '\\': <TokenType.BACKSLASH: 'BACKSLASH'>, '*': <TokenType.STAR: 'STAR'>, '~': <TokenType.TILDA: 'TILDA'>, '?': <TokenType.PLACEHOLDER: 'PLACEHOLDER'>, '@': <TokenType.PARAMETER: 'PARAMETER'>, '#': <TokenType.HASH: 'HASH'>, "'": <TokenType.UNKNOWN: 'UNKNOWN'>, '`': <TokenType.UNKNOWN: 'UNKNOWN'>, '"': <TokenType.UNKNOWN: 'UNKNOWN'>}
BIT_STRINGS: List[Union[str, Tuple[str, str]]] = []
BYTE_STRINGS: List[Union[str, Tuple[str, str]]] = []
HEX_STRINGS: List[Union[str, Tuple[str, str]]] = []
RAW_STRINGS: List[Union[str, Tuple[str, str]]] = []
HEREDOC_STRINGS: List[Union[str, Tuple[str, str]]] = []
UNICODE_STRINGS: List[Union[str, Tuple[str, str]]] = []
IDENTIFIERS: List[Union[str, Tuple[str, str]]] = ['"']
QUOTES: List[Union[str, Tuple[str, str]]] = ["'"]
STRING_ESCAPES = ["'"]
VAR_SINGLE_TOKENS: Set[str] = set()
IDENTIFIER_ESCAPES: List[str] = []
HEREDOC_TAG_IS_IDENTIFIER = False
HEREDOC_STRING_ALTERNATIVE = <TokenType.VAR: 'VAR'>
STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS = True
NESTED_COMMENTS = True
HINT_START = '/*+'
TOKENS_PRECEDING_HINT = {<TokenType.INSERT: 'INSERT'>, <TokenType.SELECT: 'SELECT'>, <TokenType.DELETE: 'DELETE'>, <TokenType.UPDATE: 'UPDATE'>}
KEYWORDS: Dict[str, TokenType] = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '|>': <TokenType.PIPE_GT: 'PIPE_GT'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, ':=': <TokenType.COLON_EQ: 'COLON_EQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, '??': <TokenType.DQMARK: 'DQMARK'>, '~~~': <TokenType.GLOB: 'GLOB'>, '~~': <TokenType.LIKE: 'LIKE'>, '~~*': <TokenType.ILIKE: 'ILIKE'>, '~*': <TokenType.IRLIKE: 'IRLIKE'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'COPY': <TokenType.COPY: 'COPY'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_SCHEMA': <TokenType.CURRENT_SCHEMA: 'CURRENT_SCHEMA'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ENUM': <TokenType.ENUM: 'ENUM'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'KILL': <TokenType.KILL: 'KILL'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NAMESPACE': <TokenType.NAMESPACE: 'NAMESPACE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'RENAME': <TokenType.RENAME: 'RENAME'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'START WITH': <TokenType.START_WITH: 'START_WITH'>, 'STRAIGHT_JOIN': <TokenType.STRAIGHT_JOIN: 'STRAIGHT_JOIN'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'TRUNCATE': <TokenType.TRUNCATE: 'TRUNCATE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'MEDIUMINT': <TokenType.MEDIUMINT: 'MEDIUMINT'>, 'INT1': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'INT16': <TokenType.SMALLINT: 'SMALLINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'HUGEINT': <TokenType.INT128: 'INT128'>, 'UHUGEINT': <TokenType.UINT128: 'UINT128'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'INT32': <TokenType.INT: 'INT'>, 'INT64': <TokenType.BIGINT: 'BIGINT'>, 'INT128': <TokenType.INT128: 'INT128'>, 'INT256': <TokenType.INT256: 'INT256'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.TINYINT: 'TINYINT'>, 'UINT': <TokenType.UINT: 'UINT'>, 'UINT128': <TokenType.UINT128: 'UINT128'>, 'UINT256': <TokenType.UINT256: 'UINT256'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL32': <TokenType.DECIMAL32: 'DECIMAL32'>, 'DECIMAL64': <TokenType.DECIMAL64: 'DECIMAL64'>, 'DECIMAL128': <TokenType.DECIMAL128: 'DECIMAL128'>, 'DECIMAL256': <TokenType.DECIMAL256: 'DECIMAL256'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'LIST': <TokenType.LIST: 'LIST'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'JSONB': <TokenType.JSONB: 'JSONB'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'CHAR VARYING': <TokenType.VARCHAR: 'VARCHAR'>, 'CHARACTER VARYING': <TokenType.VARCHAR: 'VARCHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'BPCHAR': <TokenType.BPCHAR: 'BPCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMP_LTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMPNTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'TIMESTAMP_NTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'VECTOR': <TokenType.VECTOR: 'VECTOR'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'SEQUENCE': <TokenType.SEQUENCE: 'SEQUENCE'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.ANALYZE: 'ANALYZE'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.GRANT: 'GRANT'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>}
WHITE_SPACE: Dict[Optional[str], TokenType] = {' ': <TokenType.SPACE: 'SPACE'>, '\t': <TokenType.SPACE: 'SPACE'>, '\n': <TokenType.BREAK: 'BREAK'>, '\r': <TokenType.BREAK: 'BREAK'>}
COMMANDS = {<TokenType.FETCH: 'FETCH'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.SHOW: 'SHOW'>, <TokenType.RENAME: 'RENAME'>}
COMMAND_PREFIX_TOKENS = {<TokenType.BEGIN: 'BEGIN'>, <TokenType.SEMICOLON: 'SEMICOLON'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
use_rs_tokenizer
def reset(self) -> None: View Source

    1044    def reset(self) -> None:
    1045        self.sql = ""
    1046        self.size = 0
    1047        self.tokens: t.List[Token] = []
    1048        self._start = 0
    1049        self._current = 0
    1050        self._line = 1
    1051        self._col = 0
    1052        self._comments: t.List[str] = []
    1053
    1054        self._char = ""
    1055        self._end = False
    1056        self._peek = ""
    1057        self._prev_token_line = -1

def tokenize(self, sql: str) -> List[Token]: View Source

    1059    def tokenize(self, sql: str) -> t.List[Token]:
    1060        """Returns a list of tokens corresponding to the SQL string `sql`."""
    1061        if self.use_rs_tokenizer:
    1062            return self.tokenize_rs(sql)
    1063
    1064        self.reset()
    1065        self.sql = sql
    1066        self.size = len(sql)
    1067
    1068        try:
    1069            self._scan()
    1070        except Exception as e:
    1071            start = max(self._current - 50, 0)
    1072            end = min(self._current + 50, self.size - 1)
    1073            context = self.sql[start:end]
    1074            raise TokenError(f"Error tokenizing '{context}'") from e
    1075
    1076        return self.tokens

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

def tokenize_rs(self, sql: str) -> List[Token]: View Source

    1513    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1514        if not self._RS_TOKENIZER:
    1515            raise SqlglotError("Rust tokenizer is not available")
    1516
    1517        tokens, error_msg = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1518        for token in tokens:
    1519            token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1520
    1521        # Setting this here so partial token lists can be inspected even if there is a failure
    1522        self.tokens = tokens
    1523
    1524        if error_msg is not None:
    1525            raise TokenError(error_msg)
    1526
    1527        return tokens

size
sql
tokens