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

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

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

    387    @classmethod
    388    def number(cls, number: int) -> Token:
    389        """Returns a NUMBER token with `number` as its text."""
    390        return cls(TokenType.NUMBER, str(number))

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

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

    392    @classmethod
    393    def string(cls, string: str) -> Token:
    394        """Returns a STRING token with `string` as its text."""
    395        return cls(TokenType.STRING, string)

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

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

    397    @classmethod
    398    def identifier(cls, identifier: str) -> Token:
    399        """Returns an IDENTIFIER token with `identifier` as its text."""
    400        return cls(TokenType.IDENTIFIER, identifier)

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

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

    402    @classmethod
    403    def var(cls, var: str) -> Token:
    404        """Returns an VAR token with `var` as its text."""
    405        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

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

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

    914    def __init__(self, dialect: DialectType = None) -> None:
    915        from sqlglot.dialects import Dialect
    916
    917        self.dialect = Dialect.get_or_raise(dialect)
    918
    919        if USE_RS_TOKENIZER:
    920            self._rs_dialect_settings = RsTokenizerDialectSettings(
    921                escape_sequences=self.dialect.ESCAPE_SEQUENCES,
    922                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    923            )
    924
    925        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.QUOTE: 'QUOTE'>, '`': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '"': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '#': <TokenType.HASH: 'HASH'>}
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'>, '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'>, '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'>, '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'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'COPY': <TokenType.COMMAND: 'COMMAND'>, '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.SHOW: 'SHOW'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.FETCH: 'FETCH'>, <TokenType.COMMAND: 'COMMAND'>}
COMMAND_PREFIX_TOKENS = {<TokenType.SEMICOLON: 'SEMICOLON'>, <TokenType.BEGIN: 'BEGIN'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
def reset(self) -> None: View Source

    927    def reset(self) -> None:
    928        self.sql = ""
    929        self.size = 0
    930        self.tokens: t.List[Token] = []
    931        self._start = 0
    932        self._current = 0
    933        self._line = 1
    934        self._col = 0
    935        self._comments: t.List[str] = []
    936
    937        self._char = ""
    938        self._end = False
    939        self._peek = ""
    940        self._prev_token_line = -1

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

    942    def tokenize(self, sql: str) -> t.List[Token]:
    943        """Returns a list of tokens corresponding to the SQL string `sql`."""
    944        if USE_RS_TOKENIZER:
    945            return self.tokenize_rs(sql)
    946
    947        self.reset()
    948        self.sql = sql
    949        self.size = len(sql)
    950
    951        try:
    952            self._scan()
    953        except Exception as e:
    954            start = max(self._current - 50, 0)
    955            end = min(self._current + 50, self.size - 1)
    956            context = self.sql[start:end]
    957            raise TokenError(f"Error tokenizing '{context}'") from e
    958
    959        return self.tokens

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

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

    1356    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1357        if not self._RS_TOKENIZER:
    1358            raise SqlglotError("Rust tokenizer is not available")
    1359
    1360        try:
    1361            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1362            for token in tokens:
    1363                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1364            return tokens
    1365        except Exception as e:
    1366            raise TokenError(str(e))

size
sql
tokens