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

##### Inherited Members

enum.Enum
  name
  value

class Token: View Source

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

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

    382    @classmethod
    383    def number(cls, number: int) -> Token:
    384        """Returns a NUMBER token with `number` as its text."""
    385        return cls(TokenType.NUMBER, str(number))

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

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

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

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

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

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

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

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

    397    @classmethod
    398    def var(cls, var: str) -> Token:
    399        """Returns an VAR token with `var` as its text."""
    400        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

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

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

    908    def __init__(self, dialect: DialectType = None) -> None:
    909        from sqlglot.dialects import Dialect
    910
    911        self.dialect = Dialect.get_or_raise(dialect)
    912
    913        if USE_RS_TOKENIZER:
    914            self._rs_dialect_settings = RsTokenizerDialectSettings(
    915                escape_sequences=self.dialect.ESCAPE_SEQUENCES,
    916                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    917            )
    918
    919        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'>, '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'>, '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'>, 'TRUNCATE': <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.FETCH: 'FETCH'>, <TokenType.SHOW: 'SHOW'>, <TokenType.EXECUTE: 'EXECUTE'>, <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

    921    def reset(self) -> None:
    922        self.sql = ""
    923        self.size = 0
    924        self.tokens: t.List[Token] = []
    925        self._start = 0
    926        self._current = 0
    927        self._line = 1
    928        self._col = 0
    929        self._comments: t.List[str] = []
    930
    931        self._char = ""
    932        self._end = False
    933        self._peek = ""
    934        self._prev_token_line = -1

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

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

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

def peek(self, i: int = 0) -> str: View Source

    1039    def peek(self, i: int = 0) -> str:
    1040        i = self._current + i
    1041        if i < self.size:
    1042            return self.sql[i]
    1043        return ""

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

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

size
sql
tokens