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

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'>
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

    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}>"

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

    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

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

    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))

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

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

    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)

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

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

    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)

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

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

    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)

Returns an VAR token with `var` as its text.

token_type
text
line
col
start
end
comments
class Tokenizer: View Source

     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.COMMAND,
     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))

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

    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()

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.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>}
WHITE_SPACE: Dict[Optional[str], TokenType] = {' ': <TokenType.SPACE: 'SPACE'>, '\t': <TokenType.SPACE: 'SPACE'>, '\n': <TokenType.BREAK: 'BREAK'>, '\r': <TokenType.BREAK: 'BREAK'>}
COMMANDS = {<TokenType.RENAME: 'RENAME'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.SHOW: 'SHOW'>, <TokenType.FETCH: 'FETCH'>}
COMMAND_PREFIX_TOKENS = {<TokenType.BEGIN: 'BEGIN'>, <TokenType.SEMICOLON: 'SEMICOLON'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
def reset(self) -> None: View Source

    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

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

     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

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

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

    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))

size
sql
tokens