sqlglot.tokens API documentation

Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

An enumeration.

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

##### Inherited Members

enum.Enum
  name
  value

class Token: View Source

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

Token( token_type: TokenType, text: str, line: int = 1, col: int = 1, start: int = 0, end: int = 0, comments: Optional[List[str]] = None) View Source

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

Token initializer.

###### Arguments:

- token_type: The TokenType Enum.
- text: The text of the token.
- line: The line that the token ends on.
- col: The column that the token ends on.
- start: The start index of the token.
- end: The ending index of the token.
- comments: The comments to attach to the token.

@classmethod
def number(cls, number: int) -> Token: View Source

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

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

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

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

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

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

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

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

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

    395    @classmethod
    396    def var(cls, var: str) -> Token:
    397        """Returns an VAR token with `var` as its text."""
    398        return cls(TokenType.VAR, var)

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

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

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

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

    906    def __init__(self, dialect: DialectType = None) -> None:
    907        from sqlglot.dialects import Dialect
    908
    909        self.dialect = Dialect.get_or_raise(dialect)
    910
    911        if USE_RS_TOKENIZER:
    912            self._rs_dialect_settings = RsTokenizerDialectSettings(
    913                escape_sequences=self.dialect.ESCAPE_SEQUENCES,
    914                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    915            )
    916
    917        self.reset()

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

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

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

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

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

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

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

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

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

size
sql
tokens