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

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 = 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()

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 = <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'>
class Token: View Source

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

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

    438    @classmethod
    439    def number(cls, number: int) -> Token:
    440        """Returns a NUMBER token with `number` as its text."""
    441        return cls(TokenType.NUMBER, str(number))

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

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

    443    @classmethod
    444    def string(cls, string: str) -> Token:
    445        """Returns a STRING token with `string` as its text."""
    446        return cls(TokenType.STRING, string)

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

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

    448    @classmethod
    449    def identifier(cls, identifier: str) -> Token:
    450        """Returns an IDENTIFIER token with `identifier` as its text."""
    451        return cls(TokenType.IDENTIFIER, identifier)

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

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

    453    @classmethod
    454    def var(cls, var: str) -> Token:
    455        """Returns an VAR token with `var` as its text."""
    456        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

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

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

    1015    def __init__(
    1016        self, dialect: DialectType = None, use_rs_tokenizer: t.Optional[bool] = None
    1017    ) -> None:
    1018        from sqlglot.dialects import Dialect
    1019
    1020        self.dialect = Dialect.get_or_raise(dialect)
    1021
    1022        # initialize `use_rs_tokenizer`, and allow it to be overwritten per Tokenizer instance
    1023        self.use_rs_tokenizer = (
    1024            use_rs_tokenizer if use_rs_tokenizer is not None else USE_RS_TOKENIZER
    1025        )
    1026
    1027        if self.use_rs_tokenizer:
    1028            self._rs_dialect_settings = RsTokenizerDialectSettings(
    1029                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
    1030                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    1031                numbers_can_be_underscore_separated=self.dialect.NUMBERS_CAN_BE_UNDERSCORE_SEPARATED,
    1032            )
    1033
    1034        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.UPDATE: 'UPDATE'>, <TokenType.SELECT: 'SELECT'>, <TokenType.DELETE: 'DELETE'>}
KEYWORDS: Dict[str, TokenType] = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, ':=': <TokenType.COLON_EQ: 'COLON_EQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, '??': <TokenType.DQMARK: 'DQMARK'>, '~~~': <TokenType.GLOB: 'GLOB'>, '~~': <TokenType.LIKE: 'LIKE'>, '~~*': <TokenType.ILIKE: 'ILIKE'>, '~*': <TokenType.IRLIKE: 'IRLIKE'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'COPY': <TokenType.COPY: 'COPY'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_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.COMMAND: 'COMMAND'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.RENAME: 'RENAME'>, <TokenType.FETCH: 'FETCH'>, <TokenType.SHOW: 'SHOW'>}
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

    1036    def reset(self) -> None:
    1037        self.sql = ""
    1038        self.size = 0
    1039        self.tokens: t.List[Token] = []
    1040        self._start = 0
    1041        self._current = 0
    1042        self._line = 1
    1043        self._col = 0
    1044        self._comments: t.List[str] = []
    1045
    1046        self._char = ""
    1047        self._end = False
    1048        self._peek = ""
    1049        self._prev_token_line = -1

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

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

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

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

    1505    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1506        if not self._RS_TOKENIZER:
    1507            raise SqlglotError("Rust tokenizer is not available")
    1508
    1509        try:
    1510            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1511            for token in tokens:
    1512                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1513            return tokens
    1514        except Exception as e:
    1515            raise TokenError(str(e))

size
sql
tokens