sqlglot.tokens API documentation

Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    936    def __init__(self, dialect: DialectType = None) -> None:
    937        from sqlglot.dialects import Dialect
    938
    939        self.dialect = Dialect.get_or_raise(dialect)
    940
    941        if USE_RS_TOKENIZER:
    942            self._rs_dialect_settings = RsTokenizerDialectSettings(
    943                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
    944                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    945            )
    946
    947        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'>, 'STRAIGHT_JOIN': <TokenType.STRAIGHT_JOIN: 'STRAIGHT_JOIN'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'TRUNCATE': <TokenType.TRUNCATE: 'TRUNCATE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'MEDIUMINT': <TokenType.MEDIUMINT: 'MEDIUMINT'>, 'INT1': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'INT16': <TokenType.SMALLINT: 'SMALLINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT128': <TokenType.INT128: 'INT128'>, 'HUGEINT': <TokenType.INT128: 'INT128'>, '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'>, 'LIST': <TokenType.LIST: 'LIST'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'JSONB': <TokenType.JSONB: 'JSONB'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'BPCHAR': <TokenType.BPCHAR: 'BPCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMP_LTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMPNTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'TIMESTAMP_NTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, '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.FETCH: 'FETCH'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.SHOW: 'SHOW'>}
COMMAND_PREFIX_TOKENS = {<TokenType.BEGIN: 'BEGIN'>, <TokenType.SEMICOLON: 'SEMICOLON'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
def reset(self) -> None: View Source

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

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

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

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

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

    1400    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1401        if not self._RS_TOKENIZER:
    1402            raise SqlglotError("Rust tokenizer is not available")
    1403
    1404        try:
    1405            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1406            for token in tokens:
    1407                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1408            return tokens
    1409        except Exception as e:
    1410            raise TokenError(str(e))

size
sql
tokens