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

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

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

    417    @classmethod
    418    def number(cls, number: int) -> Token:
    419        """Returns a NUMBER token with `number` as its text."""
    420        return cls(TokenType.NUMBER, str(number))

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

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

    422    @classmethod
    423    def string(cls, string: str) -> Token:
    424        """Returns a STRING token with `string` as its text."""
    425        return cls(TokenType.STRING, string)

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

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

    427    @classmethod
    428    def identifier(cls, identifier: str) -> Token:
    429        """Returns an IDENTIFIER token with `identifier` as its text."""
    430        return cls(TokenType.IDENTIFIER, identifier)

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

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

    432    @classmethod
    433    def var(cls, var: str) -> Token:
    434        """Returns an VAR token with `var` as its text."""
    435        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

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

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

    975    def __init__(self, dialect: DialectType = None) -> None:
    976        from sqlglot.dialects import Dialect
    977
    978        self.dialect = Dialect.get_or_raise(dialect)
    979
    980        if USE_RS_TOKENIZER:
    981            self._rs_dialect_settings = RsTokenizerDialectSettings(
    982                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
    983                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    984            )
    985
    986        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
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.SHOW: 'SHOW'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.FETCH: 'FETCH'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.RENAME: 'RENAME'>}
COMMAND_PREFIX_TOKENS = {<TokenType.BEGIN: 'BEGIN'>, <TokenType.SEMICOLON: 'SEMICOLON'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
def reset(self) -> None: View Source

     988    def reset(self) -> None:
     989        self.sql = ""
     990        self.size = 0
     991        self.tokens: t.List[Token] = []
     992        self._start = 0
     993        self._current = 0
     994        self._line = 1
     995        self._col = 0
     996        self._comments: t.List[str] = []
     997
     998        self._char = ""
     999        self._end = False
    1000        self._peek = ""
    1001        self._prev_token_line = -1

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

    1003    def tokenize(self, sql: str) -> t.List[Token]:
    1004        """Returns a list of tokens corresponding to the SQL string `sql`."""
    1005        if USE_RS_TOKENIZER:
    1006            return self.tokenize_rs(sql)
    1007
    1008        self.reset()
    1009        self.sql = sql
    1010        self.size = len(sql)
    1011
    1012        try:
    1013            self._scan()
    1014        except Exception as e:
    1015            start = max(self._current - 50, 0)
    1016            end = min(self._current + 50, self.size - 1)
    1017            context = self.sql[start:end]
    1018            raise TokenError(f"Error tokenizing '{context}'") from e
    1019
    1020        return self.tokens

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

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

    1446    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1447        if not self._RS_TOKENIZER:
    1448            raise SqlglotError("Rust tokenizer is not available")
    1449
    1450        try:
    1451            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1452            for token in tokens:
    1453                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1454            return tokens
    1455        except Exception as e:
    1456            raise TokenError(str(e))

size
sql
tokens