Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

An enumeration.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    1011    def __init__(
    1012        self, dialect: DialectType = None, use_rs_tokenizer: t.Optional[bool] = None
    1013    ) -> None:
    1014        from sqlglot.dialects import Dialect
    1015
    1016        self.dialect = Dialect.get_or_raise(dialect)
    1017
    1018        # initialize `use_rs_tokenizer`, and allow it to be overwritten per Tokenizer instance
    1019        self.use_rs_tokenizer = (
    1020            use_rs_tokenizer if use_rs_tokenizer is not None else USE_RS_TOKENIZER
    1021        )
    1022
    1023        if self.use_rs_tokenizer:
    1024            self._rs_dialect_settings = RsTokenizerDialectSettings(
    1025                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
    1026                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    1027                numbers_can_be_underscore_separated=self.dialect.NUMBERS_CAN_BE_UNDERSCORE_SEPARATED,
    1028            )
    1029
    1030        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.UPDATE: 'UPDATE'>, <TokenType.SELECT: 'SELECT'>, <TokenType.DELETE: 'DELETE'>, <TokenType.INSERT: 'INSERT'>}
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.EXECUTE: 'EXECUTE'>, <TokenType.SHOW: 'SHOW'>, <TokenType.FETCH: 'FETCH'>, <TokenType.RENAME: 'RENAME'>, <TokenType.COMMAND: 'COMMAND'>}
COMMAND_PREFIX_TOKENS = {<TokenType.SEMICOLON: 'SEMICOLON'>, <TokenType.BEGIN: 'BEGIN'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
use_rs_tokenizer
def reset(self) -> None: View Source

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

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

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

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

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

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

size
sql
tokens