sqlglot.tokens API documentation

Edit on GitHub

# sqlglot.tokens

View Source

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

class TokenType(sqlglot.helper.AutoName): View Source

     29class TokenType(AutoName):
     30    L_PAREN = auto()
     31    R_PAREN = auto()
     32    L_BRACKET = auto()
     33    R_BRACKET = auto()
     34    L_BRACE = auto()
     35    R_BRACE = auto()
     36    COMMA = auto()
     37    DOT = auto()
     38    DASH = auto()
     39    PLUS = auto()
     40    COLON = auto()
     41    DCOLON = auto()
     42    DQMARK = auto()
     43    SEMICOLON = auto()
     44    STAR = auto()
     45    BACKSLASH = auto()
     46    SLASH = auto()
     47    LT = auto()
     48    LTE = auto()
     49    GT = auto()
     50    GTE = auto()
     51    NOT = auto()
     52    EQ = auto()
     53    NEQ = auto()
     54    NULLSAFE_EQ = auto()
     55    COLON_EQ = auto()
     56    AND = auto()
     57    OR = auto()
     58    AMP = auto()
     59    DPIPE = auto()
     60    PIPE = auto()
     61    PIPE_SLASH = auto()
     62    DPIPE_SLASH = auto()
     63    CARET = auto()
     64    TILDA = auto()
     65    ARROW = auto()
     66    DARROW = auto()
     67    FARROW = auto()
     68    HASH = auto()
     69    HASH_ARROW = auto()
     70    DHASH_ARROW = auto()
     71    LR_ARROW = auto()
     72    DAT = auto()
     73    LT_AT = auto()
     74    AT_GT = auto()
     75    DOLLAR = auto()
     76    PARAMETER = auto()
     77    SESSION_PARAMETER = auto()
     78    DAMP = auto()
     79    XOR = auto()
     80    DSTAR = auto()
     81
     82    BLOCK_START = auto()
     83    BLOCK_END = auto()
     84
     85    SPACE = auto()
     86    BREAK = auto()
     87
     88    STRING = auto()
     89    NUMBER = auto()
     90    IDENTIFIER = auto()
     91    DATABASE = auto()
     92    COLUMN = auto()
     93    COLUMN_DEF = auto()
     94    SCHEMA = auto()
     95    TABLE = auto()
     96    VAR = auto()
     97    BIT_STRING = auto()
     98    HEX_STRING = auto()
     99    BYTE_STRING = auto()
    100    NATIONAL_STRING = auto()
    101    RAW_STRING = auto()
    102    HEREDOC_STRING = auto()
    103    UNICODE_STRING = auto()
    104
    105    # types
    106    BIT = auto()
    107    BOOLEAN = auto()
    108    TINYINT = auto()
    109    UTINYINT = auto()
    110    SMALLINT = auto()
    111    USMALLINT = auto()
    112    MEDIUMINT = auto()
    113    UMEDIUMINT = auto()
    114    INT = auto()
    115    UINT = auto()
    116    BIGINT = auto()
    117    UBIGINT = auto()
    118    INT128 = auto()
    119    UINT128 = auto()
    120    INT256 = auto()
    121    UINT256 = auto()
    122    FLOAT = auto()
    123    DOUBLE = auto()
    124    DECIMAL = auto()
    125    UDECIMAL = auto()
    126    BIGDECIMAL = auto()
    127    CHAR = auto()
    128    NCHAR = auto()
    129    VARCHAR = auto()
    130    NVARCHAR = auto()
    131    BPCHAR = auto()
    132    TEXT = auto()
    133    MEDIUMTEXT = auto()
    134    LONGTEXT = auto()
    135    MEDIUMBLOB = auto()
    136    LONGBLOB = auto()
    137    TINYBLOB = auto()
    138    TINYTEXT = auto()
    139    NAME = auto()
    140    BINARY = auto()
    141    VARBINARY = auto()
    142    JSON = auto()
    143    JSONB = auto()
    144    TIME = auto()
    145    TIMETZ = auto()
    146    TIMESTAMP = auto()
    147    TIMESTAMPTZ = auto()
    148    TIMESTAMPLTZ = auto()
    149    TIMESTAMPNTZ = auto()
    150    TIMESTAMP_S = auto()
    151    TIMESTAMP_MS = auto()
    152    TIMESTAMP_NS = auto()
    153    DATETIME = auto()
    154    DATETIME64 = auto()
    155    DATE = auto()
    156    DATE32 = auto()
    157    INT4RANGE = auto()
    158    INT4MULTIRANGE = auto()
    159    INT8RANGE = auto()
    160    INT8MULTIRANGE = auto()
    161    NUMRANGE = auto()
    162    NUMMULTIRANGE = auto()
    163    TSRANGE = auto()
    164    TSMULTIRANGE = auto()
    165    TSTZRANGE = auto()
    166    TSTZMULTIRANGE = auto()
    167    DATERANGE = auto()
    168    DATEMULTIRANGE = auto()
    169    UUID = auto()
    170    GEOGRAPHY = auto()
    171    NULLABLE = auto()
    172    GEOMETRY = auto()
    173    HLLSKETCH = auto()
    174    HSTORE = auto()
    175    SUPER = auto()
    176    SERIAL = auto()
    177    SMALLSERIAL = auto()
    178    BIGSERIAL = auto()
    179    XML = auto()
    180    YEAR = auto()
    181    UNIQUEIDENTIFIER = auto()
    182    USERDEFINED = auto()
    183    MONEY = auto()
    184    SMALLMONEY = auto()
    185    ROWVERSION = auto()
    186    IMAGE = auto()
    187    VARIANT = auto()
    188    OBJECT = auto()
    189    INET = auto()
    190    IPADDRESS = auto()
    191    IPPREFIX = auto()
    192    IPV4 = auto()
    193    IPV6 = auto()
    194    ENUM = auto()
    195    ENUM8 = auto()
    196    ENUM16 = auto()
    197    FIXEDSTRING = auto()
    198    LOWCARDINALITY = auto()
    199    NESTED = auto()
    200    AGGREGATEFUNCTION = auto()
    201    SIMPLEAGGREGATEFUNCTION = auto()
    202    TDIGEST = auto()
    203    UNKNOWN = auto()
    204
    205    # keywords
    206    ALIAS = auto()
    207    ALTER = auto()
    208    ALWAYS = auto()
    209    ALL = auto()
    210    ANTI = auto()
    211    ANY = auto()
    212    APPLY = auto()
    213    ARRAY = auto()
    214    ASC = auto()
    215    ASOF = auto()
    216    AUTO_INCREMENT = auto()
    217    BEGIN = auto()
    218    BETWEEN = auto()
    219    CACHE = auto()
    220    CASE = auto()
    221    CHARACTER_SET = auto()
    222    CLUSTER_BY = auto()
    223    COLLATE = auto()
    224    COMMAND = auto()
    225    COMMENT = auto()
    226    COMMIT = auto()
    227    CONNECT_BY = auto()
    228    CONSTRAINT = auto()
    229    COPY = auto()
    230    CREATE = auto()
    231    CROSS = auto()
    232    CUBE = auto()
    233    CURRENT_DATE = auto()
    234    CURRENT_DATETIME = auto()
    235    CURRENT_TIME = auto()
    236    CURRENT_TIMESTAMP = auto()
    237    CURRENT_USER = auto()
    238    DEFAULT = auto()
    239    DELETE = auto()
    240    DESC = auto()
    241    DESCRIBE = auto()
    242    DICTIONARY = auto()
    243    DISTINCT = auto()
    244    DISTRIBUTE_BY = auto()
    245    DIV = auto()
    246    DROP = auto()
    247    ELSE = auto()
    248    END = auto()
    249    ESCAPE = auto()
    250    EXCEPT = auto()
    251    EXECUTE = auto()
    252    EXISTS = auto()
    253    FALSE = auto()
    254    FETCH = auto()
    255    FILTER = auto()
    256    FINAL = auto()
    257    FIRST = auto()
    258    FOR = auto()
    259    FORCE = auto()
    260    FOREIGN_KEY = auto()
    261    FORMAT = auto()
    262    FROM = auto()
    263    FULL = auto()
    264    FUNCTION = auto()
    265    GLOB = auto()
    266    GLOBAL = auto()
    267    GROUP_BY = auto()
    268    GROUPING_SETS = auto()
    269    HAVING = auto()
    270    HINT = auto()
    271    IGNORE = auto()
    272    ILIKE = auto()
    273    ILIKE_ANY = auto()
    274    IN = auto()
    275    INDEX = auto()
    276    INNER = auto()
    277    INSERT = auto()
    278    INTERSECT = auto()
    279    INTERVAL = auto()
    280    INTO = auto()
    281    INTRODUCER = auto()
    282    IRLIKE = auto()
    283    IS = auto()
    284    ISNULL = auto()
    285    JOIN = auto()
    286    JOIN_MARKER = auto()
    287    KEEP = auto()
    288    KILL = auto()
    289    LANGUAGE = auto()
    290    LATERAL = auto()
    291    LEFT = auto()
    292    LIKE = auto()
    293    LIKE_ANY = auto()
    294    LIMIT = auto()
    295    LOAD = auto()
    296    LOCK = auto()
    297    MAP = auto()
    298    MATCH_CONDITION = auto()
    299    MATCH_RECOGNIZE = auto()
    300    MEMBER_OF = auto()
    301    MERGE = auto()
    302    MOD = auto()
    303    MODEL = auto()
    304    NATURAL = auto()
    305    NEXT = auto()
    306    NOTNULL = auto()
    307    NULL = auto()
    308    OBJECT_IDENTIFIER = auto()
    309    OFFSET = auto()
    310    ON = auto()
    311    ONLY = auto()
    312    OPERATOR = auto()
    313    ORDER_BY = auto()
    314    ORDER_SIBLINGS_BY = auto()
    315    ORDERED = auto()
    316    ORDINALITY = auto()
    317    OUTER = auto()
    318    OVER = auto()
    319    OVERLAPS = auto()
    320    OVERWRITE = auto()
    321    PARTITION = auto()
    322    PARTITION_BY = auto()
    323    PERCENT = auto()
    324    PIVOT = auto()
    325    PLACEHOLDER = auto()
    326    POSITIONAL = auto()
    327    PRAGMA = auto()
    328    PREWHERE = auto()
    329    PRIMARY_KEY = auto()
    330    PROCEDURE = auto()
    331    PROPERTIES = auto()
    332    PSEUDO_TYPE = auto()
    333    QUALIFY = auto()
    334    QUOTE = auto()
    335    RANGE = auto()
    336    RECURSIVE = auto()
    337    REFRESH = auto()
    338    REPLACE = auto()
    339    RETURNING = auto()
    340    REFERENCES = auto()
    341    RIGHT = auto()
    342    RLIKE = auto()
    343    ROLLBACK = auto()
    344    ROLLUP = auto()
    345    ROW = auto()
    346    ROWS = auto()
    347    SELECT = auto()
    348    SEMI = auto()
    349    SEPARATOR = auto()
    350    SEQUENCE = auto()
    351    SERDE_PROPERTIES = auto()
    352    SET = auto()
    353    SETTINGS = auto()
    354    SHOW = auto()
    355    SIMILAR_TO = auto()
    356    SOME = auto()
    357    SORT_BY = auto()
    358    START_WITH = auto()
    359    STORAGE_INTEGRATION = auto()
    360    STRUCT = auto()
    361    TABLE_SAMPLE = auto()
    362    TEMPORARY = auto()
    363    TOP = auto()
    364    THEN = auto()
    365    TRUE = auto()
    366    TRUNCATE = auto()
    367    UNCACHE = auto()
    368    UNION = auto()
    369    UNNEST = auto()
    370    UNPIVOT = auto()
    371    UPDATE = auto()
    372    USE = auto()
    373    USING = auto()
    374    VALUES = auto()
    375    VIEW = auto()
    376    VOLATILE = auto()
    377    WHEN = auto()
    378    WHERE = auto()
    379    WINDOW = auto()
    380    WITH = auto()
    381    UNIQUE = auto()
    382    VERSION_SNAPSHOT = auto()
    383    TIMESTAMP_SNAPSHOT = auto()
    384    OPTION = auto()

An enumeration.

L_PAREN = <TokenType.L_PAREN: 'L_PAREN'>
R_PAREN = <TokenType.R_PAREN: 'R_PAREN'>
L_BRACKET = <TokenType.L_BRACKET: 'L_BRACKET'>
R_BRACKET = <TokenType.R_BRACKET: 'R_BRACKET'>
L_BRACE = <TokenType.L_BRACE: 'L_BRACE'>
R_BRACE = <TokenType.R_BRACE: 'R_BRACE'>
COMMA = <TokenType.COMMA: 'COMMA'>
DOT = <TokenType.DOT: 'DOT'>
DASH = <TokenType.DASH: 'DASH'>
PLUS = <TokenType.PLUS: 'PLUS'>
COLON = <TokenType.COLON: 'COLON'>
DCOLON = <TokenType.DCOLON: 'DCOLON'>
DQMARK = <TokenType.DQMARK: 'DQMARK'>
SEMICOLON = <TokenType.SEMICOLON: 'SEMICOLON'>
STAR = <TokenType.STAR: 'STAR'>
BACKSLASH = <TokenType.BACKSLASH: 'BACKSLASH'>
SLASH = <TokenType.SLASH: 'SLASH'>
LT = <TokenType.LT: 'LT'>
LTE = <TokenType.LTE: 'LTE'>
GT = <TokenType.GT: 'GT'>
GTE = <TokenType.GTE: 'GTE'>
NOT = <TokenType.NOT: 'NOT'>
EQ = <TokenType.EQ: 'EQ'>
NEQ = <TokenType.NEQ: 'NEQ'>
NULLSAFE_EQ = <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>
COLON_EQ = <TokenType.COLON_EQ: 'COLON_EQ'>
AND = <TokenType.AND: 'AND'>
OR = <TokenType.OR: 'OR'>
AMP = <TokenType.AMP: 'AMP'>
DPIPE = <TokenType.DPIPE: 'DPIPE'>
PIPE = <TokenType.PIPE: 'PIPE'>
PIPE_SLASH = <TokenType.PIPE_SLASH: 'PIPE_SLASH'>
DPIPE_SLASH = <TokenType.DPIPE_SLASH: 'DPIPE_SLASH'>
CARET = <TokenType.CARET: 'CARET'>
TILDA = <TokenType.TILDA: 'TILDA'>
ARROW = <TokenType.ARROW: 'ARROW'>
DARROW = <TokenType.DARROW: 'DARROW'>
FARROW = <TokenType.FARROW: 'FARROW'>
HASH = <TokenType.HASH: 'HASH'>
HASH_ARROW = <TokenType.HASH_ARROW: 'HASH_ARROW'>
DHASH_ARROW = <TokenType.DHASH_ARROW: 'DHASH_ARROW'>
LR_ARROW = <TokenType.LR_ARROW: 'LR_ARROW'>
DAT = <TokenType.DAT: 'DAT'>
LT_AT = <TokenType.LT_AT: 'LT_AT'>
AT_GT = <TokenType.AT_GT: 'AT_GT'>
DOLLAR = <TokenType.DOLLAR: 'DOLLAR'>
PARAMETER = <TokenType.PARAMETER: 'PARAMETER'>
SESSION_PARAMETER = <TokenType.SESSION_PARAMETER: 'SESSION_PARAMETER'>
DAMP = <TokenType.DAMP: 'DAMP'>
XOR = <TokenType.XOR: 'XOR'>
DSTAR = <TokenType.DSTAR: 'DSTAR'>
BLOCK_START = <TokenType.BLOCK_START: 'BLOCK_START'>
BLOCK_END = <TokenType.BLOCK_END: 'BLOCK_END'>
SPACE = <TokenType.SPACE: 'SPACE'>
BREAK = <TokenType.BREAK: 'BREAK'>
STRING = <TokenType.STRING: 'STRING'>
NUMBER = <TokenType.NUMBER: 'NUMBER'>
IDENTIFIER = <TokenType.IDENTIFIER: 'IDENTIFIER'>
DATABASE = <TokenType.DATABASE: 'DATABASE'>
COLUMN = <TokenType.COLUMN: 'COLUMN'>
COLUMN_DEF = <TokenType.COLUMN_DEF: 'COLUMN_DEF'>
SCHEMA = <TokenType.SCHEMA: 'SCHEMA'>
TABLE = <TokenType.TABLE: 'TABLE'>
VAR = <TokenType.VAR: 'VAR'>
BIT_STRING = <TokenType.BIT_STRING: 'BIT_STRING'>
HEX_STRING = <TokenType.HEX_STRING: 'HEX_STRING'>
BYTE_STRING = <TokenType.BYTE_STRING: 'BYTE_STRING'>
NATIONAL_STRING = <TokenType.NATIONAL_STRING: 'NATIONAL_STRING'>
RAW_STRING = <TokenType.RAW_STRING: 'RAW_STRING'>
HEREDOC_STRING = <TokenType.HEREDOC_STRING: 'HEREDOC_STRING'>
UNICODE_STRING = <TokenType.UNICODE_STRING: 'UNICODE_STRING'>
BIT = <TokenType.BIT: 'BIT'>
BOOLEAN = <TokenType.BOOLEAN: 'BOOLEAN'>
TINYINT = <TokenType.TINYINT: 'TINYINT'>
UTINYINT = <TokenType.UTINYINT: 'UTINYINT'>
SMALLINT = <TokenType.SMALLINT: 'SMALLINT'>
USMALLINT = <TokenType.USMALLINT: 'USMALLINT'>
MEDIUMINT = <TokenType.MEDIUMINT: 'MEDIUMINT'>
UMEDIUMINT = <TokenType.UMEDIUMINT: 'UMEDIUMINT'>
INT = <TokenType.INT: 'INT'>
UINT = <TokenType.UINT: 'UINT'>
BIGINT = <TokenType.BIGINT: 'BIGINT'>
UBIGINT = <TokenType.UBIGINT: 'UBIGINT'>
INT128 = <TokenType.INT128: 'INT128'>
UINT128 = <TokenType.UINT128: 'UINT128'>
INT256 = <TokenType.INT256: 'INT256'>
UINT256 = <TokenType.UINT256: 'UINT256'>
FLOAT = <TokenType.FLOAT: 'FLOAT'>
DOUBLE = <TokenType.DOUBLE: 'DOUBLE'>
DECIMAL = <TokenType.DECIMAL: 'DECIMAL'>
UDECIMAL = <TokenType.UDECIMAL: 'UDECIMAL'>
BIGDECIMAL = <TokenType.BIGDECIMAL: 'BIGDECIMAL'>
CHAR = <TokenType.CHAR: 'CHAR'>
NCHAR = <TokenType.NCHAR: 'NCHAR'>
VARCHAR = <TokenType.VARCHAR: 'VARCHAR'>
NVARCHAR = <TokenType.NVARCHAR: 'NVARCHAR'>
BPCHAR = <TokenType.BPCHAR: 'BPCHAR'>
TEXT = <TokenType.TEXT: 'TEXT'>
MEDIUMTEXT = <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <TokenType.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <TokenType.LONGBLOB: 'LONGBLOB'>
TINYBLOB = <TokenType.TINYBLOB: 'TINYBLOB'>
TINYTEXT = <TokenType.TINYTEXT: 'TINYTEXT'>
NAME = <TokenType.NAME: 'NAME'>
BINARY = <TokenType.BINARY: 'BINARY'>
VARBINARY = <TokenType.VARBINARY: 'VARBINARY'>
JSON = <TokenType.JSON: 'JSON'>
JSONB = <TokenType.JSONB: 'JSONB'>
TIME = <TokenType.TIME: 'TIME'>
TIMETZ = <TokenType.TIMETZ: 'TIMETZ'>
TIMESTAMP = <TokenType.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPNTZ = <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>
TIMESTAMP_S = <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>
TIMESTAMP_MS = <TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>
TIMESTAMP_NS = <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>
DATETIME = <TokenType.DATETIME: 'DATETIME'>
DATETIME64 = <TokenType.DATETIME64: 'DATETIME64'>
DATE = <TokenType.DATE: 'DATE'>
DATE32 = <TokenType.DATE32: 'DATE32'>
INT4RANGE = <TokenType.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <TokenType.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <TokenType.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <TokenType.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <TokenType.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <TokenType.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>
UUID = <TokenType.UUID: 'UUID'>
GEOGRAPHY = <TokenType.GEOGRAPHY: 'GEOGRAPHY'>
NULLABLE = <TokenType.NULLABLE: 'NULLABLE'>
GEOMETRY = <TokenType.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <TokenType.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <TokenType.HSTORE: 'HSTORE'>
SUPER = <TokenType.SUPER: 'SUPER'>
SERIAL = <TokenType.SERIAL: 'SERIAL'>
SMALLSERIAL = <TokenType.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <TokenType.BIGSERIAL: 'BIGSERIAL'>
XML = <TokenType.XML: 'XML'>
YEAR = <TokenType.YEAR: 'YEAR'>
UNIQUEIDENTIFIER = <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
USERDEFINED = <TokenType.USERDEFINED: 'USERDEFINED'>
MONEY = <TokenType.MONEY: 'MONEY'>
SMALLMONEY = <TokenType.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <TokenType.ROWVERSION: 'ROWVERSION'>
IMAGE = <TokenType.IMAGE: 'IMAGE'>
VARIANT = <TokenType.VARIANT: 'VARIANT'>
OBJECT = <TokenType.OBJECT: 'OBJECT'>
INET = <TokenType.INET: 'INET'>
IPADDRESS = <TokenType.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <TokenType.IPPREFIX: 'IPPREFIX'>
IPV4 = <TokenType.IPV4: 'IPV4'>
IPV6 = <TokenType.IPV6: 'IPV6'>
ENUM = <TokenType.ENUM: 'ENUM'>
ENUM8 = <TokenType.ENUM8: 'ENUM8'>
ENUM16 = <TokenType.ENUM16: 'ENUM16'>
FIXEDSTRING = <TokenType.FIXEDSTRING: 'FIXEDSTRING'>
LOWCARDINALITY = <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>
NESTED = <TokenType.NESTED: 'NESTED'>
AGGREGATEFUNCTION = <TokenType.AGGREGATEFUNCTION: 'AGGREGATEFUNCTION'>
SIMPLEAGGREGATEFUNCTION = <TokenType.SIMPLEAGGREGATEFUNCTION: 'SIMPLEAGGREGATEFUNCTION'>
TDIGEST = <TokenType.TDIGEST: 'TDIGEST'>
UNKNOWN = <TokenType.UNKNOWN: 'UNKNOWN'>
ALIAS = <TokenType.ALIAS: 'ALIAS'>
ALTER = <TokenType.ALTER: 'ALTER'>
ALWAYS = <TokenType.ALWAYS: 'ALWAYS'>
ALL = <TokenType.ALL: 'ALL'>
ANTI = <TokenType.ANTI: 'ANTI'>
ANY = <TokenType.ANY: 'ANY'>
APPLY = <TokenType.APPLY: 'APPLY'>
ARRAY = <TokenType.ARRAY: 'ARRAY'>
ASC = <TokenType.ASC: 'ASC'>
ASOF = <TokenType.ASOF: 'ASOF'>
AUTO_INCREMENT = <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>
BEGIN = <TokenType.BEGIN: 'BEGIN'>
BETWEEN = <TokenType.BETWEEN: 'BETWEEN'>
CACHE = <TokenType.CACHE: 'CACHE'>
CASE = <TokenType.CASE: 'CASE'>
CHARACTER_SET = <TokenType.CHARACTER_SET: 'CHARACTER_SET'>
CLUSTER_BY = <TokenType.CLUSTER_BY: 'CLUSTER_BY'>
COLLATE = <TokenType.COLLATE: 'COLLATE'>
COMMAND = <TokenType.COMMAND: 'COMMAND'>
COMMENT = <TokenType.COMMENT: 'COMMENT'>
COMMIT = <TokenType.COMMIT: 'COMMIT'>
CONNECT_BY = <TokenType.CONNECT_BY: 'CONNECT_BY'>
CONSTRAINT = <TokenType.CONSTRAINT: 'CONSTRAINT'>
COPY = <TokenType.COPY: 'COPY'>
CREATE = <TokenType.CREATE: 'CREATE'>
CROSS = <TokenType.CROSS: 'CROSS'>
CUBE = <TokenType.CUBE: 'CUBE'>
CURRENT_DATE = <TokenType.CURRENT_DATE: 'CURRENT_DATE'>
CURRENT_DATETIME = <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>
CURRENT_TIME = <TokenType.CURRENT_TIME: 'CURRENT_TIME'>
CURRENT_TIMESTAMP = <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>
CURRENT_USER = <TokenType.CURRENT_USER: 'CURRENT_USER'>
DEFAULT = <TokenType.DEFAULT: 'DEFAULT'>
DELETE = <TokenType.DELETE: 'DELETE'>
DESC = <TokenType.DESC: 'DESC'>
DESCRIBE = <TokenType.DESCRIBE: 'DESCRIBE'>
DICTIONARY = <TokenType.DICTIONARY: 'DICTIONARY'>
DISTINCT = <TokenType.DISTINCT: 'DISTINCT'>
DISTRIBUTE_BY = <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>
DIV = <TokenType.DIV: 'DIV'>
DROP = <TokenType.DROP: 'DROP'>
ELSE = <TokenType.ELSE: 'ELSE'>
END = <TokenType.END: 'END'>
ESCAPE = <TokenType.ESCAPE: 'ESCAPE'>
EXCEPT = <TokenType.EXCEPT: 'EXCEPT'>
EXECUTE = <TokenType.EXECUTE: 'EXECUTE'>
EXISTS = <TokenType.EXISTS: 'EXISTS'>
FALSE = <TokenType.FALSE: 'FALSE'>
FETCH = <TokenType.FETCH: 'FETCH'>
FILTER = <TokenType.FILTER: 'FILTER'>
FINAL = <TokenType.FINAL: 'FINAL'>
FIRST = <TokenType.FIRST: 'FIRST'>
FOR = <TokenType.FOR: 'FOR'>
FORCE = <TokenType.FORCE: 'FORCE'>
FOREIGN_KEY = <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>
FORMAT = <TokenType.FORMAT: 'FORMAT'>
FROM = <TokenType.FROM: 'FROM'>
FULL = <TokenType.FULL: 'FULL'>
FUNCTION = <TokenType.FUNCTION: 'FUNCTION'>
GLOB = <TokenType.GLOB: 'GLOB'>
GLOBAL = <TokenType.GLOBAL: 'GLOBAL'>
GROUP_BY = <TokenType.GROUP_BY: 'GROUP_BY'>
GROUPING_SETS = <TokenType.GROUPING_SETS: 'GROUPING_SETS'>
HAVING = <TokenType.HAVING: 'HAVING'>
HINT = <TokenType.HINT: 'HINT'>
IGNORE = <TokenType.IGNORE: 'IGNORE'>
ILIKE = <TokenType.ILIKE: 'ILIKE'>
ILIKE_ANY = <TokenType.ILIKE_ANY: 'ILIKE_ANY'>
IN = <TokenType.IN: 'IN'>
INDEX = <TokenType.INDEX: 'INDEX'>
INNER = <TokenType.INNER: 'INNER'>
INSERT = <TokenType.INSERT: 'INSERT'>
INTERSECT = <TokenType.INTERSECT: 'INTERSECT'>
INTERVAL = <TokenType.INTERVAL: 'INTERVAL'>
INTO = <TokenType.INTO: 'INTO'>
INTRODUCER = <TokenType.INTRODUCER: 'INTRODUCER'>
IRLIKE = <TokenType.IRLIKE: 'IRLIKE'>
IS = <TokenType.IS: 'IS'>
ISNULL = <TokenType.ISNULL: 'ISNULL'>
JOIN = <TokenType.JOIN: 'JOIN'>
JOIN_MARKER = <TokenType.JOIN_MARKER: 'JOIN_MARKER'>
KEEP = <TokenType.KEEP: 'KEEP'>
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'>
LOAD = <TokenType.LOAD: 'LOAD'>
LOCK = <TokenType.LOCK: 'LOCK'>
MAP = <TokenType.MAP: 'MAP'>
MATCH_CONDITION = <TokenType.MATCH_CONDITION: 'MATCH_CONDITION'>
MATCH_RECOGNIZE = <TokenType.MATCH_RECOGNIZE: 'MATCH_RECOGNIZE'>
MEMBER_OF = <TokenType.MEMBER_OF: 'MEMBER_OF'>
MERGE = <TokenType.MERGE: 'MERGE'>
MOD = <TokenType.MOD: 'MOD'>
MODEL = <TokenType.MODEL: 'MODEL'>
NATURAL = <TokenType.NATURAL: 'NATURAL'>
NEXT = <TokenType.NEXT: 'NEXT'>
NOTNULL = <TokenType.NOTNULL: 'NOTNULL'>
NULL = <TokenType.NULL: 'NULL'>
OBJECT_IDENTIFIER = <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>
OFFSET = <TokenType.OFFSET: 'OFFSET'>
ON = <TokenType.ON: 'ON'>
ONLY = <TokenType.ONLY: 'ONLY'>
OPERATOR = <TokenType.OPERATOR: 'OPERATOR'>
ORDER_BY = <TokenType.ORDER_BY: 'ORDER_BY'>
ORDER_SIBLINGS_BY = <TokenType.ORDER_SIBLINGS_BY: 'ORDER_SIBLINGS_BY'>
ORDERED = <TokenType.ORDERED: 'ORDERED'>
ORDINALITY = <TokenType.ORDINALITY: 'ORDINALITY'>
OUTER = <TokenType.OUTER: 'OUTER'>
OVER = <TokenType.OVER: 'OVER'>
OVERLAPS = <TokenType.OVERLAPS: 'OVERLAPS'>
OVERWRITE = <TokenType.OVERWRITE: 'OVERWRITE'>
PARTITION = <TokenType.PARTITION: 'PARTITION'>
PARTITION_BY = <TokenType.PARTITION_BY: 'PARTITION_BY'>
PERCENT = <TokenType.PERCENT: 'PERCENT'>
PIVOT = <TokenType.PIVOT: 'PIVOT'>
PLACEHOLDER = <TokenType.PLACEHOLDER: 'PLACEHOLDER'>
POSITIONAL = <TokenType.POSITIONAL: 'POSITIONAL'>
PRAGMA = <TokenType.PRAGMA: 'PRAGMA'>
PREWHERE = <TokenType.PREWHERE: 'PREWHERE'>
PRIMARY_KEY = <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>
PROCEDURE = <TokenType.PROCEDURE: 'PROCEDURE'>
PROPERTIES = <TokenType.PROPERTIES: 'PROPERTIES'>
PSEUDO_TYPE = <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>
QUALIFY = <TokenType.QUALIFY: 'QUALIFY'>
QUOTE = <TokenType.QUOTE: 'QUOTE'>
RANGE = <TokenType.RANGE: 'RANGE'>
RECURSIVE = <TokenType.RECURSIVE: 'RECURSIVE'>
REFRESH = <TokenType.REFRESH: 'REFRESH'>
REPLACE = <TokenType.REPLACE: 'REPLACE'>
RETURNING = <TokenType.RETURNING: 'RETURNING'>
REFERENCES = <TokenType.REFERENCES: 'REFERENCES'>
RIGHT = <TokenType.RIGHT: 'RIGHT'>
RLIKE = <TokenType.RLIKE: 'RLIKE'>
ROLLBACK = <TokenType.ROLLBACK: 'ROLLBACK'>
ROLLUP = <TokenType.ROLLUP: 'ROLLUP'>
ROW = <TokenType.ROW: 'ROW'>
ROWS = <TokenType.ROWS: 'ROWS'>
SELECT = <TokenType.SELECT: 'SELECT'>
SEMI = <TokenType.SEMI: 'SEMI'>
SEPARATOR = <TokenType.SEPARATOR: 'SEPARATOR'>
SEQUENCE = <TokenType.SEQUENCE: 'SEQUENCE'>
SERDE_PROPERTIES = <TokenType.SERDE_PROPERTIES: 'SERDE_PROPERTIES'>
SET = <TokenType.SET: 'SET'>
SETTINGS = <TokenType.SETTINGS: 'SETTINGS'>
SHOW = <TokenType.SHOW: 'SHOW'>
SIMILAR_TO = <TokenType.SIMILAR_TO: 'SIMILAR_TO'>
SOME = <TokenType.SOME: 'SOME'>
SORT_BY = <TokenType.SORT_BY: 'SORT_BY'>
START_WITH = <TokenType.START_WITH: 'START_WITH'>
STORAGE_INTEGRATION = <TokenType.STORAGE_INTEGRATION: 'STORAGE_INTEGRATION'>
STRUCT = <TokenType.STRUCT: 'STRUCT'>
TABLE_SAMPLE = <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>
TEMPORARY = <TokenType.TEMPORARY: 'TEMPORARY'>
TOP = <TokenType.TOP: 'TOP'>
THEN = <TokenType.THEN: 'THEN'>
TRUE = <TokenType.TRUE: 'TRUE'>
TRUNCATE = <TokenType.TRUNCATE: 'TRUNCATE'>
UNCACHE = <TokenType.UNCACHE: 'UNCACHE'>
UNION = <TokenType.UNION: 'UNION'>
UNNEST = <TokenType.UNNEST: 'UNNEST'>
UNPIVOT = <TokenType.UNPIVOT: 'UNPIVOT'>
UPDATE = <TokenType.UPDATE: 'UPDATE'>
USE = <TokenType.USE: 'USE'>
USING = <TokenType.USING: 'USING'>
VALUES = <TokenType.VALUES: 'VALUES'>
VIEW = <TokenType.VIEW: 'VIEW'>
VOLATILE = <TokenType.VOLATILE: 'VOLATILE'>
WHEN = <TokenType.WHEN: 'WHEN'>
WHERE = <TokenType.WHERE: 'WHERE'>
WINDOW = <TokenType.WINDOW: 'WINDOW'>
WITH = <TokenType.WITH: 'WITH'>
UNIQUE = <TokenType.UNIQUE: 'UNIQUE'>
VERSION_SNAPSHOT = <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>
TIMESTAMP_SNAPSHOT = <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>
OPTION = <TokenType.OPTION: 'OPTION'>

##### Inherited Members

enum.Enum
  name
  value

class Token: View Source

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

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

    394    @classmethod
    395    def number(cls, number: int) -> Token:
    396        """Returns a NUMBER token with `number` as its text."""
    397        return cls(TokenType.NUMBER, str(number))

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

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

    399    @classmethod
    400    def string(cls, string: str) -> Token:
    401        """Returns a STRING token with `string` as its text."""
    402        return cls(TokenType.STRING, string)

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

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

    404    @classmethod
    405    def identifier(cls, identifier: str) -> Token:
    406        """Returns an IDENTIFIER token with `identifier` as its text."""
    407        return cls(TokenType.IDENTIFIER, identifier)

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

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

    409    @classmethod
    410    def var(cls, var: str) -> Token:
    411        """Returns an VAR token with `var` as its text."""
    412        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

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

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

    926    def __init__(self, dialect: DialectType = None) -> None:
    927        from sqlglot.dialects import Dialect
    928
    929        self.dialect = Dialect.get_or_raise(dialect)
    930
    931        if USE_RS_TOKENIZER:
    932            self._rs_dialect_settings = RsTokenizerDialectSettings(
    933                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
    934                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    935            )
    936
    937        self.reset()

SINGLE_TOKENS = {'(': <TokenType.L_PAREN: 'L_PAREN'>, ')': <TokenType.R_PAREN: 'R_PAREN'>, '[': <TokenType.L_BRACKET: 'L_BRACKET'>, ']': <TokenType.R_BRACKET: 'R_BRACKET'>, '{': <TokenType.L_BRACE: 'L_BRACE'>, '}': <TokenType.R_BRACE: 'R_BRACE'>, '&': <TokenType.AMP: 'AMP'>, '^': <TokenType.CARET: 'CARET'>, ':': <TokenType.COLON: 'COLON'>, ',': <TokenType.COMMA: 'COMMA'>, '.': <TokenType.DOT: 'DOT'>, '-': <TokenType.DASH: 'DASH'>, '=': <TokenType.EQ: 'EQ'>, '>': <TokenType.GT: 'GT'>, '<': <TokenType.LT: 'LT'>, '%': <TokenType.MOD: 'MOD'>, '!': <TokenType.NOT: 'NOT'>, '|': <TokenType.PIPE: 'PIPE'>, '+': <TokenType.PLUS: 'PLUS'>, ';': <TokenType.SEMICOLON: 'SEMICOLON'>, '/': <TokenType.SLASH: 'SLASH'>, '\\': <TokenType.BACKSLASH: 'BACKSLASH'>, '*': <TokenType.STAR: 'STAR'>, '~': <TokenType.TILDA: 'TILDA'>, '?': <TokenType.PLACEHOLDER: 'PLACEHOLDER'>, '@': <TokenType.PARAMETER: 'PARAMETER'>, '#': <TokenType.HASH: 'HASH'>, "'": <TokenType.UNKNOWN: 'UNKNOWN'>, '`': <TokenType.UNKNOWN: 'UNKNOWN'>, '"': <TokenType.UNKNOWN: 'UNKNOWN'>}
BIT_STRINGS: List[Union[str, Tuple[str, str]]] = []
BYTE_STRINGS: List[Union[str, Tuple[str, str]]] = []
HEX_STRINGS: List[Union[str, Tuple[str, str]]] = []
RAW_STRINGS: List[Union[str, Tuple[str, str]]] = []
HEREDOC_STRINGS: List[Union[str, Tuple[str, str]]] = []
UNICODE_STRINGS: List[Union[str, Tuple[str, str]]] = []
IDENTIFIERS: List[Union[str, Tuple[str, str]]] = ['"']
IDENTIFIER_ESCAPES = ['"']
QUOTES: List[Union[str, Tuple[str, str]]] = ["'"]
STRING_ESCAPES = ["'"]
VAR_SINGLE_TOKENS: Set[str] = set()
HEREDOC_TAG_IS_IDENTIFIER = False
HEREDOC_STRING_ALTERNATIVE = <TokenType.VAR: 'VAR'>
KEYWORDS: Dict[str, TokenType] = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, ':=': <TokenType.COLON_EQ: 'COLON_EQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, '??': <TokenType.DQMARK: 'DQMARK'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'COPY': <TokenType.COPY: 'COPY'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ENUM': <TokenType.ENUM: 'ENUM'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'KILL': <TokenType.KILL: 'KILL'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'START WITH': <TokenType.START_WITH: 'START_WITH'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'TRUNCATE': <TokenType.TRUNCATE: 'TRUNCATE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'MEDIUMINT': <TokenType.MEDIUMINT: 'MEDIUMINT'>, 'INT1': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'INT16': <TokenType.SMALLINT: 'SMALLINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT128': <TokenType.INT128: 'INT128'>, 'HUGEINT': <TokenType.INT128: 'INT128'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'INT32': <TokenType.INT: 'INT'>, 'INT64': <TokenType.BIGINT: 'BIGINT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.TINYINT: 'TINYINT'>, 'UINT': <TokenType.UINT: 'UINT'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, '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'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'BPCHAR': <TokenType.BPCHAR: 'BPCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMP_LTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMPNTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'TIMESTAMP_NTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'SEQUENCE': <TokenType.SEQUENCE: 'SEQUENCE'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>}
WHITE_SPACE: Dict[Optional[str], TokenType] = {' ': <TokenType.SPACE: 'SPACE'>, '\t': <TokenType.SPACE: 'SPACE'>, '\n': <TokenType.BREAK: 'BREAK'>, '\r': <TokenType.BREAK: 'BREAK'>}
COMMANDS = {<TokenType.COMMAND: 'COMMAND'>, <TokenType.SHOW: 'SHOW'>, <TokenType.FETCH: 'FETCH'>, <TokenType.EXECUTE: 'EXECUTE'>}
COMMAND_PREFIX_TOKENS = {<TokenType.BEGIN: 'BEGIN'>, <TokenType.SEMICOLON: 'SEMICOLON'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
def reset(self) -> None: View Source

    939    def reset(self) -> None:
    940        self.sql = ""
    941        self.size = 0
    942        self.tokens: t.List[Token] = []
    943        self._start = 0
    944        self._current = 0
    945        self._line = 1
    946        self._col = 0
    947        self._comments: t.List[str] = []
    948
    949        self._char = ""
    950        self._end = False
    951        self._peek = ""
    952        self._prev_token_line = -1

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

    954    def tokenize(self, sql: str) -> t.List[Token]:
    955        """Returns a list of tokens corresponding to the SQL string `sql`."""
    956        if USE_RS_TOKENIZER:
    957            return self.tokenize_rs(sql)
    958
    959        self.reset()
    960        self.sql = sql
    961        self.size = len(sql)
    962
    963        try:
    964            self._scan()
    965        except Exception as e:
    966            start = max(self._current - 50, 0)
    967            end = min(self._current + 50, self.size - 1)
    968            context = self.sql[start:end]
    969            raise TokenError(f"Error tokenizing '{context}'") from e
    970
    971        return self.tokens

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

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

    1385    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1386        if not self._RS_TOKENIZER:
    1387            raise SqlglotError("Rust tokenizer is not available")
    1388
    1389        try:
    1390            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1391            for token in tokens:
    1392                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1393            return tokens
    1394        except Exception as e:
    1395            raise TokenError(str(e))

size
sql
tokens