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

##### Inherited Members

enum.Enum
  name
  value

class Token: View Source

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    943    def __init__(self, dialect: DialectType = None) -> None:
    944        from sqlglot.dialects import Dialect
    945
    946        self.dialect = Dialect.get_or_raise(dialect)
    947
    948        if USE_RS_TOKENIZER:
    949            self._rs_dialect_settings = RsTokenizerDialectSettings(
    950                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
    951                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    952            )
    953
    954        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'>
STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS = True
KEYWORDS: Dict[str, TokenType] = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, ':=': <TokenType.COLON_EQ: 'COLON_EQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, '??': <TokenType.DQMARK: 'DQMARK'>, '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'>, 'VECTOR': <TokenType.VECTOR: 'VECTOR'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'SEQUENCE': <TokenType.SEQUENCE: 'SEQUENCE'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.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.COMMAND: 'COMMAND'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.FETCH: 'FETCH'>, <TokenType.SHOW: 'SHOW'>}
COMMAND_PREFIX_TOKENS = {<TokenType.SEMICOLON: 'SEMICOLON'>, <TokenType.BEGIN: 'BEGIN'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
def reset(self) -> None: View Source

    956    def reset(self) -> None:
    957        self.sql = ""
    958        self.size = 0
    959        self.tokens: t.List[Token] = []
    960        self._start = 0
    961        self._current = 0
    962        self._line = 1
    963        self._col = 0
    964        self._comments: t.List[str] = []
    965
    966        self._char = ""
    967        self._end = False
    968        self._peek = ""
    969        self._prev_token_line = -1

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

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

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

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

    1408    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1409        if not self._RS_TOKENIZER:
    1410            raise SqlglotError("Rust tokenizer is not available")
    1411
    1412        try:
    1413            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1414            for token in tokens:
    1415                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1416            return tokens
    1417        except Exception as e:
    1418            raise TokenError(str(e))

size
sql
tokens