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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

size
sql
tokens