Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

An enumeration.

L_PAREN = <TokenType.L_PAREN: 'L_PAREN'>
R_PAREN = <TokenType.R_PAREN: 'R_PAREN'>
L_BRACKET = <TokenType.L_BRACKET: 'L_BRACKET'>
R_BRACKET = <TokenType.R_BRACKET: 'R_BRACKET'>
L_BRACE = <TokenType.L_BRACE: 'L_BRACE'>
R_BRACE = <TokenType.R_BRACE: 'R_BRACE'>
COMMA = <TokenType.COMMA: 'COMMA'>
DOT = <TokenType.DOT: 'DOT'>
DASH = <TokenType.DASH: 'DASH'>
PLUS = <TokenType.PLUS: 'PLUS'>
COLON = <TokenType.COLON: 'COLON'>
DOTCOLON = <TokenType.DOTCOLON: 'DOTCOLON'>
DCOLON = <TokenType.DCOLON: 'DCOLON'>
DQMARK = <TokenType.DQMARK: 'DQMARK'>
SEMICOLON = <TokenType.SEMICOLON: 'SEMICOLON'>
STAR = <TokenType.STAR: 'STAR'>
BACKSLASH = <TokenType.BACKSLASH: 'BACKSLASH'>
SLASH = <TokenType.SLASH: 'SLASH'>
LT = <TokenType.LT: 'LT'>
LTE = <TokenType.LTE: 'LTE'>
GT = <TokenType.GT: 'GT'>
GTE = <TokenType.GTE: 'GTE'>
NOT = <TokenType.NOT: 'NOT'>
EQ = <TokenType.EQ: 'EQ'>
NEQ = <TokenType.NEQ: 'NEQ'>
NULLSAFE_EQ = <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>
COLON_EQ = <TokenType.COLON_EQ: 'COLON_EQ'>
AND = <TokenType.AND: 'AND'>
OR = <TokenType.OR: 'OR'>
AMP = <TokenType.AMP: 'AMP'>
DPIPE = <TokenType.DPIPE: 'DPIPE'>
PIPE = <TokenType.PIPE: 'PIPE'>
PIPE_SLASH = <TokenType.PIPE_SLASH: 'PIPE_SLASH'>
DPIPE_SLASH = <TokenType.DPIPE_SLASH: 'DPIPE_SLASH'>
CARET = <TokenType.CARET: 'CARET'>
CARET_AT = <TokenType.CARET_AT: 'CARET_AT'>
TILDA = <TokenType.TILDA: 'TILDA'>
ARROW = <TokenType.ARROW: 'ARROW'>
DARROW = <TokenType.DARROW: 'DARROW'>
FARROW = <TokenType.FARROW: 'FARROW'>
HASH = <TokenType.HASH: 'HASH'>
HASH_ARROW = <TokenType.HASH_ARROW: 'HASH_ARROW'>
DHASH_ARROW = <TokenType.DHASH_ARROW: 'DHASH_ARROW'>
LR_ARROW = <TokenType.LR_ARROW: 'LR_ARROW'>
DAT = <TokenType.DAT: 'DAT'>
LT_AT = <TokenType.LT_AT: 'LT_AT'>
AT_GT = <TokenType.AT_GT: 'AT_GT'>
DOLLAR = <TokenType.DOLLAR: 'DOLLAR'>
PARAMETER = <TokenType.PARAMETER: 'PARAMETER'>
SESSION_PARAMETER = <TokenType.SESSION_PARAMETER: 'SESSION_PARAMETER'>
DAMP = <TokenType.DAMP: 'DAMP'>
XOR = <TokenType.XOR: 'XOR'>
DSTAR = <TokenType.DSTAR: 'DSTAR'>
URI_START = <TokenType.URI_START: 'URI_START'>
BLOCK_START = <TokenType.BLOCK_START: 'BLOCK_START'>
BLOCK_END = <TokenType.BLOCK_END: 'BLOCK_END'>
SPACE = <TokenType.SPACE: 'SPACE'>
BREAK = <TokenType.BREAK: 'BREAK'>
STRING = <TokenType.STRING: 'STRING'>
NUMBER = <TokenType.NUMBER: 'NUMBER'>
IDENTIFIER = <TokenType.IDENTIFIER: 'IDENTIFIER'>
DATABASE = <TokenType.DATABASE: 'DATABASE'>
COLUMN = <TokenType.COLUMN: 'COLUMN'>
COLUMN_DEF = <TokenType.COLUMN_DEF: 'COLUMN_DEF'>
SCHEMA = <TokenType.SCHEMA: 'SCHEMA'>
TABLE = <TokenType.TABLE: 'TABLE'>
WAREHOUSE = <TokenType.WAREHOUSE: 'WAREHOUSE'>
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'>
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'>
FILTER = <TokenType.FILTER: 'FILTER'>
FINAL = <TokenType.FINAL: 'FINAL'>
FIRST = <TokenType.FIRST: 'FIRST'>
FOR = <TokenType.FOR: 'FOR'>
FORCE = <TokenType.FORCE: 'FORCE'>
FOREIGN_KEY = <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>
FORMAT = <TokenType.FORMAT: 'FORMAT'>
FROM = <TokenType.FROM: 'FROM'>
FULL = <TokenType.FULL: 'FULL'>
FUNCTION = <TokenType.FUNCTION: 'FUNCTION'>
GLOB = <TokenType.GLOB: 'GLOB'>
GLOBAL = <TokenType.GLOBAL: 'GLOBAL'>
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'>
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

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

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

    433    @classmethod
    434    def number(cls, number: int) -> Token:
    435        """Returns a NUMBER token with `number` as its text."""
    436        return cls(TokenType.NUMBER, str(number))

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

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

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

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

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

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

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

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

    448    @classmethod
    449    def var(cls, var: str) -> Token:
    450        """Returns an VAR token with `var` as its text."""
    451        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

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

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

    1008    def __init__(
    1009        self, dialect: DialectType = None, use_rs_tokenizer: t.Optional[bool] = None
    1010    ) -> None:
    1011        from sqlglot.dialects import Dialect
    1012
    1013        self.dialect = Dialect.get_or_raise(dialect)
    1014
    1015        # initialize `use_rs_tokenizer`, and allow it to be overwritten per Tokenizer instance
    1016        self.use_rs_tokenizer = (
    1017            use_rs_tokenizer if use_rs_tokenizer is not None else USE_RS_TOKENIZER
    1018        )
    1019
    1020        if self.use_rs_tokenizer:
    1021            self._rs_dialect_settings = RsTokenizerDialectSettings(
    1022                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
    1023                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    1024                numbers_can_be_underscore_separated=self.dialect.NUMBERS_CAN_BE_UNDERSCORE_SEPARATED,
    1025            )
    1026
    1027        self.reset()

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

    1029    def reset(self) -> None:
    1030        self.sql = ""
    1031        self.size = 0
    1032        self.tokens: t.List[Token] = []
    1033        self._start = 0
    1034        self._current = 0
    1035        self._line = 1
    1036        self._col = 0
    1037        self._comments: t.List[str] = []
    1038
    1039        self._char = ""
    1040        self._end = False
    1041        self._peek = ""
    1042        self._prev_token_line = -1

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

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

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

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

    1498    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1499        if not self._RS_TOKENIZER:
    1500            raise SqlglotError("Rust tokenizer is not available")
    1501
    1502        try:
    1503            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1504            for token in tokens:
    1505                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1506            return tokens
    1507        except Exception as e:
    1508            raise TokenError(str(e))

size
sql
tokens