sqlglot.tokens API documentation

Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

    421    @classmethod
    422    def number(cls, number: int) -> Token:
    423        """Returns a NUMBER token with `number` as its text."""
    424        return cls(TokenType.NUMBER, str(number))

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

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

    426    @classmethod
    427    def string(cls, string: str) -> Token:
    428        """Returns a STRING token with `string` as its text."""
    429        return cls(TokenType.STRING, string)

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

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

    431    @classmethod
    432    def identifier(cls, identifier: str) -> Token:
    433        """Returns an IDENTIFIER token with `identifier` as its text."""
    434        return cls(TokenType.IDENTIFIER, identifier)

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

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

    436    @classmethod
    437    def var(cls, var: str) -> Token:
    438        """Returns an VAR token with `var` as its text."""
    439        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

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

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

     990    def __init__(self, dialect: DialectType = None) -> None:
     991        from sqlglot.dialects import Dialect
     992
     993        self.dialect = Dialect.get_or_raise(dialect)
     994
     995        if USE_RS_TOKENIZER:
     996            self._rs_dialect_settings = RsTokenizerDialectSettings(
     997                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
     998                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
     999            )
    1000
    1001        self.reset()

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

    1003    def reset(self) -> None:
    1004        self.sql = ""
    1005        self.size = 0
    1006        self.tokens: t.List[Token] = []
    1007        self._start = 0
    1008        self._current = 0
    1009        self._line = 1
    1010        self._col = 0
    1011        self._comments: t.List[str] = []
    1012
    1013        self._char = ""
    1014        self._end = False
    1015        self._peek = ""
    1016        self._prev_token_line = -1

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

    1018    def tokenize(self, sql: str) -> t.List[Token]:
    1019        """Returns a list of tokens corresponding to the SQL string `sql`."""
    1020        if USE_RS_TOKENIZER:
    1021            return self.tokenize_rs(sql)
    1022
    1023        self.reset()
    1024        self.sql = sql
    1025        self.size = len(sql)
    1026
    1027        try:
    1028            self._scan()
    1029        except Exception as e:
    1030            start = max(self._current - 50, 0)
    1031            end = min(self._current + 50, self.size - 1)
    1032            context = self.sql[start:end]
    1033            raise TokenError(f"Error tokenizing '{context}'") from e
    1034
    1035        return self.tokens

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

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

    1468    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1469        if not self._RS_TOKENIZER:
    1470            raise SqlglotError("Rust tokenizer is not available")
    1471
    1472        try:
    1473            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1474            for token in tokens:
    1475                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1476            return tokens
    1477        except Exception as e:
    1478            raise TokenError(str(e))

size
sql
tokens