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

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'>
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

    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}>"

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

    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

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

    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))

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

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

    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)

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

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

    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)

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

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

    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)

Returns an VAR token with `var` as its text.

token_type
text
line
col
start
end
comments
class Tokenizer: View Source

     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        "STR": TokenType.TEXT,
     806        "STRING": TokenType.TEXT,
     807        "TEXT": TokenType.TEXT,
     808        "LONGTEXT": TokenType.LONGTEXT,
     809        "MEDIUMTEXT": TokenType.MEDIUMTEXT,
     810        "TINYTEXT": TokenType.TINYTEXT,
     811        "CLOB": TokenType.TEXT,
     812        "LONGVARCHAR": TokenType.TEXT,
     813        "BINARY": TokenType.BINARY,
     814        "BLOB": TokenType.VARBINARY,
     815        "LONGBLOB": TokenType.LONGBLOB,
     816        "MEDIUMBLOB": TokenType.MEDIUMBLOB,
     817        "TINYBLOB": TokenType.TINYBLOB,
     818        "BYTEA": TokenType.VARBINARY,
     819        "VARBINARY": TokenType.VARBINARY,
     820        "TIME": TokenType.TIME,
     821        "TIMETZ": TokenType.TIMETZ,
     822        "TIMESTAMP": TokenType.TIMESTAMP,
     823        "TIMESTAMPTZ": TokenType.TIMESTAMPTZ,
     824        "TIMESTAMPLTZ": TokenType.TIMESTAMPLTZ,
     825        "DATE": TokenType.DATE,
     826        "DATETIME": TokenType.DATETIME,
     827        "INT4RANGE": TokenType.INT4RANGE,
     828        "INT4MULTIRANGE": TokenType.INT4MULTIRANGE,
     829        "INT8RANGE": TokenType.INT8RANGE,
     830        "INT8MULTIRANGE": TokenType.INT8MULTIRANGE,
     831        "NUMRANGE": TokenType.NUMRANGE,
     832        "NUMMULTIRANGE": TokenType.NUMMULTIRANGE,
     833        "TSRANGE": TokenType.TSRANGE,
     834        "TSMULTIRANGE": TokenType.TSMULTIRANGE,
     835        "TSTZRANGE": TokenType.TSTZRANGE,
     836        "TSTZMULTIRANGE": TokenType.TSTZMULTIRANGE,
     837        "DATERANGE": TokenType.DATERANGE,
     838        "DATEMULTIRANGE": TokenType.DATEMULTIRANGE,
     839        "UNIQUE": TokenType.UNIQUE,
     840        "STRUCT": TokenType.STRUCT,
     841        "VARIANT": TokenType.VARIANT,
     842        "ALTER": TokenType.ALTER,
     843        "ANALYZE": TokenType.COMMAND,
     844        "CALL": TokenType.COMMAND,
     845        "COMMENT": TokenType.COMMENT,
     846        "COPY": TokenType.COMMAND,
     847        "EXPLAIN": TokenType.COMMAND,
     848        "GRANT": TokenType.COMMAND,
     849        "OPTIMIZE": TokenType.COMMAND,
     850        "PREPARE": TokenType.COMMAND,
     851        "TRUNCATE": TokenType.COMMAND,
     852        "VACUUM": TokenType.COMMAND,
     853        "USER-DEFINED": TokenType.USERDEFINED,
     854        "FOR VERSION": TokenType.VERSION_SNAPSHOT,
     855        "FOR TIMESTAMP": TokenType.TIMESTAMP_SNAPSHOT,
     856    }
     857
     858    WHITE_SPACE: t.Dict[t.Optional[str], TokenType] = {
     859        " ": TokenType.SPACE,
     860        "\t": TokenType.SPACE,
     861        "\n": TokenType.BREAK,
     862        "\r": TokenType.BREAK,
     863    }
     864
     865    COMMANDS = {
     866        TokenType.COMMAND,
     867        TokenType.EXECUTE,
     868        TokenType.FETCH,
     869        TokenType.SHOW,
     870    }
     871
     872    COMMAND_PREFIX_TOKENS = {TokenType.SEMICOLON, TokenType.BEGIN}
     873
     874    # handle numeric literals like in hive (3L = BIGINT)
     875    NUMERIC_LITERALS: t.Dict[str, str] = {}
     876
     877    COMMENTS = ["--", ("/*", "*/")]
     878
     879    __slots__ = (
     880        "sql",
     881        "size",
     882        "tokens",
     883        "dialect",
     884        "_start",
     885        "_current",
     886        "_line",
     887        "_col",
     888        "_comments",
     889        "_char",
     890        "_end",
     891        "_peek",
     892        "_prev_token_line",
     893        "_rs_dialect_settings",
     894    )
     895
     896    def __init__(self, dialect: DialectType = None) -> None:
     897        from sqlglot.dialects import Dialect
     898
     899        self.dialect = Dialect.get_or_raise(dialect)
     900
     901        if USE_RS_TOKENIZER:
     902            self._rs_dialect_settings = RsTokenizerDialectSettings(
     903                escape_sequences=self.dialect.ESCAPE_SEQUENCES,
     904                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
     905            )
     906
     907        self.reset()
     908
     909    def reset(self) -> None:
     910        self.sql = ""
     911        self.size = 0
     912        self.tokens: t.List[Token] = []
     913        self._start = 0
     914        self._current = 0
     915        self._line = 1
     916        self._col = 0
     917        self._comments: t.List[str] = []
     918
     919        self._char = ""
     920        self._end = False
     921        self._peek = ""
     922        self._prev_token_line = -1
     923
     924    def tokenize(self, sql: str) -> t.List[Token]:
     925        """Returns a list of tokens corresponding to the SQL string `sql`."""
     926        if USE_RS_TOKENIZER:
     927            return self.tokenize_rs(sql)
     928
     929        self.reset()
     930        self.sql = sql
     931        self.size = len(sql)
     932
     933        try:
     934            self._scan()
     935        except Exception as e:
     936            start = max(self._current - 50, 0)
     937            end = min(self._current + 50, self.size - 1)
     938            context = self.sql[start:end]
     939            raise TokenError(f"Error tokenizing '{context}'") from e
     940
     941        return self.tokens
     942
     943    def _scan(self, until: t.Optional[t.Callable] = None) -> None:
     944        while self.size and not self._end:
     945            current = self._current
     946
     947            # skip spaces inline rather than iteratively call advance()
     948            # for performance reasons
     949            while current < self.size:
     950                char = self.sql[current]
     951
     952                if char.isspace() and (char == " " or char == "\t"):
     953                    current += 1
     954                else:
     955                    break
     956
     957            n = current - self._current
     958            self._start = current
     959            self._advance(n if n > 1 else 1)
     960
     961            if self._char is None:
     962                break
     963
     964            if not self._char.isspace():
     965                if self._char.isdigit():
     966                    self._scan_number()
     967                elif self._char in self._IDENTIFIERS:
     968                    self._scan_identifier(self._IDENTIFIERS[self._char])
     969                else:
     970                    self._scan_keywords()
     971
     972            if until and until():
     973                break
     974
     975        if self.tokens and self._comments:
     976            self.tokens[-1].comments.extend(self._comments)
     977
     978    def _chars(self, size: int) -> str:
     979        if size == 1:
     980            return self._char
     981
     982        start = self._current - 1
     983        end = start + size
     984
     985        return self.sql[start:end] if end <= self.size else ""
     986
     987    def _advance(self, i: int = 1, alnum: bool = False) -> None:
     988        if self.WHITE_SPACE.get(self._char) is TokenType.BREAK:
     989            # Ensures we don't count an extra line if we get a \r\n line break sequence
     990            if self._char == "\r" and self._peek == "\n":
     991                i = 2
     992                self._start += 1
     993
     994            self._col = 1
     995            self._line += 1
     996        else:
     997            self._col += i
     998
     999        self._current += i
    1000        self._end = self._current >= self.size
    1001        self._char = self.sql[self._current - 1]
    1002        self._peek = "" if self._end else self.sql[self._current]
    1003
    1004        if alnum and self._char.isalnum():
    1005            # Here we use local variables instead of attributes for better performance
    1006            _col = self._col
    1007            _current = self._current
    1008            _end = self._end
    1009            _peek = self._peek
    1010
    1011            while _peek.isalnum():
    1012                _col += 1
    1013                _current += 1
    1014                _end = _current >= self.size
    1015                _peek = "" if _end else self.sql[_current]
    1016
    1017            self._col = _col
    1018            self._current = _current
    1019            self._end = _end
    1020            self._peek = _peek
    1021            self._char = self.sql[_current - 1]
    1022
    1023    @property
    1024    def _text(self) -> str:
    1025        return self.sql[self._start : self._current]
    1026
    1027    def peek(self, i: int = 0) -> str:
    1028        i = self._current + i
    1029        if i < self.size:
    1030            return self.sql[i]
    1031        return ""
    1032
    1033    def _add(self, token_type: TokenType, text: t.Optional[str] = None) -> None:
    1034        self._prev_token_line = self._line
    1035
    1036        if self._comments and token_type == TokenType.SEMICOLON and self.tokens:
    1037            self.tokens[-1].comments.extend(self._comments)
    1038            self._comments = []
    1039
    1040        self.tokens.append(
    1041            Token(
    1042                token_type,
    1043                text=self._text if text is None else text,
    1044                line=self._line,
    1045                col=self._col,
    1046                start=self._start,
    1047                end=self._current - 1,
    1048                comments=self._comments,
    1049            )
    1050        )
    1051        self._comments = []
    1052
    1053        # If we have either a semicolon or a begin token before the command's token, we'll parse
    1054        # whatever follows the command's token as a string
    1055        if (
    1056            token_type in self.COMMANDS
    1057            and self._peek != ";"
    1058            and (len(self.tokens) == 1 or self.tokens[-2].token_type in self.COMMAND_PREFIX_TOKENS)
    1059        ):
    1060            start = self._current
    1061            tokens = len(self.tokens)
    1062            self._scan(lambda: self._peek == ";")
    1063            self.tokens = self.tokens[:tokens]
    1064            text = self.sql[start : self._current].strip()
    1065            if text:
    1066                self._add(TokenType.STRING, text)
    1067
    1068    def _scan_keywords(self) -> None:
    1069        size = 0
    1070        word = None
    1071        chars = self._text
    1072        char = chars
    1073        prev_space = False
    1074        skip = False
    1075        trie = self._KEYWORD_TRIE
    1076        single_token = char in self.SINGLE_TOKENS
    1077
    1078        while chars:
    1079            if skip:
    1080                result = TrieResult.PREFIX
    1081            else:
    1082                result, trie = in_trie(trie, char.upper())
    1083
    1084            if result == TrieResult.FAILED:
    1085                break
    1086            if result == TrieResult.EXISTS:
    1087                word = chars
    1088
    1089            end = self._current + size
    1090            size += 1
    1091
    1092            if end < self.size:
    1093                char = self.sql[end]
    1094                single_token = single_token or char in self.SINGLE_TOKENS
    1095                is_space = char.isspace()
    1096
    1097                if not is_space or not prev_space:
    1098                    if is_space:
    1099                        char = " "
    1100                    chars += char
    1101                    prev_space = is_space
    1102                    skip = False
    1103                else:
    1104                    skip = True
    1105            else:
    1106                char = ""
    1107                break
    1108
    1109        if word:
    1110            if self._scan_string(word):
    1111                return
    1112            if self._scan_comment(word):
    1113                return
    1114            if prev_space or single_token or not char:
    1115                self._advance(size - 1)
    1116                word = word.upper()
    1117                self._add(self.KEYWORDS[word], text=word)
    1118                return
    1119
    1120        if self._char in self.SINGLE_TOKENS:
    1121            self._add(self.SINGLE_TOKENS[self._char], text=self._char)
    1122            return
    1123
    1124        self._scan_var()
    1125
    1126    def _scan_comment(self, comment_start: str) -> bool:
    1127        if comment_start not in self._COMMENTS:
    1128            return False
    1129
    1130        comment_start_line = self._line
    1131        comment_start_size = len(comment_start)
    1132        comment_end = self._COMMENTS[comment_start]
    1133
    1134        if comment_end:
    1135            # Skip the comment's start delimiter
    1136            self._advance(comment_start_size)
    1137
    1138            comment_end_size = len(comment_end)
    1139            while not self._end and self._chars(comment_end_size) != comment_end:
    1140                self._advance(alnum=True)
    1141
    1142            self._comments.append(self._text[comment_start_size : -comment_end_size + 1])
    1143            self._advance(comment_end_size - 1)
    1144        else:
    1145            while not self._end and not self.WHITE_SPACE.get(self._peek) is TokenType.BREAK:
    1146                self._advance(alnum=True)
    1147            self._comments.append(self._text[comment_start_size:])
    1148
    1149        # Leading comment is attached to the succeeding token, whilst trailing comment to the preceding.
    1150        # Multiple consecutive comments are preserved by appending them to the current comments list.
    1151        if comment_start_line == self._prev_token_line:
    1152            self.tokens[-1].comments.extend(self._comments)
    1153            self._comments = []
    1154            self._prev_token_line = self._line
    1155
    1156        return True
    1157
    1158    def _scan_number(self) -> None:
    1159        if self._char == "0":
    1160            peek = self._peek.upper()
    1161            if peek == "B":
    1162                return self._scan_bits() if self.BIT_STRINGS else self._add(TokenType.NUMBER)
    1163            elif peek == "X":
    1164                return self._scan_hex() if self.HEX_STRINGS else self._add(TokenType.NUMBER)
    1165
    1166        decimal = False
    1167        scientific = 0
    1168
    1169        while True:
    1170            if self._peek.isdigit():
    1171                self._advance()
    1172            elif self._peek == "." and not decimal:
    1173                after = self.peek(1)
    1174                if after.isdigit() or not after.isalpha():
    1175                    decimal = True
    1176                    self._advance()
    1177                else:
    1178                    return self._add(TokenType.VAR)
    1179            elif self._peek in ("-", "+") and scientific == 1:
    1180                scientific += 1
    1181                self._advance()
    1182            elif self._peek.upper() == "E" and not scientific:
    1183                scientific += 1
    1184                self._advance()
    1185            elif self._peek.isidentifier():
    1186                number_text = self._text
    1187                literal = ""
    1188
    1189                while self._peek.strip() and self._peek not in self.SINGLE_TOKENS:
    1190                    literal += self._peek
    1191                    self._advance()
    1192
    1193                token_type = self.KEYWORDS.get(self.NUMERIC_LITERALS.get(literal.upper(), ""))
    1194
    1195                if token_type:
    1196                    self._add(TokenType.NUMBER, number_text)
    1197                    self._add(TokenType.DCOLON, "::")
    1198                    return self._add(token_type, literal)
    1199                elif self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT:
    1200                    return self._add(TokenType.VAR)
    1201
    1202                self._advance(-len(literal))
    1203                return self._add(TokenType.NUMBER, number_text)
    1204            else:
    1205                return self._add(TokenType.NUMBER)
    1206
    1207    def _scan_bits(self) -> None:
    1208        self._advance()
    1209        value = self._extract_value()
    1210        try:
    1211            # If `value` can't be converted to a binary, fallback to tokenizing it as an identifier
    1212            int(value, 2)
    1213            self._add(TokenType.BIT_STRING, value[2:])  # Drop the 0b
    1214        except ValueError:
    1215            self._add(TokenType.IDENTIFIER)
    1216
    1217    def _scan_hex(self) -> None:
    1218        self._advance()
    1219        value = self._extract_value()
    1220        try:
    1221            # If `value` can't be converted to a hex, fallback to tokenizing it as an identifier
    1222            int(value, 16)
    1223            self._add(TokenType.HEX_STRING, value[2:])  # Drop the 0x
    1224        except ValueError:
    1225            self._add(TokenType.IDENTIFIER)
    1226
    1227    def _extract_value(self) -> str:
    1228        while True:
    1229            char = self._peek.strip()
    1230            if char and char not in self.SINGLE_TOKENS:
    1231                self._advance(alnum=True)
    1232            else:
    1233                break
    1234
    1235        return self._text
    1236
    1237    def _scan_string(self, start: str) -> bool:
    1238        base = None
    1239        token_type = TokenType.STRING
    1240
    1241        if start in self._QUOTES:
    1242            end = self._QUOTES[start]
    1243        elif start in self._FORMAT_STRINGS:
    1244            end, token_type = self._FORMAT_STRINGS[start]
    1245
    1246            if token_type == TokenType.HEX_STRING:
    1247                base = 16
    1248            elif token_type == TokenType.BIT_STRING:
    1249                base = 2
    1250            elif token_type == TokenType.HEREDOC_STRING:
    1251                self._advance()
    1252                tag = "" if self._char == end else self._extract_string(end)
    1253                end = f"{start}{tag}{end}"
    1254        else:
    1255            return False
    1256
    1257        self._advance(len(start))
    1258        text = self._extract_string(end)
    1259
    1260        if base:
    1261            try:
    1262                int(text, base)
    1263            except:
    1264                raise TokenError(
    1265                    f"Numeric string contains invalid characters from {self._line}:{self._start}"
    1266                )
    1267
    1268        self._add(token_type, text)
    1269        return True
    1270
    1271    def _scan_identifier(self, identifier_end: str) -> None:
    1272        self._advance()
    1273        text = self._extract_string(identifier_end, self._IDENTIFIER_ESCAPES)
    1274        self._add(TokenType.IDENTIFIER, text)
    1275
    1276    def _scan_var(self) -> None:
    1277        while True:
    1278            char = self._peek.strip()
    1279            if char and (char in self.VAR_SINGLE_TOKENS or char not in self.SINGLE_TOKENS):
    1280                self._advance(alnum=True)
    1281            else:
    1282                break
    1283
    1284        self._add(
    1285            TokenType.VAR
    1286            if self.tokens and self.tokens[-1].token_type == TokenType.PARAMETER
    1287            else self.KEYWORDS.get(self._text.upper(), TokenType.VAR)
    1288        )
    1289
    1290    def _extract_string(self, delimiter: str, escapes=None) -> str:
    1291        text = ""
    1292        delim_size = len(delimiter)
    1293        escapes = self._STRING_ESCAPES if escapes is None else escapes
    1294
    1295        while True:
    1296            if (
    1297                self._char in escapes
    1298                and (self._peek == delimiter or self._peek in escapes)
    1299                and (self._char not in self._QUOTES or self._char == self._peek)
    1300            ):
    1301                if self._peek == delimiter:
    1302                    text += self._peek
    1303                else:
    1304                    text += self._char + self._peek
    1305
    1306                if self._current + 1 < self.size:
    1307                    self._advance(2)
    1308                else:
    1309                    raise TokenError(f"Missing {delimiter} from {self._line}:{self._current}")
    1310            else:
    1311                if self._chars(delim_size) == delimiter:
    1312                    if delim_size > 1:
    1313                        self._advance(delim_size - 1)
    1314                    break
    1315
    1316                if self._end:
    1317                    raise TokenError(f"Missing {delimiter} from {self._line}:{self._start}")
    1318
    1319                if (
    1320                    self.dialect.ESCAPE_SEQUENCES
    1321                    and self._peek
    1322                    and self._char in self.STRING_ESCAPES
    1323                ):
    1324                    escaped_sequence = self.dialect.ESCAPE_SEQUENCES.get(self._char + self._peek)
    1325                    if escaped_sequence:
    1326                        self._advance(2)
    1327                        text += escaped_sequence
    1328                        continue
    1329
    1330                current = self._current - 1
    1331                self._advance(alnum=True)
    1332                text += self.sql[current : self._current - 1]
    1333
    1334        return text
    1335
    1336    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1337        if not self._RS_TOKENIZER:
    1338            raise SqlglotError("Rust tokenizer is not available")
    1339
    1340        try:
    1341            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1342            for token in tokens:
    1343                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1344            return tokens
    1345        except Exception as e:
    1346            raise TokenError(str(e))

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

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

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

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

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

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

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

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

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

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

size
sql
tokens