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

##### Inherited Members

enum.Enum
  name
  value

class Token: View Source

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

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

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

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

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

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

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

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

    418    @classmethod
    419    def identifier(cls, identifier: str) -> Token:
    420        """Returns an IDENTIFIER token with `identifier` as its text."""
    421        return cls(TokenType.IDENTIFIER, identifier)

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

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

    423    @classmethod
    424    def var(cls, var: str) -> Token:
    425        """Returns an VAR token with `var` as its text."""
    426        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

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

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

    956    def __init__(self, dialect: DialectType = None) -> None:
    957        from sqlglot.dialects import Dialect
    958
    959        self.dialect = Dialect.get_or_raise(dialect)
    960
    961        if USE_RS_TOKENIZER:
    962            self._rs_dialect_settings = RsTokenizerDialectSettings(
    963                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
    964                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    965            )
    966
    967        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
NESTED_COMMENTS = True
KEYWORDS: Dict[str, TokenType] = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, ':=': <TokenType.COLON_EQ: 'COLON_EQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, '??': <TokenType.DQMARK: 'DQMARK'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'COPY': <TokenType.COPY: 'COPY'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ENUM': <TokenType.ENUM: 'ENUM'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'KILL': <TokenType.KILL: 'KILL'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'RENAME': <TokenType.RENAME: 'RENAME'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'START WITH': <TokenType.START_WITH: 'START_WITH'>, 'STRAIGHT_JOIN': <TokenType.STRAIGHT_JOIN: 'STRAIGHT_JOIN'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'TRUNCATE': <TokenType.TRUNCATE: 'TRUNCATE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'MEDIUMINT': <TokenType.MEDIUMINT: 'MEDIUMINT'>, 'INT1': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'INT16': <TokenType.SMALLINT: 'SMALLINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT128': <TokenType.INT128: 'INT128'>, 'HUGEINT': <TokenType.INT128: 'INT128'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'INT32': <TokenType.INT: 'INT'>, 'INT64': <TokenType.BIGINT: 'BIGINT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.TINYINT: 'TINYINT'>, 'UINT': <TokenType.UINT: 'UINT'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL32': <TokenType.DECIMAL32: 'DECIMAL32'>, 'DECIMAL64': <TokenType.DECIMAL64: 'DECIMAL64'>, 'DECIMAL128': <TokenType.DECIMAL128: 'DECIMAL128'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'LIST': <TokenType.LIST: 'LIST'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'JSONB': <TokenType.JSONB: 'JSONB'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'BPCHAR': <TokenType.BPCHAR: 'BPCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMP_LTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMPNTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'TIMESTAMP_NTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'VECTOR': <TokenType.VECTOR: 'VECTOR'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'SEQUENCE': <TokenType.SEQUENCE: 'SEQUENCE'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.GRANT: 'GRANT'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>}
WHITE_SPACE: Dict[Optional[str], TokenType] = {' ': <TokenType.SPACE: 'SPACE'>, '\t': <TokenType.SPACE: 'SPACE'>, '\n': <TokenType.BREAK: 'BREAK'>, '\r': <TokenType.BREAK: 'BREAK'>}
COMMANDS = {<TokenType.EXECUTE: 'EXECUTE'>, <TokenType.RENAME: 'RENAME'>, <TokenType.SHOW: 'SHOW'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.FETCH: 'FETCH'>}
COMMAND_PREFIX_TOKENS = {<TokenType.SEMICOLON: 'SEMICOLON'>, <TokenType.BEGIN: 'BEGIN'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
def reset(self) -> None: View Source

    969    def reset(self) -> None:
    970        self.sql = ""
    971        self.size = 0
    972        self.tokens: t.List[Token] = []
    973        self._start = 0
    974        self._current = 0
    975        self._line = 1
    976        self._col = 0
    977        self._comments: t.List[str] = []
    978
    979        self._char = ""
    980        self._end = False
    981        self._peek = ""
    982        self._prev_token_line = -1

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

     984    def tokenize(self, sql: str) -> t.List[Token]:
     985        """Returns a list of tokens corresponding to the SQL string `sql`."""
     986        if USE_RS_TOKENIZER:
     987            return self.tokenize_rs(sql)
     988
     989        self.reset()
     990        self.sql = sql
     991        self.size = len(sql)
     992
     993        try:
     994            self._scan()
     995        except Exception as e:
     996            start = max(self._current - 50, 0)
     997            end = min(self._current + 50, self.size - 1)
     998            context = self.sql[start:end]
     999            raise TokenError(f"Error tokenizing '{context}'") from e
    1000
    1001        return self.tokens

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

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

    1425    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1426        if not self._RS_TOKENIZER:
    1427            raise SqlglotError("Rust tokenizer is not available")
    1428
    1429        try:
    1430            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1431            for token in tokens:
    1432                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1433            return tokens
    1434        except Exception as e:
    1435            raise TokenError(str(e))

size
sql
tokens