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

##### Inherited Members

enum.Enum
  name
  value

class Token: View Source

    395class Token:
    396    __slots__ = ("token_type", "text", "line", "col", "start", "end", "comments")
    397
    398    @classmethod
    399    def number(cls, number: int) -> Token:
    400        """Returns a NUMBER token with `number` as its text."""
    401        return cls(TokenType.NUMBER, str(number))
    402
    403    @classmethod
    404    def string(cls, string: str) -> Token:
    405        """Returns a STRING token with `string` as its text."""
    406        return cls(TokenType.STRING, string)
    407
    408    @classmethod
    409    def identifier(cls, identifier: str) -> Token:
    410        """Returns an IDENTIFIER token with `identifier` as its text."""
    411        return cls(TokenType.IDENTIFIER, identifier)
    412
    413    @classmethod
    414    def var(cls, var: str) -> Token:
    415        """Returns an VAR token with `var` as its text."""
    416        return cls(TokenType.VAR, var)
    417
    418    def __init__(
    419        self,
    420        token_type: TokenType,
    421        text: str,
    422        line: int = 1,
    423        col: int = 1,
    424        start: int = 0,
    425        end: int = 0,
    426        comments: t.Optional[t.List[str]] = None,
    427    ) -> None:
    428        """Token initializer.
    429
    430        Args:
    431            token_type: The TokenType Enum.
    432            text: The text of the token.
    433            line: The line that the token ends on.
    434            col: The column that the token ends on.
    435            start: The start index of the token.
    436            end: The ending index of the token.
    437            comments: The comments to attach to the token.
    438        """
    439        self.token_type = token_type
    440        self.text = text
    441        self.line = line
    442        self.col = col
    443        self.start = start
    444        self.end = end
    445        self.comments = [] if comments is None else comments
    446
    447    def __repr__(self) -> str:
    448        attributes = ", ".join(f"{k}: {getattr(self, k)}" for k in self.__slots__)
    449        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

    418    def __init__(
    419        self,
    420        token_type: TokenType,
    421        text: str,
    422        line: int = 1,
    423        col: int = 1,
    424        start: int = 0,
    425        end: int = 0,
    426        comments: t.Optional[t.List[str]] = None,
    427    ) -> None:
    428        """Token initializer.
    429
    430        Args:
    431            token_type: The TokenType Enum.
    432            text: The text of the token.
    433            line: The line that the token ends on.
    434            col: The column that the token ends on.
    435            start: The start index of the token.
    436            end: The ending index of the token.
    437            comments: The comments to attach to the token.
    438        """
    439        self.token_type = token_type
    440        self.text = text
    441        self.line = line
    442        self.col = col
    443        self.start = start
    444        self.end = end
    445        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

    398    @classmethod
    399    def number(cls, number: int) -> Token:
    400        """Returns a NUMBER token with `number` as its text."""
    401        return cls(TokenType.NUMBER, str(number))

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

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

    403    @classmethod
    404    def string(cls, string: str) -> Token:
    405        """Returns a STRING token with `string` as its text."""
    406        return cls(TokenType.STRING, string)

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

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

    408    @classmethod
    409    def identifier(cls, identifier: str) -> Token:
    410        """Returns an IDENTIFIER token with `identifier` as its text."""
    411        return cls(TokenType.IDENTIFIER, identifier)

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

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

    413    @classmethod
    414    def var(cls, var: str) -> Token:
    415        """Returns an VAR token with `var` as its text."""
    416        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

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

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

    931    def __init__(self, dialect: DialectType = None) -> None:
    932        from sqlglot.dialects import Dialect
    933
    934        self.dialect = Dialect.get_or_raise(dialect)
    935
    936        if USE_RS_TOKENIZER:
    937            self._rs_dialect_settings = RsTokenizerDialectSettings(
    938                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
    939                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    940            )
    941
    942        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]]] = ['"']
IDENTIFIER_ESCAPES = ['"']
QUOTES: List[Union[str, Tuple[str, str]]] = ["'"]
STRING_ESCAPES = ["'"]
VAR_SINGLE_TOKENS: Set[str] = set()
HEREDOC_TAG_IS_IDENTIFIER = False
HEREDOC_STRING_ALTERNATIVE = <TokenType.VAR: 'VAR'>
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'>, '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'>, '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'>, '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'>, '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'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, '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'>, '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.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>}
WHITE_SPACE: Dict[Optional[str], TokenType] = {' ': <TokenType.SPACE: 'SPACE'>, '\t': <TokenType.SPACE: 'SPACE'>, '\n': <TokenType.BREAK: 'BREAK'>, '\r': <TokenType.BREAK: 'BREAK'>}
COMMANDS = {<TokenType.EXECUTE: 'EXECUTE'>, <TokenType.SHOW: 'SHOW'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.FETCH: 'FETCH'>}
COMMAND_PREFIX_TOKENS = {<TokenType.SEMICOLON: 'SEMICOLON'>, <TokenType.BEGIN: 'BEGIN'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
def reset(self) -> None: View Source

    944    def reset(self) -> None:
    945        self.sql = ""
    946        self.size = 0
    947        self.tokens: t.List[Token] = []
    948        self._start = 0
    949        self._current = 0
    950        self._line = 1
    951        self._col = 0
    952        self._comments: t.List[str] = []
    953
    954        self._char = ""
    955        self._end = False
    956        self._peek = ""
    957        self._prev_token_line = -1

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

    959    def tokenize(self, sql: str) -> t.List[Token]:
    960        """Returns a list of tokens corresponding to the SQL string `sql`."""
    961        if USE_RS_TOKENIZER:
    962            return self.tokenize_rs(sql)
    963
    964        self.reset()
    965        self.sql = sql
    966        self.size = len(sql)
    967
    968        try:
    969            self._scan()
    970        except Exception as e:
    971            start = max(self._current - 50, 0)
    972            end = min(self._current + 50, self.size - 1)
    973            context = self.sql[start:end]
    974            raise TokenError(f"Error tokenizing '{context}'") from e
    975
    976        return self.tokens

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

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

    1392    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1393        if not self._RS_TOKENIZER:
    1394            raise SqlglotError("Rust tokenizer is not available")
    1395
    1396        try:
    1397            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1398            for token in tokens:
    1399                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1400            return tokens
    1401        except Exception as e:
    1402            raise TokenError(str(e))

size
sql
tokens