sqlglot.tokens API documentation

Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

An enumeration.

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

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

Token( token_type: TokenType, text: str, line: int = 1, col: int = 1, start: int = 0, end: int = 0, comments: Optional[List[str]] = None) View Source

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

Token initializer.

###### Arguments:

- token_type: The TokenType Enum.
- text: The text of the token.
- line: The line that the token ends on.
- col: The column that the token ends on.
- start: The start index of the token.
- end: The ending index of the token.
- comments: The comments to attach to the token.

@classmethod
def number(cls, number: int) -> Token: View Source

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

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

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

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

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

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

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

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

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

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

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

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

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

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

SINGLE_TOKENS = {'(': <TokenType.L_PAREN: 'L_PAREN'>, ')': <TokenType.R_PAREN: 'R_PAREN'>, '[': <TokenType.L_BRACKET: 'L_BRACKET'>, ']': <TokenType.R_BRACKET: 'R_BRACKET'>, '{': <TokenType.L_BRACE: 'L_BRACE'>, '}': <TokenType.R_BRACE: 'R_BRACE'>, '&': <TokenType.AMP: 'AMP'>, '^': <TokenType.CARET: 'CARET'>, ':': <TokenType.COLON: 'COLON'>, ',': <TokenType.COMMA: 'COMMA'>, '.': <TokenType.DOT: 'DOT'>, '-': <TokenType.DASH: 'DASH'>, '=': <TokenType.EQ: 'EQ'>, '>': <TokenType.GT: 'GT'>, '<': <TokenType.LT: 'LT'>, '%': <TokenType.MOD: 'MOD'>, '!': <TokenType.NOT: 'NOT'>, '|': <TokenType.PIPE: 'PIPE'>, '+': <TokenType.PLUS: 'PLUS'>, ';': <TokenType.SEMICOLON: 'SEMICOLON'>, '/': <TokenType.SLASH: 'SLASH'>, '\\': <TokenType.BACKSLASH: 'BACKSLASH'>, '*': <TokenType.STAR: 'STAR'>, '~': <TokenType.TILDA: 'TILDA'>, '?': <TokenType.PLACEHOLDER: 'PLACEHOLDER'>, '@': <TokenType.PARAMETER: 'PARAMETER'>, '#': <TokenType.HASH: 'HASH'>, "'": <TokenType.UNKNOWN: 'UNKNOWN'>, '`': <TokenType.UNKNOWN: 'UNKNOWN'>, '"': <TokenType.UNKNOWN: 'UNKNOWN'>}
BIT_STRINGS: List[Union[str, Tuple[str, str]]] = []
BYTE_STRINGS: List[Union[str, Tuple[str, str]]] = []
HEX_STRINGS: List[Union[str, Tuple[str, str]]] = []
RAW_STRINGS: List[Union[str, Tuple[str, str]]] = []
HEREDOC_STRINGS: List[Union[str, Tuple[str, str]]] = []
UNICODE_STRINGS: List[Union[str, Tuple[str, str]]] = []
IDENTIFIERS: List[Union[str, Tuple[str, str]]] = ['"']
QUOTES: List[Union[str, Tuple[str, str]]] = ["'"]
STRING_ESCAPES = ["'"]
VAR_SINGLE_TOKENS: Set[str] = set()
IDENTIFIER_ESCAPES: List[str] = []
HEREDOC_TAG_IS_IDENTIFIER = False
HEREDOC_STRING_ALTERNATIVE = <TokenType.VAR: 'VAR'>
STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS = True
NESTED_COMMENTS = True
HINT_START = '/*+'
TOKENS_PRECEDING_HINT = {<TokenType.DELETE: 'DELETE'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.INSERT: 'INSERT'>, <TokenType.SELECT: 'SELECT'>}
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.FETCH: 'FETCH'>, <TokenType.SHOW: 'SHOW'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.RENAME: 'RENAME'>}
COMMAND_PREFIX_TOKENS = {<TokenType.BEGIN: 'BEGIN'>, <TokenType.SEMICOLON: 'SEMICOLON'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
use_rs_tokenizer
def reset(self) -> None: View Source

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

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

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

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

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

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

size
sql
tokens