sqlglot.tokens API documentation

Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

    429    @classmethod
    430    def number(cls, number: int) -> Token:
    431        """Returns a NUMBER token with `number` as its text."""
    432        return cls(TokenType.NUMBER, str(number))

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

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

    434    @classmethod
    435    def string(cls, string: str) -> Token:
    436        """Returns a STRING token with `string` as its text."""
    437        return cls(TokenType.STRING, string)

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

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

    439    @classmethod
    440    def identifier(cls, identifier: str) -> Token:
    441        """Returns an IDENTIFIER token with `identifier` as its text."""
    442        return cls(TokenType.IDENTIFIER, identifier)

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

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

    444    @classmethod
    445    def var(cls, var: str) -> Token:
    446        """Returns an VAR token with `var` as its text."""
    447        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

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

    1004    def __init__(
    1005        self, dialect: DialectType = None, use_rs_tokenizer: t.Optional[bool] = None
    1006    ) -> None:
    1007        from sqlglot.dialects import Dialect
    1008
    1009        self.dialect = Dialect.get_or_raise(dialect)
    1010
    1011        # initialize `use_rs_tokenizer`, and allow it to be overwritten per Tokenizer instance
    1012        self.use_rs_tokenizer = (
    1013            use_rs_tokenizer if use_rs_tokenizer is not None else USE_RS_TOKENIZER
    1014        )
    1015
    1016        if self.use_rs_tokenizer:
    1017            self._rs_dialect_settings = RsTokenizerDialectSettings(
    1018                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
    1019                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    1020                numbers_can_be_underscore_separated=self.dialect.NUMBERS_CAN_BE_UNDERSCORE_SEPARATED,
    1021            )
    1022
    1023        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.SELECT: 'SELECT'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.INSERT: 'INSERT'>, <TokenType.DELETE: 'DELETE'>}
KEYWORDS: Dict[str, TokenType] = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, ':=': <TokenType.COLON_EQ: 'COLON_EQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, '??': <TokenType.DQMARK: 'DQMARK'>, '~~~': <TokenType.GLOB: 'GLOB'>, '~~': <TokenType.LIKE: 'LIKE'>, '~~*': <TokenType.ILIKE: 'ILIKE'>, '~*': <TokenType.IRLIKE: 'IRLIKE'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'COPY': <TokenType.COPY: 'COPY'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_SCHEMA': <TokenType.CURRENT_SCHEMA: 'CURRENT_SCHEMA'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ENUM': <TokenType.ENUM: 'ENUM'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'KILL': <TokenType.KILL: 'KILL'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NAMESPACE': <TokenType.NAMESPACE: 'NAMESPACE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'RENAME': <TokenType.RENAME: 'RENAME'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'START WITH': <TokenType.START_WITH: 'START_WITH'>, 'STRAIGHT_JOIN': <TokenType.STRAIGHT_JOIN: 'STRAIGHT_JOIN'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'TRUNCATE': <TokenType.TRUNCATE: 'TRUNCATE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'MEDIUMINT': <TokenType.MEDIUMINT: 'MEDIUMINT'>, 'INT1': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'INT16': <TokenType.SMALLINT: 'SMALLINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'HUGEINT': <TokenType.INT128: 'INT128'>, 'UHUGEINT': <TokenType.UINT128: 'UINT128'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'INT32': <TokenType.INT: 'INT'>, 'INT64': <TokenType.BIGINT: 'BIGINT'>, 'INT128': <TokenType.INT128: 'INT128'>, 'INT256': <TokenType.INT256: 'INT256'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.TINYINT: 'TINYINT'>, 'UINT': <TokenType.UINT: 'UINT'>, 'UINT128': <TokenType.UINT128: 'UINT128'>, 'UINT256': <TokenType.UINT256: 'UINT256'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL32': <TokenType.DECIMAL32: 'DECIMAL32'>, 'DECIMAL64': <TokenType.DECIMAL64: 'DECIMAL64'>, 'DECIMAL128': <TokenType.DECIMAL128: 'DECIMAL128'>, 'DECIMAL256': <TokenType.DECIMAL256: 'DECIMAL256'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'LIST': <TokenType.LIST: 'LIST'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'JSONB': <TokenType.JSONB: 'JSONB'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'BPCHAR': <TokenType.BPCHAR: 'BPCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMP_LTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMPNTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'TIMESTAMP_NTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'VECTOR': <TokenType.VECTOR: 'VECTOR'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'SEQUENCE': <TokenType.SEQUENCE: 'SEQUENCE'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.ANALYZE: 'ANALYZE'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.GRANT: 'GRANT'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>}
WHITE_SPACE: Dict[Optional[str], TokenType] = {' ': <TokenType.SPACE: 'SPACE'>, '\t': <TokenType.SPACE: 'SPACE'>, '\n': <TokenType.BREAK: 'BREAK'>, '\r': <TokenType.BREAK: 'BREAK'>}
COMMANDS = {<TokenType.FETCH: 'FETCH'>, <TokenType.RENAME: 'RENAME'>, <TokenType.SHOW: 'SHOW'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.EXECUTE: 'EXECUTE'>}
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

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

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

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

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

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

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

size
sql
tokens