# sqlglot.tokens API documentation

Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

An enumeration.

L_PAREN = <TokenType.L_PAREN: 'L_PAREN'>
R_PAREN = <TokenType.R_PAREN: 'R_PAREN'>
L_BRACKET = <TokenType.L_BRACKET: 'L_BRACKET'>
R_BRACKET = <TokenType.R_BRACKET: 'R_BRACKET'>
L_BRACE = <TokenType.L_BRACE: 'L_BRACE'>
R_BRACE = <TokenType.R_BRACE: 'R_BRACE'>
COMMA = <TokenType.COMMA: 'COMMA'>
DOT = <TokenType.DOT: 'DOT'>
DASH = <TokenType.DASH: 'DASH'>
PLUS = <TokenType.PLUS: 'PLUS'>
COLON = <TokenType.COLON: 'COLON'>
DOTCOLON = <TokenType.DOTCOLON: 'DOTCOLON'>
DCOLON = <TokenType.DCOLON: 'DCOLON'>
DQMARK = <TokenType.DQMARK: 'DQMARK'>
SEMICOLON = <TokenType.SEMICOLON: 'SEMICOLON'>
STAR = <TokenType.STAR: 'STAR'>
BACKSLASH = <TokenType.BACKSLASH: 'BACKSLASH'>
SLASH = <TokenType.SLASH: 'SLASH'>
LT = <TokenType.LT: 'LT'>
LTE = <TokenType.LTE: 'LTE'>
GT = <TokenType.GT: 'GT'>
GTE = <TokenType.GTE: 'GTE'>
NOT = <TokenType.NOT: 'NOT'>
EQ = <TokenType.EQ: 'EQ'>
NEQ = <TokenType.NEQ: 'NEQ'>
NULLSAFE_EQ = <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>
COLON_EQ = <TokenType.COLON_EQ: 'COLON_EQ'>
AND = <TokenType.AND: 'AND'>
OR = <TokenType.OR: 'OR'>
AMP = <TokenType.AMP: 'AMP'>
DPIPE = <TokenType.DPIPE: 'DPIPE'>
PIPE_GT = <TokenType.PIPE_GT: 'PIPE_GT'>
PIPE = <TokenType.PIPE: 'PIPE'>
PIPE_SLASH = <TokenType.PIPE_SLASH: 'PIPE_SLASH'>
DPIPE_SLASH = <TokenType.DPIPE_SLASH: 'DPIPE_SLASH'>
CARET = <TokenType.CARET: 'CARET'>
CARET_AT = <TokenType.CARET_AT: 'CARET_AT'>
TILDA = <TokenType.TILDA: 'TILDA'>
ARROW = <TokenType.ARROW: 'ARROW'>
DARROW = <TokenType.DARROW: 'DARROW'>
FARROW = <TokenType.FARROW: 'FARROW'>
HASH = <TokenType.HASH: 'HASH'>
HASH_ARROW = <TokenType.HASH_ARROW: 'HASH_ARROW'>
DHASH_ARROW = <TokenType.DHASH_ARROW: 'DHASH_ARROW'>
LR_ARROW = <TokenType.LR_ARROW: 'LR_ARROW'>
DAT = <TokenType.DAT: 'DAT'>
LT_AT = <TokenType.LT_AT: 'LT_AT'>
AT_GT = <TokenType.AT_GT: 'AT_GT'>
DOLLAR = <TokenType.DOLLAR: 'DOLLAR'>
PARAMETER = <TokenType.PARAMETER: 'PARAMETER'>
SESSION_PARAMETER = <TokenType.SESSION_PARAMETER: 'SESSION_PARAMETER'>
DAMP = <TokenType.DAMP: 'DAMP'>
XOR = <TokenType.XOR: 'XOR'>
DSTAR = <TokenType.DSTAR: 'DSTAR'>
URI_START = <TokenType.URI_START: 'URI_START'>
BLOCK_START = <TokenType.BLOCK_START: 'BLOCK_START'>
BLOCK_END = <TokenType.BLOCK_END: 'BLOCK_END'>
SPACE = <TokenType.SPACE: 'SPACE'>
BREAK = <TokenType.BREAK: 'BREAK'>
STRING = <TokenType.STRING: 'STRING'>
NUMBER = <TokenType.NUMBER: 'NUMBER'>
IDENTIFIER = <TokenType.IDENTIFIER: 'IDENTIFIER'>
DATABASE = <TokenType.DATABASE: 'DATABASE'>
COLUMN = <TokenType.COLUMN: 'COLUMN'>
COLUMN_DEF = <TokenType.COLUMN_DEF: 'COLUMN_DEF'>
SCHEMA = <TokenType.SCHEMA: 'SCHEMA'>
TABLE = <TokenType.TABLE: 'TABLE'>
WAREHOUSE = <TokenType.WAREHOUSE: 'WAREHOUSE'>
STAGE = <TokenType.STAGE: 'STAGE'>
STREAMLIT = <TokenType.STREAMLIT: 'STREAMLIT'>
VAR = <TokenType.VAR: 'VAR'>
BIT_STRING = <TokenType.BIT_STRING: 'BIT_STRING'>
HEX_STRING = <TokenType.HEX_STRING: 'HEX_STRING'>
BYTE_STRING = <TokenType.BYTE_STRING: 'BYTE_STRING'>
NATIONAL_STRING = <TokenType.NATIONAL_STRING: 'NATIONAL_STRING'>
RAW_STRING = <TokenType.RAW_STRING: 'RAW_STRING'>
HEREDOC_STRING = <TokenType.HEREDOC_STRING: 'HEREDOC_STRING'>
UNICODE_STRING = <TokenType.UNICODE_STRING: 'UNICODE_STRING'>
BIT = <TokenType.BIT: 'BIT'>
BOOLEAN = <TokenType.BOOLEAN: 'BOOLEAN'>
TINYINT = <TokenType.TINYINT: 'TINYINT'>
UTINYINT = <TokenType.UTINYINT: 'UTINYINT'>
SMALLINT = <TokenType.SMALLINT: 'SMALLINT'>
USMALLINT = <TokenType.USMALLINT: 'USMALLINT'>
MEDIUMINT = <TokenType.MEDIUMINT: 'MEDIUMINT'>
UMEDIUMINT = <TokenType.UMEDIUMINT: 'UMEDIUMINT'>
INT = <TokenType.INT: 'INT'>
UINT = <TokenType.UINT: 'UINT'>
BIGINT = <TokenType.BIGINT: 'BIGINT'>
UBIGINT = <TokenType.UBIGINT: 'UBIGINT'>
INT128 = <TokenType.INT128: 'INT128'>
UINT128 = <TokenType.UINT128: 'UINT128'>
INT256 = <TokenType.INT256: 'INT256'>
UINT256 = <TokenType.UINT256: 'UINT256'>
FLOAT = <TokenType.FLOAT: 'FLOAT'>
DOUBLE = <TokenType.DOUBLE: 'DOUBLE'>
UDOUBLE = <TokenType.UDOUBLE: 'UDOUBLE'>
DECIMAL = <TokenType.DECIMAL: 'DECIMAL'>
DECIMAL32 = <TokenType.DECIMAL32: 'DECIMAL32'>
DECIMAL64 = <TokenType.DECIMAL64: 'DECIMAL64'>
DECIMAL128 = <TokenType.DECIMAL128: 'DECIMAL128'>
DECIMAL256 = <TokenType.DECIMAL256: 'DECIMAL256'>
UDECIMAL = <TokenType.UDECIMAL: 'UDECIMAL'>
BIGDECIMAL = <TokenType.BIGDECIMAL: 'BIGDECIMAL'>
CHAR = <TokenType.CHAR: 'CHAR'>
NCHAR = <TokenType.NCHAR: 'NCHAR'>
VARCHAR = <TokenType.VARCHAR: 'VARCHAR'>
NVARCHAR = <TokenType.NVARCHAR: 'NVARCHAR'>
BPCHAR = <TokenType.BPCHAR: 'BPCHAR'>
TEXT = <TokenType.TEXT: 'TEXT'>
MEDIUMTEXT = <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <TokenType.LONGTEXT: 'LONGTEXT'>
BLOB = <TokenType.BLOB: 'BLOB'>
MEDIUMBLOB = <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <TokenType.LONGBLOB: 'LONGBLOB'>
TINYBLOB = <TokenType.TINYBLOB: 'TINYBLOB'>
TINYTEXT = <TokenType.TINYTEXT: 'TINYTEXT'>
NAME = <TokenType.NAME: 'NAME'>
BINARY = <TokenType.BINARY: 'BINARY'>
VARBINARY = <TokenType.VARBINARY: 'VARBINARY'>
JSON = <TokenType.JSON: 'JSON'>
JSONB = <TokenType.JSONB: 'JSONB'>
TIME = <TokenType.TIME: 'TIME'>
TIMETZ = <TokenType.TIMETZ: 'TIMETZ'>
TIMESTAMP = <TokenType.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPNTZ = <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>
TIMESTAMP_S = <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>
TIMESTAMP_MS = <TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>
TIMESTAMP_NS = <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>
DATETIME = <TokenType.DATETIME: 'DATETIME'>
DATETIME2 = <TokenType.DATETIME2: 'DATETIME2'>
DATETIME64 = <TokenType.DATETIME64: 'DATETIME64'>
SMALLDATETIME = <TokenType.SMALLDATETIME: 'SMALLDATETIME'>
DATE = <TokenType.DATE: 'DATE'>
DATE32 = <TokenType.DATE32: 'DATE32'>
INT4RANGE = <TokenType.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <TokenType.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <TokenType.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <TokenType.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <TokenType.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <TokenType.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>
UUID = <TokenType.UUID: 'UUID'>
GEOGRAPHY = <TokenType.GEOGRAPHY: 'GEOGRAPHY'>
NULLABLE = <TokenType.NULLABLE: 'NULLABLE'>
GEOMETRY = <TokenType.GEOMETRY: 'GEOMETRY'>
POINT = <TokenType.POINT: 'POINT'>
RING = <TokenType.RING: 'RING'>
LINESTRING = <TokenType.LINESTRING: 'LINESTRING'>
MULTILINESTRING = <TokenType.MULTILINESTRING: 'MULTILINESTRING'>
POLYGON = <TokenType.POLYGON: 'POLYGON'>
MULTIPOLYGON = <TokenType.MULTIPOLYGON: 'MULTIPOLYGON'>
HLLSKETCH = <TokenType.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <TokenType.HSTORE: 'HSTORE'>
SUPER = <TokenType.SUPER: 'SUPER'>
SERIAL = <TokenType.SERIAL: 'SERIAL'>
SMALLSERIAL = <TokenType.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <TokenType.BIGSERIAL: 'BIGSERIAL'>
XML = <TokenType.XML: 'XML'>
YEAR = <TokenType.YEAR: 'YEAR'>
USERDEFINED = <TokenType.USERDEFINED: 'USERDEFINED'>
MONEY = <TokenType.MONEY: 'MONEY'>
SMALLMONEY = <TokenType.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <TokenType.ROWVERSION: 'ROWVERSION'>
IMAGE = <TokenType.IMAGE: 'IMAGE'>
VARIANT = <TokenType.VARIANT: 'VARIANT'>
OBJECT = <TokenType.OBJECT: 'OBJECT'>
INET = <TokenType.INET: 'INET'>
IPADDRESS = <TokenType.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <TokenType.IPPREFIX: 'IPPREFIX'>
IPV4 = <TokenType.IPV4: 'IPV4'>
IPV6 = <TokenType.IPV6: 'IPV6'>
ENUM = <TokenType.ENUM: 'ENUM'>
ENUM8 = <TokenType.ENUM8: 'ENUM8'>
ENUM16 = <TokenType.ENUM16: 'ENUM16'>
FIXEDSTRING = <TokenType.FIXEDSTRING: 'FIXEDSTRING'>
LOWCARDINALITY = <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>
NESTED = <TokenType.NESTED: 'NESTED'>
AGGREGATEFUNCTION = <TokenType.AGGREGATEFUNCTION: 'AGGREGATEFUNCTION'>
SIMPLEAGGREGATEFUNCTION = <TokenType.SIMPLEAGGREGATEFUNCTION: 'SIMPLEAGGREGATEFUNCTION'>
TDIGEST = <TokenType.TDIGEST: 'TDIGEST'>
UNKNOWN = <TokenType.UNKNOWN: 'UNKNOWN'>
VECTOR = <TokenType.VECTOR: 'VECTOR'>
DYNAMIC = <TokenType.DYNAMIC: 'DYNAMIC'>
VOID = <TokenType.VOID: 'VOID'>
ALIAS = <TokenType.ALIAS: 'ALIAS'>
ALTER = <TokenType.ALTER: 'ALTER'>
ALWAYS = <TokenType.ALWAYS: 'ALWAYS'>
ALL = <TokenType.ALL: 'ALL'>
ANTI = <TokenType.ANTI: 'ANTI'>
ANY = <TokenType.ANY: 'ANY'>
APPLY = <TokenType.APPLY: 'APPLY'>
ARRAY = <TokenType.ARRAY: 'ARRAY'>
ASC = <TokenType.ASC: 'ASC'>
ASOF = <TokenType.ASOF: 'ASOF'>
ATTACH = <TokenType.ATTACH: 'ATTACH'>
AUTO_INCREMENT = <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>
BEGIN = <TokenType.BEGIN: 'BEGIN'>
BETWEEN = <TokenType.BETWEEN: 'BETWEEN'>
BULK_COLLECT_INTO = <TokenType.BULK_COLLECT_INTO: 'BULK_COLLECT_INTO'>
CACHE = <TokenType.CACHE: 'CACHE'>
CASE = <TokenType.CASE: 'CASE'>
CHARACTER_SET = <TokenType.CHARACTER_SET: 'CHARACTER_SET'>
CLUSTER_BY = <TokenType.CLUSTER_BY: 'CLUSTER_BY'>
COLLATE = <TokenType.COLLATE: 'COLLATE'>
COMMAND = <TokenType.COMMAND: 'COMMAND'>
COMMENT = <TokenType.COMMENT: 'COMMENT'>
COMMIT = <TokenType.COMMIT: 'COMMIT'>
CONNECT_BY = <TokenType.CONNECT_BY: 'CONNECT_BY'>
CONSTRAINT = <TokenType.CONSTRAINT: 'CONSTRAINT'>
COPY = <TokenType.COPY: 'COPY'>
CREATE = <TokenType.CREATE: 'CREATE'>
CROSS = <TokenType.CROSS: 'CROSS'>
CUBE = <TokenType.CUBE: 'CUBE'>
CURRENT_DATE = <TokenType.CURRENT_DATE: 'CURRENT_DATE'>
CURRENT_DATETIME = <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>
CURRENT_SCHEMA = <TokenType.CURRENT_SCHEMA: 'CURRENT_SCHEMA'>
CURRENT_TIME = <TokenType.CURRENT_TIME: 'CURRENT_TIME'>
CURRENT_TIMESTAMP = <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>
CURRENT_USER = <TokenType.CURRENT_USER: 'CURRENT_USER'>
DECLARE = <TokenType.DECLARE: 'DECLARE'>
DEFAULT = <TokenType.DEFAULT: 'DEFAULT'>
DELETE = <TokenType.DELETE: 'DELETE'>
DESC = <TokenType.DESC: 'DESC'>
DESCRIBE = <TokenType.DESCRIBE: 'DESCRIBE'>
DETACH = <TokenType.DETACH: 'DETACH'>
DICTIONARY = <TokenType.DICTIONARY: 'DICTIONARY'>
DISTINCT = <TokenType.DISTINCT: 'DISTINCT'>
DISTRIBUTE_BY = <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>
DIV = <TokenType.DIV: 'DIV'>
DROP = <TokenType.DROP: 'DROP'>
ELSE = <TokenType.ELSE: 'ELSE'>
END = <TokenType.END: 'END'>
ESCAPE = <TokenType.ESCAPE: 'ESCAPE'>
EXCEPT = <TokenType.EXCEPT: 'EXCEPT'>
EXECUTE = <TokenType.EXECUTE: 'EXECUTE'>
EXISTS = <TokenType.EXISTS: 'EXISTS'>
FALSE = <TokenType.FALSE: 'FALSE'>
FETCH = <TokenType.FETCH: 'FETCH'>
FILE_FORMAT = <TokenType.FILE_FORMAT: 'FILE_FORMAT'>
FILTER = <TokenType.FILTER: 'FILTER'>
FINAL = <TokenType.FINAL: 'FINAL'>
FIRST = <TokenType.FIRST: 'FIRST'>
FOR = <TokenType.FOR: 'FOR'>
FORCE = <TokenType.FORCE: 'FORCE'>
FOREIGN_KEY = <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>
FORMAT = <TokenType.FORMAT: 'FORMAT'>
FROM = <TokenType.FROM: 'FROM'>
FULL = <TokenType.FULL: 'FULL'>
FUNCTION = <TokenType.FUNCTION: 'FUNCTION'>
GET = <TokenType.GET: 'GET'>
GLOB = <TokenType.GLOB: 'GLOB'>
GLOBAL = <TokenType.GLOBAL: 'GLOBAL'>
GRANT = <TokenType.GRANT: 'GRANT'>
GROUP_BY = <TokenType.GROUP_BY: 'GROUP_BY'>
GROUPING_SETS = <TokenType.GROUPING_SETS: 'GROUPING_SETS'>
HAVING = <TokenType.HAVING: 'HAVING'>
HINT = <TokenType.HINT: 'HINT'>
IGNORE = <TokenType.IGNORE: 'IGNORE'>
ILIKE = <TokenType.ILIKE: 'ILIKE'>
ILIKE_ANY = <TokenType.ILIKE_ANY: 'ILIKE_ANY'>
IN = <TokenType.IN: 'IN'>
INDEX = <TokenType.INDEX: 'INDEX'>
INNER = <TokenType.INNER: 'INNER'>
INSERT = <TokenType.INSERT: 'INSERT'>
INTERSECT = <TokenType.INTERSECT: 'INTERSECT'>
INTERVAL = <TokenType.INTERVAL: 'INTERVAL'>
INTO = <TokenType.INTO: 'INTO'>
INTRODUCER = <TokenType.INTRODUCER: 'INTRODUCER'>
IRLIKE = <TokenType.IRLIKE: 'IRLIKE'>
IS = <TokenType.IS: 'IS'>
ISNULL = <TokenType.ISNULL: 'ISNULL'>
JOIN = <TokenType.JOIN: 'JOIN'>
JOIN_MARKER = <TokenType.JOIN_MARKER: 'JOIN_MARKER'>
KEEP = <TokenType.KEEP: 'KEEP'>
KEY = <TokenType.KEY: 'KEY'>
KILL = <TokenType.KILL: 'KILL'>
LANGUAGE = <TokenType.LANGUAGE: 'LANGUAGE'>
LATERAL = <TokenType.LATERAL: 'LATERAL'>
LEFT = <TokenType.LEFT: 'LEFT'>
LIKE = <TokenType.LIKE: 'LIKE'>
LIKE_ANY = <TokenType.LIKE_ANY: 'LIKE_ANY'>
LIMIT = <TokenType.LIMIT: 'LIMIT'>
LIST = <TokenType.LIST: 'LIST'>
LOAD = <TokenType.LOAD: 'LOAD'>
LOCK = <TokenType.LOCK: 'LOCK'>
MAP = <TokenType.MAP: 'MAP'>
MATCH_CONDITION = <TokenType.MATCH_CONDITION: 'MATCH_CONDITION'>
MATCH_RECOGNIZE = <TokenType.MATCH_RECOGNIZE: 'MATCH_RECOGNIZE'>
MEMBER_OF = <TokenType.MEMBER_OF: 'MEMBER_OF'>
MERGE = <TokenType.MERGE: 'MERGE'>
MOD = <TokenType.MOD: 'MOD'>
MODEL = <TokenType.MODEL: 'MODEL'>
NATURAL = <TokenType.NATURAL: 'NATURAL'>
NEXT = <TokenType.NEXT: 'NEXT'>
NOTHING = <TokenType.NOTHING: 'NOTHING'>
NOTNULL = <TokenType.NOTNULL: 'NOTNULL'>
NULL = <TokenType.NULL: 'NULL'>
OBJECT_IDENTIFIER = <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>
OFFSET = <TokenType.OFFSET: 'OFFSET'>
ON = <TokenType.ON: 'ON'>
ONLY = <TokenType.ONLY: 'ONLY'>
OPERATOR = <TokenType.OPERATOR: 'OPERATOR'>
ORDER_BY = <TokenType.ORDER_BY: 'ORDER_BY'>
ORDER_SIBLINGS_BY = <TokenType.ORDER_SIBLINGS_BY: 'ORDER_SIBLINGS_BY'>
ORDERED = <TokenType.ORDERED: 'ORDERED'>
ORDINALITY = <TokenType.ORDINALITY: 'ORDINALITY'>
OUTER = <TokenType.OUTER: 'OUTER'>
OVER = <TokenType.OVER: 'OVER'>
OVERLAPS = <TokenType.OVERLAPS: 'OVERLAPS'>
OVERWRITE = <TokenType.OVERWRITE: 'OVERWRITE'>
PARTITION = <TokenType.PARTITION: 'PARTITION'>
PARTITION_BY = <TokenType.PARTITION_BY: 'PARTITION_BY'>
PERCENT = <TokenType.PERCENT: 'PERCENT'>
PIVOT = <TokenType.PIVOT: 'PIVOT'>
PLACEHOLDER = <TokenType.PLACEHOLDER: 'PLACEHOLDER'>
POSITIONAL = <TokenType.POSITIONAL: 'POSITIONAL'>
PRAGMA = <TokenType.PRAGMA: 'PRAGMA'>
PREWHERE = <TokenType.PREWHERE: 'PREWHERE'>
PRIMARY_KEY = <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>
PROCEDURE = <TokenType.PROCEDURE: 'PROCEDURE'>
PROPERTIES = <TokenType.PROPERTIES: 'PROPERTIES'>
PSEUDO_TYPE = <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>
PUT = <TokenType.PUT: 'PUT'>
QUALIFY = <TokenType.QUALIFY: 'QUALIFY'>
QUOTE = <TokenType.QUOTE: 'QUOTE'>
RANGE = <TokenType.RANGE: 'RANGE'>
RECURSIVE = <TokenType.RECURSIVE: 'RECURSIVE'>
REFRESH = <TokenType.REFRESH: 'REFRESH'>
RENAME = <TokenType.RENAME: 'RENAME'>
REPLACE = <TokenType.REPLACE: 'REPLACE'>
RETURNING = <TokenType.RETURNING: 'RETURNING'>
REFERENCES = <TokenType.REFERENCES: 'REFERENCES'>
RIGHT = <TokenType.RIGHT: 'RIGHT'>
RLIKE = <TokenType.RLIKE: 'RLIKE'>
ROLLBACK = <TokenType.ROLLBACK: 'ROLLBACK'>
ROLLUP = <TokenType.ROLLUP: 'ROLLUP'>
ROW = <TokenType.ROW: 'ROW'>
ROWS = <TokenType.ROWS: 'ROWS'>
SELECT = <TokenType.SELECT: 'SELECT'>
SEMI = <TokenType.SEMI: 'SEMI'>
SEPARATOR = <TokenType.SEPARATOR: 'SEPARATOR'>
SEQUENCE = <TokenType.SEQUENCE: 'SEQUENCE'>
SERDE_PROPERTIES = <TokenType.SERDE_PROPERTIES: 'SERDE_PROPERTIES'>
SET = <TokenType.SET: 'SET'>
SETTINGS = <TokenType.SETTINGS: 'SETTINGS'>
SHOW = <TokenType.SHOW: 'SHOW'>
SIMILAR_TO = <TokenType.SIMILAR_TO: 'SIMILAR_TO'>
SOME = <TokenType.SOME: 'SOME'>
SORT_BY = <TokenType.SORT_BY: 'SORT_BY'>
START_WITH = <TokenType.START_WITH: 'START_WITH'>
STORAGE_INTEGRATION = <TokenType.STORAGE_INTEGRATION: 'STORAGE_INTEGRATION'>
STRAIGHT_JOIN = <TokenType.STRAIGHT_JOIN: 'STRAIGHT_JOIN'>
STRUCT = <TokenType.STRUCT: 'STRUCT'>
SUMMARIZE = <TokenType.SUMMARIZE: 'SUMMARIZE'>
TABLE_SAMPLE = <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>
TAG = <TokenType.TAG: 'TAG'>
TEMPORARY = <TokenType.TEMPORARY: 'TEMPORARY'>
TOP = <TokenType.TOP: 'TOP'>
THEN = <TokenType.THEN: 'THEN'>
TRUE = <TokenType.TRUE: 'TRUE'>
TRUNCATE = <TokenType.TRUNCATE: 'TRUNCATE'>
UNCACHE = <TokenType.UNCACHE: 'UNCACHE'>
UNION = <TokenType.UNION: 'UNION'>
UNNEST = <TokenType.UNNEST: 'UNNEST'>
UNPIVOT = <TokenType.UNPIVOT: 'UNPIVOT'>
UPDATE = <TokenType.UPDATE: 'UPDATE'>
USE = <TokenType.USE: 'USE'>
USING = <TokenType.USING: 'USING'>
VALUES = <TokenType.VALUES: 'VALUES'>
VIEW = <TokenType.VIEW: 'VIEW'>
VOLATILE = <TokenType.VOLATILE: 'VOLATILE'>
WHEN = <TokenType.WHEN: 'WHEN'>
WHERE = <TokenType.WHERE: 'WHERE'>
WINDOW = <TokenType.WINDOW: 'WINDOW'>
WITH = <TokenType.WITH: 'WITH'>
UNIQUE = <TokenType.UNIQUE: 'UNIQUE'>
VERSION_SNAPSHOT = <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>
TIMESTAMP_SNAPSHOT = <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>
OPTION = <TokenType.OPTION: 'OPTION'>
SINK = <TokenType.SINK: 'SINK'>
SOURCE = <TokenType.SOURCE: 'SOURCE'>
ANALYZE = <TokenType.ANALYZE: 'ANALYZE'>
NAMESPACE = <TokenType.NAMESPACE: 'NAMESPACE'>
EXPORT = <TokenType.EXPORT: 'EXPORT'>
class Token: View Source

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

size
sql
tokens