sqlglot.tokens API documentation

Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    963    def __init__(self, dialect: DialectType = None) -> None:
    964        from sqlglot.dialects import Dialect
    965
    966        self.dialect = Dialect.get_or_raise(dialect)
    967
    968        if USE_RS_TOKENIZER:
    969            self._rs_dialect_settings = RsTokenizerDialectSettings(
    970                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
    971                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    972            )
    973
    974        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'>, '~~~': <TokenType.GLOB: 'GLOB'>, '~~': <TokenType.LIKE: 'LIKE'>, '~~*': <TokenType.ILIKE: 'ILIKE'>, '~*': <TokenType.IRLIKE: 'IRLIKE'>, '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'>, 'UHUGEINT': <TokenType.UINT128: 'UINT128'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'INT32': <TokenType.INT: 'INT'>, 'INT64': <TokenType.BIGINT: 'BIGINT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.TINYINT: 'TINYINT'>, 'UINT': <TokenType.UINT: 'UINT'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL32': <TokenType.DECIMAL32: 'DECIMAL32'>, 'DECIMAL64': <TokenType.DECIMAL64: 'DECIMAL64'>, 'DECIMAL128': <TokenType.DECIMAL128: 'DECIMAL128'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'LIST': <TokenType.LIST: 'LIST'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'JSONB': <TokenType.JSONB: 'JSONB'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'BPCHAR': <TokenType.BPCHAR: 'BPCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMP_LTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMPNTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'TIMESTAMP_NTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'VECTOR': <TokenType.VECTOR: 'VECTOR'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'SEQUENCE': <TokenType.SEQUENCE: 'SEQUENCE'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.GRANT: 'GRANT'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>}
WHITE_SPACE: Dict[Optional[str], TokenType] = {' ': <TokenType.SPACE: 'SPACE'>, '\t': <TokenType.SPACE: 'SPACE'>, '\n': <TokenType.BREAK: 'BREAK'>, '\r': <TokenType.BREAK: 'BREAK'>}
COMMANDS = {<TokenType.SHOW: 'SHOW'>, <TokenType.RENAME: 'RENAME'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.FETCH: 'FETCH'>, <TokenType.COMMAND: 'COMMAND'>}
COMMAND_PREFIX_TOKENS = {<TokenType.SEMICOLON: 'SEMICOLON'>, <TokenType.BEGIN: 'BEGIN'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
def reset(self) -> None: View Source

    976    def reset(self) -> None:
    977        self.sql = ""
    978        self.size = 0
    979        self.tokens: t.List[Token] = []
    980        self._start = 0
    981        self._current = 0
    982        self._line = 1
    983        self._col = 0
    984        self._comments: t.List[str] = []
    985
    986        self._char = ""
    987        self._end = False
    988        self._peek = ""
    989        self._prev_token_line = -1

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

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

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

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

    1432    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1433        if not self._RS_TOKENIZER:
    1434            raise SqlglotError("Rust tokenizer is not available")
    1435
    1436        try:
    1437            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1438            for token in tokens:
    1439                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1440            return tokens
    1441        except Exception as e:
    1442            raise TokenError(str(e))

size
sql
tokens