Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

An enumeration.

L_PAREN = <TokenType.L_PAREN: 'L_PAREN'>
R_PAREN = <TokenType.R_PAREN: 'R_PAREN'>
L_BRACKET = <TokenType.L_BRACKET: 'L_BRACKET'>
R_BRACKET = <TokenType.R_BRACKET: 'R_BRACKET'>
L_BRACE = <TokenType.L_BRACE: 'L_BRACE'>
R_BRACE = <TokenType.R_BRACE: 'R_BRACE'>
COMMA = <TokenType.COMMA: 'COMMA'>
DOT = <TokenType.DOT: 'DOT'>
DASH = <TokenType.DASH: 'DASH'>
PLUS = <TokenType.PLUS: 'PLUS'>
COLON = <TokenType.COLON: 'COLON'>
DOTCOLON = <TokenType.DOTCOLON: 'DOTCOLON'>
DCOLON = <TokenType.DCOLON: 'DCOLON'>
DQMARK = <TokenType.DQMARK: 'DQMARK'>
SEMICOLON = <TokenType.SEMICOLON: 'SEMICOLON'>
STAR = <TokenType.STAR: 'STAR'>
BACKSLASH = <TokenType.BACKSLASH: 'BACKSLASH'>
SLASH = <TokenType.SLASH: 'SLASH'>
LT = <TokenType.LT: 'LT'>
LTE = <TokenType.LTE: 'LTE'>
GT = <TokenType.GT: 'GT'>
GTE = <TokenType.GTE: 'GTE'>
NOT = <TokenType.NOT: 'NOT'>
EQ = <TokenType.EQ: 'EQ'>
NEQ = <TokenType.NEQ: 'NEQ'>
NULLSAFE_EQ = <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>
COLON_EQ = <TokenType.COLON_EQ: 'COLON_EQ'>
AND = <TokenType.AND: 'AND'>
OR = <TokenType.OR: 'OR'>
AMP = <TokenType.AMP: 'AMP'>
DPIPE = <TokenType.DPIPE: 'DPIPE'>
PIPE = <TokenType.PIPE: 'PIPE'>
PIPE_SLASH = <TokenType.PIPE_SLASH: 'PIPE_SLASH'>
DPIPE_SLASH = <TokenType.DPIPE_SLASH: 'DPIPE_SLASH'>
CARET = <TokenType.CARET: 'CARET'>
CARET_AT = <TokenType.CARET_AT: 'CARET_AT'>
TILDA = <TokenType.TILDA: 'TILDA'>
ARROW = <TokenType.ARROW: 'ARROW'>
DARROW = <TokenType.DARROW: 'DARROW'>
FARROW = <TokenType.FARROW: 'FARROW'>
HASH = <TokenType.HASH: 'HASH'>
HASH_ARROW = <TokenType.HASH_ARROW: 'HASH_ARROW'>
DHASH_ARROW = <TokenType.DHASH_ARROW: 'DHASH_ARROW'>
LR_ARROW = <TokenType.LR_ARROW: 'LR_ARROW'>
DAT = <TokenType.DAT: 'DAT'>
LT_AT = <TokenType.LT_AT: 'LT_AT'>
AT_GT = <TokenType.AT_GT: 'AT_GT'>
DOLLAR = <TokenType.DOLLAR: 'DOLLAR'>
PARAMETER = <TokenType.PARAMETER: 'PARAMETER'>
SESSION_PARAMETER = <TokenType.SESSION_PARAMETER: 'SESSION_PARAMETER'>
DAMP = <TokenType.DAMP: 'DAMP'>
XOR = <TokenType.XOR: 'XOR'>
DSTAR = <TokenType.DSTAR: 'DSTAR'>
URI_START = <TokenType.URI_START: 'URI_START'>
BLOCK_START = <TokenType.BLOCK_START: 'BLOCK_START'>
BLOCK_END = <TokenType.BLOCK_END: 'BLOCK_END'>
SPACE = <TokenType.SPACE: 'SPACE'>
BREAK = <TokenType.BREAK: 'BREAK'>
STRING = <TokenType.STRING: 'STRING'>
NUMBER = <TokenType.NUMBER: 'NUMBER'>
IDENTIFIER = <TokenType.IDENTIFIER: 'IDENTIFIER'>
DATABASE = <TokenType.DATABASE: 'DATABASE'>
COLUMN = <TokenType.COLUMN: 'COLUMN'>
COLUMN_DEF = <TokenType.COLUMN_DEF: 'COLUMN_DEF'>
SCHEMA = <TokenType.SCHEMA: 'SCHEMA'>
TABLE = <TokenType.TABLE: 'TABLE'>
WAREHOUSE = <TokenType.WAREHOUSE: 'WAREHOUSE'>
STAGE = <TokenType.STAGE: 'STAGE'>
STREAMLIT = <TokenType.STREAMLIT: 'STREAMLIT'>
VAR = <TokenType.VAR: 'VAR'>
BIT_STRING = <TokenType.BIT_STRING: 'BIT_STRING'>
HEX_STRING = <TokenType.HEX_STRING: 'HEX_STRING'>
BYTE_STRING = <TokenType.BYTE_STRING: 'BYTE_STRING'>
NATIONAL_STRING = <TokenType.NATIONAL_STRING: 'NATIONAL_STRING'>
RAW_STRING = <TokenType.RAW_STRING: 'RAW_STRING'>
HEREDOC_STRING = <TokenType.HEREDOC_STRING: 'HEREDOC_STRING'>
UNICODE_STRING = <TokenType.UNICODE_STRING: 'UNICODE_STRING'>
BIT = <TokenType.BIT: 'BIT'>
BOOLEAN = <TokenType.BOOLEAN: 'BOOLEAN'>
TINYINT = <TokenType.TINYINT: 'TINYINT'>
UTINYINT = <TokenType.UTINYINT: 'UTINYINT'>
SMALLINT = <TokenType.SMALLINT: 'SMALLINT'>
USMALLINT = <TokenType.USMALLINT: 'USMALLINT'>
MEDIUMINT = <TokenType.MEDIUMINT: 'MEDIUMINT'>
UMEDIUMINT = <TokenType.UMEDIUMINT: 'UMEDIUMINT'>
INT = <TokenType.INT: 'INT'>
UINT = <TokenType.UINT: 'UINT'>
BIGINT = <TokenType.BIGINT: 'BIGINT'>
UBIGINT = <TokenType.UBIGINT: 'UBIGINT'>
INT128 = <TokenType.INT128: 'INT128'>
UINT128 = <TokenType.UINT128: 'UINT128'>
INT256 = <TokenType.INT256: 'INT256'>
UINT256 = <TokenType.UINT256: 'UINT256'>
FLOAT = <TokenType.FLOAT: 'FLOAT'>
DOUBLE = <TokenType.DOUBLE: 'DOUBLE'>
UDOUBLE = <TokenType.UDOUBLE: 'UDOUBLE'>
DECIMAL = <TokenType.DECIMAL: 'DECIMAL'>
DECIMAL32 = <TokenType.DECIMAL32: 'DECIMAL32'>
DECIMAL64 = <TokenType.DECIMAL64: 'DECIMAL64'>
DECIMAL128 = <TokenType.DECIMAL128: 'DECIMAL128'>
DECIMAL256 = <TokenType.DECIMAL256: 'DECIMAL256'>
UDECIMAL = <TokenType.UDECIMAL: 'UDECIMAL'>
BIGDECIMAL = <TokenType.BIGDECIMAL: 'BIGDECIMAL'>
CHAR = <TokenType.CHAR: 'CHAR'>
NCHAR = <TokenType.NCHAR: 'NCHAR'>
VARCHAR = <TokenType.VARCHAR: 'VARCHAR'>
NVARCHAR = <TokenType.NVARCHAR: 'NVARCHAR'>
BPCHAR = <TokenType.BPCHAR: 'BPCHAR'>
TEXT = <TokenType.TEXT: 'TEXT'>
MEDIUMTEXT = <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <TokenType.LONGTEXT: 'LONGTEXT'>
BLOB = <TokenType.BLOB: 'BLOB'>
MEDIUMBLOB = <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <TokenType.LONGBLOB: 'LONGBLOB'>
TINYBLOB = <TokenType.TINYBLOB: 'TINYBLOB'>
TINYTEXT = <TokenType.TINYTEXT: 'TINYTEXT'>
NAME = <TokenType.NAME: 'NAME'>
BINARY = <TokenType.BINARY: 'BINARY'>
VARBINARY = <TokenType.VARBINARY: 'VARBINARY'>
JSON = <TokenType.JSON: 'JSON'>
JSONB = <TokenType.JSONB: 'JSONB'>
TIME = <TokenType.TIME: 'TIME'>
TIMETZ = <TokenType.TIMETZ: 'TIMETZ'>
TIMESTAMP = <TokenType.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPNTZ = <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>
TIMESTAMP_S = <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>
TIMESTAMP_MS = <TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>
TIMESTAMP_NS = <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>
DATETIME = <TokenType.DATETIME: 'DATETIME'>
DATETIME2 = <TokenType.DATETIME2: 'DATETIME2'>
DATETIME64 = <TokenType.DATETIME64: 'DATETIME64'>
SMALLDATETIME = <TokenType.SMALLDATETIME: 'SMALLDATETIME'>
DATE = <TokenType.DATE: 'DATE'>
DATE32 = <TokenType.DATE32: 'DATE32'>
INT4RANGE = <TokenType.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <TokenType.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <TokenType.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <TokenType.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <TokenType.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <TokenType.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>
UUID = <TokenType.UUID: 'UUID'>
GEOGRAPHY = <TokenType.GEOGRAPHY: 'GEOGRAPHY'>
NULLABLE = <TokenType.NULLABLE: 'NULLABLE'>
GEOMETRY = <TokenType.GEOMETRY: 'GEOMETRY'>
POINT = <TokenType.POINT: 'POINT'>
RING = <TokenType.RING: 'RING'>
LINESTRING = <TokenType.LINESTRING: 'LINESTRING'>
MULTILINESTRING = <TokenType.MULTILINESTRING: 'MULTILINESTRING'>
POLYGON = <TokenType.POLYGON: 'POLYGON'>
MULTIPOLYGON = <TokenType.MULTIPOLYGON: 'MULTIPOLYGON'>
HLLSKETCH = <TokenType.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <TokenType.HSTORE: 'HSTORE'>
SUPER = <TokenType.SUPER: 'SUPER'>
SERIAL = <TokenType.SERIAL: 'SERIAL'>
SMALLSERIAL = <TokenType.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <TokenType.BIGSERIAL: 'BIGSERIAL'>
XML = <TokenType.XML: 'XML'>
YEAR = <TokenType.YEAR: 'YEAR'>
USERDEFINED = <TokenType.USERDEFINED: 'USERDEFINED'>
MONEY = <TokenType.MONEY: 'MONEY'>
SMALLMONEY = <TokenType.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <TokenType.ROWVERSION: 'ROWVERSION'>
IMAGE = <TokenType.IMAGE: 'IMAGE'>
VARIANT = <TokenType.VARIANT: 'VARIANT'>
OBJECT = <TokenType.OBJECT: 'OBJECT'>
INET = <TokenType.INET: 'INET'>
IPADDRESS = <TokenType.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <TokenType.IPPREFIX: 'IPPREFIX'>
IPV4 = <TokenType.IPV4: 'IPV4'>
IPV6 = <TokenType.IPV6: 'IPV6'>
ENUM = <TokenType.ENUM: 'ENUM'>
ENUM8 = <TokenType.ENUM8: 'ENUM8'>
ENUM16 = <TokenType.ENUM16: 'ENUM16'>
FIXEDSTRING = <TokenType.FIXEDSTRING: 'FIXEDSTRING'>
LOWCARDINALITY = <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>
NESTED = <TokenType.NESTED: 'NESTED'>
AGGREGATEFUNCTION = <TokenType.AGGREGATEFUNCTION: 'AGGREGATEFUNCTION'>
SIMPLEAGGREGATEFUNCTION = <TokenType.SIMPLEAGGREGATEFUNCTION: 'SIMPLEAGGREGATEFUNCTION'>
TDIGEST = <TokenType.TDIGEST: 'TDIGEST'>
UNKNOWN = <TokenType.UNKNOWN: 'UNKNOWN'>
VECTOR = <TokenType.VECTOR: 'VECTOR'>
DYNAMIC = <TokenType.DYNAMIC: 'DYNAMIC'>
ALIAS = <TokenType.ALIAS: 'ALIAS'>
ALTER = <TokenType.ALTER: 'ALTER'>
ALWAYS = <TokenType.ALWAYS: 'ALWAYS'>
ALL = <TokenType.ALL: 'ALL'>
ANTI = <TokenType.ANTI: 'ANTI'>
ANY = <TokenType.ANY: 'ANY'>
APPLY = <TokenType.APPLY: 'APPLY'>
ARRAY = <TokenType.ARRAY: 'ARRAY'>
ASC = <TokenType.ASC: 'ASC'>
ASOF = <TokenType.ASOF: 'ASOF'>
ATTACH = <TokenType.ATTACH: 'ATTACH'>
AUTO_INCREMENT = <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>
BEGIN = <TokenType.BEGIN: 'BEGIN'>
BETWEEN = <TokenType.BETWEEN: 'BETWEEN'>
BULK_COLLECT_INTO = <TokenType.BULK_COLLECT_INTO: 'BULK_COLLECT_INTO'>
CACHE = <TokenType.CACHE: 'CACHE'>
CASE = <TokenType.CASE: 'CASE'>
CHARACTER_SET = <TokenType.CHARACTER_SET: 'CHARACTER_SET'>
CLUSTER_BY = <TokenType.CLUSTER_BY: 'CLUSTER_BY'>
COLLATE = <TokenType.COLLATE: 'COLLATE'>
COMMAND = <TokenType.COMMAND: 'COMMAND'>
COMMENT = <TokenType.COMMENT: 'COMMENT'>
COMMIT = <TokenType.COMMIT: 'COMMIT'>
CONNECT_BY = <TokenType.CONNECT_BY: 'CONNECT_BY'>
CONSTRAINT = <TokenType.CONSTRAINT: 'CONSTRAINT'>
COPY = <TokenType.COPY: 'COPY'>
CREATE = <TokenType.CREATE: 'CREATE'>
CROSS = <TokenType.CROSS: 'CROSS'>
CUBE = <TokenType.CUBE: 'CUBE'>
CURRENT_DATE = <TokenType.CURRENT_DATE: 'CURRENT_DATE'>
CURRENT_DATETIME = <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>
CURRENT_SCHEMA = <TokenType.CURRENT_SCHEMA: 'CURRENT_SCHEMA'>
CURRENT_TIME = <TokenType.CURRENT_TIME: 'CURRENT_TIME'>
CURRENT_TIMESTAMP = <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>
CURRENT_USER = <TokenType.CURRENT_USER: 'CURRENT_USER'>
DECLARE = <TokenType.DECLARE: 'DECLARE'>
DEFAULT = <TokenType.DEFAULT: 'DEFAULT'>
DELETE = <TokenType.DELETE: 'DELETE'>
DESC = <TokenType.DESC: 'DESC'>
DESCRIBE = <TokenType.DESCRIBE: 'DESCRIBE'>
DETACH = <TokenType.DETACH: 'DETACH'>
DICTIONARY = <TokenType.DICTIONARY: 'DICTIONARY'>
DISTINCT = <TokenType.DISTINCT: 'DISTINCT'>
DISTRIBUTE_BY = <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>
DIV = <TokenType.DIV: 'DIV'>
DROP = <TokenType.DROP: 'DROP'>
ELSE = <TokenType.ELSE: 'ELSE'>
END = <TokenType.END: 'END'>
ESCAPE = <TokenType.ESCAPE: 'ESCAPE'>
EXCEPT = <TokenType.EXCEPT: 'EXCEPT'>
EXECUTE = <TokenType.EXECUTE: 'EXECUTE'>
EXISTS = <TokenType.EXISTS: 'EXISTS'>
FALSE = <TokenType.FALSE: 'FALSE'>
FETCH = <TokenType.FETCH: 'FETCH'>
FILE_FORMAT = <TokenType.FILE_FORMAT: 'FILE_FORMAT'>
FILTER = <TokenType.FILTER: 'FILTER'>
FINAL = <TokenType.FINAL: 'FINAL'>
FIRST = <TokenType.FIRST: 'FIRST'>
FOR = <TokenType.FOR: 'FOR'>
FORCE = <TokenType.FORCE: 'FORCE'>
FOREIGN_KEY = <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>
FORMAT = <TokenType.FORMAT: 'FORMAT'>
FROM = <TokenType.FROM: 'FROM'>
FULL = <TokenType.FULL: 'FULL'>
FUNCTION = <TokenType.FUNCTION: 'FUNCTION'>
GLOB = <TokenType.GLOB: 'GLOB'>
GLOBAL = <TokenType.GLOBAL: 'GLOBAL'>
GRANT = <TokenType.GRANT: 'GRANT'>
GROUP_BY = <TokenType.GROUP_BY: 'GROUP_BY'>
GROUPING_SETS = <TokenType.GROUPING_SETS: 'GROUPING_SETS'>
HAVING = <TokenType.HAVING: 'HAVING'>
HINT = <TokenType.HINT: 'HINT'>
IGNORE = <TokenType.IGNORE: 'IGNORE'>
ILIKE = <TokenType.ILIKE: 'ILIKE'>
ILIKE_ANY = <TokenType.ILIKE_ANY: 'ILIKE_ANY'>
IN = <TokenType.IN: 'IN'>
INDEX = <TokenType.INDEX: 'INDEX'>
INNER = <TokenType.INNER: 'INNER'>
INSERT = <TokenType.INSERT: 'INSERT'>
INTERSECT = <TokenType.INTERSECT: 'INTERSECT'>
INTERVAL = <TokenType.INTERVAL: 'INTERVAL'>
INTO = <TokenType.INTO: 'INTO'>
INTRODUCER = <TokenType.INTRODUCER: 'INTRODUCER'>
IRLIKE = <TokenType.IRLIKE: 'IRLIKE'>
IS = <TokenType.IS: 'IS'>
ISNULL = <TokenType.ISNULL: 'ISNULL'>
JOIN = <TokenType.JOIN: 'JOIN'>
JOIN_MARKER = <TokenType.JOIN_MARKER: 'JOIN_MARKER'>
KEEP = <TokenType.KEEP: 'KEEP'>
KEY = <TokenType.KEY: 'KEY'>
KILL = <TokenType.KILL: 'KILL'>
LANGUAGE = <TokenType.LANGUAGE: 'LANGUAGE'>
LATERAL = <TokenType.LATERAL: 'LATERAL'>
LEFT = <TokenType.LEFT: 'LEFT'>
LIKE = <TokenType.LIKE: 'LIKE'>
LIKE_ANY = <TokenType.LIKE_ANY: 'LIKE_ANY'>
LIMIT = <TokenType.LIMIT: 'LIMIT'>
LIST = <TokenType.LIST: 'LIST'>
LOAD = <TokenType.LOAD: 'LOAD'>
LOCK = <TokenType.LOCK: 'LOCK'>
MAP = <TokenType.MAP: 'MAP'>
MATCH_CONDITION = <TokenType.MATCH_CONDITION: 'MATCH_CONDITION'>
MATCH_RECOGNIZE = <TokenType.MATCH_RECOGNIZE: 'MATCH_RECOGNIZE'>
MEMBER_OF = <TokenType.MEMBER_OF: 'MEMBER_OF'>
MERGE = <TokenType.MERGE: 'MERGE'>
MOD = <TokenType.MOD: 'MOD'>
MODEL = <TokenType.MODEL: 'MODEL'>
NATURAL = <TokenType.NATURAL: 'NATURAL'>
NEXT = <TokenType.NEXT: 'NEXT'>
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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

size
sql
tokens