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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    898    def __init__(self, dialect: DialectType = None) -> None:
    899        from sqlglot.dialects import Dialect
    900
    901        self.dialect = Dialect.get_or_raise(dialect)
    902
    903        if USE_RS_TOKENIZER:
    904            self._rs_dialect_settings = RsTokenizerDialectSettings(
    905                escape_sequences=self.dialect.ESCAPE_SEQUENCES,
    906                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    907            )
    908
    909        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()
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.COMMAND: 'COMMAND'>, <TokenType.FETCH: 'FETCH'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.SHOW: 'SHOW'>}
COMMAND_PREFIX_TOKENS = {<TokenType.BEGIN: 'BEGIN'>, <TokenType.SEMICOLON: 'SEMICOLON'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
def reset(self) -> None: View Source

    911    def reset(self) -> None:
    912        self.sql = ""
    913        self.size = 0
    914        self.tokens: t.List[Token] = []
    915        self._start = 0
    916        self._current = 0
    917        self._line = 1
    918        self._col = 0
    919        self._comments: t.List[str] = []
    920
    921        self._char = ""
    922        self._end = False
    923        self._peek = ""
    924        self._prev_token_line = -1

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

    926    def tokenize(self, sql: str) -> t.List[Token]:
    927        """Returns a list of tokens corresponding to the SQL string `sql`."""
    928        if USE_RS_TOKENIZER:
    929            return self.tokenize_rs(sql)
    930
    931        self.reset()
    932        self.sql = sql
    933        self.size = len(sql)
    934
    935        try:
    936            self._scan()
    937        except Exception as e:
    938            start = max(self._current - 50, 0)
    939            end = min(self._current + 50, self.size - 1)
    940            context = self.sql[start:end]
    941            raise TokenError(f"Error tokenizing '{context}'") from e
    942
    943        return self.tokens

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

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

    1029    def peek(self, i: int = 0) -> str:
    1030        i = self._current + i
    1031        if i < self.size:
    1032            return self.sql[i]
    1033        return ""

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

    1338    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1339        if not self._RS_TOKENIZER:
    1340            raise SqlglotError("Rust tokenizer is not available")
    1341
    1342        try:
    1343            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1344            for token in tokens:
    1345                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1346            return tokens
    1347        except Exception as e:
    1348            raise TokenError(str(e))

size
sql
tokens