sqlglot.tokens API documentation

Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

An enumeration.

L_PAREN = <TokenType.L_PAREN: 'L_PAREN'>
R_PAREN = <TokenType.R_PAREN: 'R_PAREN'>
L_BRACKET = <TokenType.L_BRACKET: 'L_BRACKET'>
R_BRACKET = <TokenType.R_BRACKET: 'R_BRACKET'>
L_BRACE = <TokenType.L_BRACE: 'L_BRACE'>
R_BRACE = <TokenType.R_BRACE: 'R_BRACE'>
COMMA = <TokenType.COMMA: 'COMMA'>
DOT = <TokenType.DOT: 'DOT'>
DASH = <TokenType.DASH: 'DASH'>
PLUS = <TokenType.PLUS: 'PLUS'>
COLON = <TokenType.COLON: 'COLON'>
DCOLON = <TokenType.DCOLON: 'DCOLON'>
DQMARK = <TokenType.DQMARK: 'DQMARK'>
SEMICOLON = <TokenType.SEMICOLON: 'SEMICOLON'>
STAR = <TokenType.STAR: 'STAR'>
BACKSLASH = <TokenType.BACKSLASH: 'BACKSLASH'>
SLASH = <TokenType.SLASH: 'SLASH'>
LT = <TokenType.LT: 'LT'>
LTE = <TokenType.LTE: 'LTE'>
GT = <TokenType.GT: 'GT'>
GTE = <TokenType.GTE: 'GTE'>
NOT = <TokenType.NOT: 'NOT'>
EQ = <TokenType.EQ: 'EQ'>
NEQ = <TokenType.NEQ: 'NEQ'>
NULLSAFE_EQ = <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>
COLON_EQ = <TokenType.COLON_EQ: 'COLON_EQ'>
AND = <TokenType.AND: 'AND'>
OR = <TokenType.OR: 'OR'>
AMP = <TokenType.AMP: 'AMP'>
DPIPE = <TokenType.DPIPE: 'DPIPE'>
PIPE = <TokenType.PIPE: 'PIPE'>
PIPE_SLASH = <TokenType.PIPE_SLASH: 'PIPE_SLASH'>
DPIPE_SLASH = <TokenType.DPIPE_SLASH: 'DPIPE_SLASH'>
CARET = <TokenType.CARET: 'CARET'>
TILDA = <TokenType.TILDA: 'TILDA'>
ARROW = <TokenType.ARROW: 'ARROW'>
DARROW = <TokenType.DARROW: 'DARROW'>
FARROW = <TokenType.FARROW: 'FARROW'>
HASH = <TokenType.HASH: 'HASH'>
HASH_ARROW = <TokenType.HASH_ARROW: 'HASH_ARROW'>
DHASH_ARROW = <TokenType.DHASH_ARROW: 'DHASH_ARROW'>
LR_ARROW = <TokenType.LR_ARROW: 'LR_ARROW'>
DAT = <TokenType.DAT: 'DAT'>
LT_AT = <TokenType.LT_AT: 'LT_AT'>
AT_GT = <TokenType.AT_GT: 'AT_GT'>
DOLLAR = <TokenType.DOLLAR: 'DOLLAR'>
PARAMETER = <TokenType.PARAMETER: 'PARAMETER'>
SESSION_PARAMETER = <TokenType.SESSION_PARAMETER: 'SESSION_PARAMETER'>
DAMP = <TokenType.DAMP: 'DAMP'>
XOR = <TokenType.XOR: 'XOR'>
DSTAR = <TokenType.DSTAR: 'DSTAR'>
BLOCK_START = <TokenType.BLOCK_START: 'BLOCK_START'>
BLOCK_END = <TokenType.BLOCK_END: 'BLOCK_END'>
SPACE = <TokenType.SPACE: 'SPACE'>
BREAK = <TokenType.BREAK: 'BREAK'>
STRING = <TokenType.STRING: 'STRING'>
NUMBER = <TokenType.NUMBER: 'NUMBER'>
IDENTIFIER = <TokenType.IDENTIFIER: 'IDENTIFIER'>
DATABASE = <TokenType.DATABASE: 'DATABASE'>
COLUMN = <TokenType.COLUMN: 'COLUMN'>
COLUMN_DEF = <TokenType.COLUMN_DEF: 'COLUMN_DEF'>
SCHEMA = <TokenType.SCHEMA: 'SCHEMA'>
TABLE = <TokenType.TABLE: 'TABLE'>
VAR = <TokenType.VAR: 'VAR'>
BIT_STRING = <TokenType.BIT_STRING: 'BIT_STRING'>
HEX_STRING = <TokenType.HEX_STRING: 'HEX_STRING'>
BYTE_STRING = <TokenType.BYTE_STRING: 'BYTE_STRING'>
NATIONAL_STRING = <TokenType.NATIONAL_STRING: 'NATIONAL_STRING'>
RAW_STRING = <TokenType.RAW_STRING: 'RAW_STRING'>
HEREDOC_STRING = <TokenType.HEREDOC_STRING: 'HEREDOC_STRING'>
UNICODE_STRING = <TokenType.UNICODE_STRING: 'UNICODE_STRING'>
BIT = <TokenType.BIT: 'BIT'>
BOOLEAN = <TokenType.BOOLEAN: 'BOOLEAN'>
TINYINT = <TokenType.TINYINT: 'TINYINT'>
UTINYINT = <TokenType.UTINYINT: 'UTINYINT'>
SMALLINT = <TokenType.SMALLINT: 'SMALLINT'>
USMALLINT = <TokenType.USMALLINT: 'USMALLINT'>
MEDIUMINT = <TokenType.MEDIUMINT: 'MEDIUMINT'>
UMEDIUMINT = <TokenType.UMEDIUMINT: 'UMEDIUMINT'>
INT = <TokenType.INT: 'INT'>
UINT = <TokenType.UINT: 'UINT'>
BIGINT = <TokenType.BIGINT: 'BIGINT'>
UBIGINT = <TokenType.UBIGINT: 'UBIGINT'>
INT128 = <TokenType.INT128: 'INT128'>
UINT128 = <TokenType.UINT128: 'UINT128'>
INT256 = <TokenType.INT256: 'INT256'>
UINT256 = <TokenType.UINT256: 'UINT256'>
FLOAT = <TokenType.FLOAT: 'FLOAT'>
DOUBLE = <TokenType.DOUBLE: 'DOUBLE'>
DECIMAL = <TokenType.DECIMAL: 'DECIMAL'>
UDECIMAL = <TokenType.UDECIMAL: 'UDECIMAL'>
BIGDECIMAL = <TokenType.BIGDECIMAL: 'BIGDECIMAL'>
CHAR = <TokenType.CHAR: 'CHAR'>
NCHAR = <TokenType.NCHAR: 'NCHAR'>
VARCHAR = <TokenType.VARCHAR: 'VARCHAR'>
NVARCHAR = <TokenType.NVARCHAR: 'NVARCHAR'>
BPCHAR = <TokenType.BPCHAR: 'BPCHAR'>
TEXT = <TokenType.TEXT: 'TEXT'>
MEDIUMTEXT = <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <TokenType.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <TokenType.LONGBLOB: 'LONGBLOB'>
TINYBLOB = <TokenType.TINYBLOB: 'TINYBLOB'>
TINYTEXT = <TokenType.TINYTEXT: 'TINYTEXT'>
NAME = <TokenType.NAME: 'NAME'>
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'>
TIMESTAMPNTZ = <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>
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'>
TDIGEST = <TokenType.TDIGEST: 'TDIGEST'>
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'>
COPY = <TokenType.COPY: 'COPY'>
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'>
DECLARE = <TokenType.DECLARE: 'DECLARE'>
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_CONDITION = <TokenType.MATCH_CONDITION: 'MATCH_CONDITION'>
MATCH_RECOGNIZE = <TokenType.MATCH_RECOGNIZE: 'MATCH_RECOGNIZE'>
MEMBER_OF = <TokenType.MEMBER_OF: 'MEMBER_OF'>
MERGE = <TokenType.MERGE: 'MERGE'>
MOD = <TokenType.MOD: 'MOD'>
MODEL = <TokenType.MODEL: 'MODEL'>
NATURAL = <TokenType.NATURAL: 'NATURAL'>
NEXT = <TokenType.NEXT: 'NEXT'>
NOTNULL = <TokenType.NOTNULL: 'NOTNULL'>
NULL = <TokenType.NULL: 'NULL'>
OBJECT_IDENTIFIER = <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>
OFFSET = <TokenType.OFFSET: 'OFFSET'>
ON = <TokenType.ON: 'ON'>
ONLY = <TokenType.ONLY: 'ONLY'>
OPERATOR = <TokenType.OPERATOR: 'OPERATOR'>
ORDER_BY = <TokenType.ORDER_BY: 'ORDER_BY'>
ORDER_SIBLINGS_BY = <TokenType.ORDER_SIBLINGS_BY: 'ORDER_SIBLINGS_BY'>
ORDERED = <TokenType.ORDERED: 'ORDERED'>
ORDINALITY = <TokenType.ORDINALITY: 'ORDINALITY'>
OUTER = <TokenType.OUTER: 'OUTER'>
OVER = <TokenType.OVER: 'OVER'>
OVERLAPS = <TokenType.OVERLAPS: 'OVERLAPS'>
OVERWRITE = <TokenType.OVERWRITE: 'OVERWRITE'>
PARTITION = <TokenType.PARTITION: 'PARTITION'>
PARTITION_BY = <TokenType.PARTITION_BY: 'PARTITION_BY'>
PERCENT = <TokenType.PERCENT: 'PERCENT'>
PIVOT = <TokenType.PIVOT: 'PIVOT'>
PLACEHOLDER = <TokenType.PLACEHOLDER: 'PLACEHOLDER'>
POSITIONAL = <TokenType.POSITIONAL: 'POSITIONAL'>
PRAGMA = <TokenType.PRAGMA: 'PRAGMA'>
PREWHERE = <TokenType.PREWHERE: 'PREWHERE'>
PRIMARY_KEY = <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>
PROCEDURE = <TokenType.PROCEDURE: 'PROCEDURE'>
PROPERTIES = <TokenType.PROPERTIES: 'PROPERTIES'>
PSEUDO_TYPE = <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>
QUALIFY = <TokenType.QUALIFY: 'QUALIFY'>
QUOTE = <TokenType.QUOTE: 'QUOTE'>
RANGE = <TokenType.RANGE: 'RANGE'>
RECURSIVE = <TokenType.RECURSIVE: 'RECURSIVE'>
REFRESH = <TokenType.REFRESH: 'REFRESH'>
REPLACE = <TokenType.REPLACE: 'REPLACE'>
RETURNING = <TokenType.RETURNING: 'RETURNING'>
REFERENCES = <TokenType.REFERENCES: 'REFERENCES'>
RIGHT = <TokenType.RIGHT: 'RIGHT'>
RLIKE = <TokenType.RLIKE: 'RLIKE'>
ROLLBACK = <TokenType.ROLLBACK: 'ROLLBACK'>
ROLLUP = <TokenType.ROLLUP: 'ROLLUP'>
ROW = <TokenType.ROW: 'ROW'>
ROWS = <TokenType.ROWS: 'ROWS'>
SELECT = <TokenType.SELECT: 'SELECT'>
SEMI = <TokenType.SEMI: 'SEMI'>
SEPARATOR = <TokenType.SEPARATOR: 'SEPARATOR'>
SEQUENCE = <TokenType.SEQUENCE: 'SEQUENCE'>
SERDE_PROPERTIES = <TokenType.SERDE_PROPERTIES: 'SERDE_PROPERTIES'>
SET = <TokenType.SET: 'SET'>
SETTINGS = <TokenType.SETTINGS: 'SETTINGS'>
SHOW = <TokenType.SHOW: 'SHOW'>
SIMILAR_TO = <TokenType.SIMILAR_TO: 'SIMILAR_TO'>
SOME = <TokenType.SOME: 'SOME'>
SORT_BY = <TokenType.SORT_BY: 'SORT_BY'>
START_WITH = <TokenType.START_WITH: 'START_WITH'>
STORAGE_INTEGRATION = <TokenType.STORAGE_INTEGRATION: 'STORAGE_INTEGRATION'>
STRUCT = <TokenType.STRUCT: 'STRUCT'>
TABLE_SAMPLE = <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>
TAG = <TokenType.TAG: 'TAG'>
TEMPORARY = <TokenType.TEMPORARY: 'TEMPORARY'>
TOP = <TokenType.TOP: 'TOP'>
THEN = <TokenType.THEN: 'THEN'>
TRUE = <TokenType.TRUE: 'TRUE'>
TRUNCATE = <TokenType.TRUNCATE: 'TRUNCATE'>
UNCACHE = <TokenType.UNCACHE: 'UNCACHE'>
UNION = <TokenType.UNION: 'UNION'>
UNNEST = <TokenType.UNNEST: 'UNNEST'>
UNPIVOT = <TokenType.UNPIVOT: 'UNPIVOT'>
UPDATE = <TokenType.UPDATE: 'UPDATE'>
USE = <TokenType.USE: 'USE'>
USING = <TokenType.USING: 'USING'>
VALUES = <TokenType.VALUES: 'VALUES'>
VIEW = <TokenType.VIEW: 'VIEW'>
VOLATILE = <TokenType.VOLATILE: 'VOLATILE'>
WHEN = <TokenType.WHEN: 'WHEN'>
WHERE = <TokenType.WHERE: 'WHERE'>
WINDOW = <TokenType.WINDOW: 'WINDOW'>
WITH = <TokenType.WITH: 'WITH'>
UNIQUE = <TokenType.UNIQUE: 'UNIQUE'>
VERSION_SNAPSHOT = <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>
TIMESTAMP_SNAPSHOT = <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>
OPTION = <TokenType.OPTION: 'OPTION'>

##### Inherited Members

enum.Enum
  name
  value

class Token: View Source

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

    416    def __init__(
    417        self,
    418        token_type: TokenType,
    419        text: str,
    420        line: int = 1,
    421        col: int = 1,
    422        start: int = 0,
    423        end: int = 0,
    424        comments: t.Optional[t.List[str]] = None,
    425    ) -> None:
    426        """Token initializer.
    427
    428        Args:
    429            token_type: The TokenType Enum.
    430            text: The text of the token.
    431            line: The line that the token ends on.
    432            col: The column that the token ends on.
    433            start: The start index of the token.
    434            end: The ending index of the token.
    435            comments: The comments to attach to the token.
    436        """
    437        self.token_type = token_type
    438        self.text = text
    439        self.line = line
    440        self.col = col
    441        self.start = start
    442        self.end = end
    443        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

    396    @classmethod
    397    def number(cls, number: int) -> Token:
    398        """Returns a NUMBER token with `number` as its text."""
    399        return cls(TokenType.NUMBER, str(number))

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

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

    401    @classmethod
    402    def string(cls, string: str) -> Token:
    403        """Returns a STRING token with `string` as its text."""
    404        return cls(TokenType.STRING, string)

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

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

    406    @classmethod
    407    def identifier(cls, identifier: str) -> Token:
    408        """Returns an IDENTIFIER token with `identifier` as its text."""
    409        return cls(TokenType.IDENTIFIER, identifier)

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

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

    411    @classmethod
    412    def var(cls, var: str) -> Token:
    413        """Returns an VAR token with `var` as its text."""
    414        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

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

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

    928    def __init__(self, dialect: DialectType = None) -> None:
    929        from sqlglot.dialects import Dialect
    930
    931        self.dialect = Dialect.get_or_raise(dialect)
    932
    933        if USE_RS_TOKENIZER:
    934            self._rs_dialect_settings = RsTokenizerDialectSettings(
    935                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
    936                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    937            )
    938
    939        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.HASH: 'HASH'>, "'": <TokenType.UNKNOWN: 'UNKNOWN'>, '`': <TokenType.UNKNOWN: 'UNKNOWN'>, '"': <TokenType.UNKNOWN: 'UNKNOWN'>}
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'>, 'COPY': <TokenType.COPY: 'COPY'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ENUM': <TokenType.ENUM: 'ENUM'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'KILL': <TokenType.KILL: 'KILL'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'START WITH': <TokenType.START_WITH: 'START_WITH'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'TRUNCATE': <TokenType.TRUNCATE: 'TRUNCATE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'MEDIUMINT': <TokenType.MEDIUMINT: 'MEDIUMINT'>, 'INT1': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'INT16': <TokenType.SMALLINT: 'SMALLINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT128': <TokenType.INT128: 'INT128'>, 'HUGEINT': <TokenType.INT128: 'INT128'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'INT32': <TokenType.INT: 'INT'>, 'INT64': <TokenType.BIGINT: 'BIGINT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.TINYINT: 'TINYINT'>, 'UINT': <TokenType.UINT: 'UINT'>, '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'>, 'TIMESTAMP_LTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'TIMESTAMPNTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, 'TIMESTAMP_NTZ': <TokenType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, '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'>, 'SEQUENCE': <TokenType.SEQUENCE: 'SEQUENCE'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>}
WHITE_SPACE: Dict[Optional[str], TokenType] = {' ': <TokenType.SPACE: 'SPACE'>, '\t': <TokenType.SPACE: 'SPACE'>, '\n': <TokenType.BREAK: 'BREAK'>, '\r': <TokenType.BREAK: 'BREAK'>}
COMMANDS = {<TokenType.SHOW: 'SHOW'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.FETCH: 'FETCH'>, <TokenType.COMMAND: 'COMMAND'>}
COMMAND_PREFIX_TOKENS = {<TokenType.BEGIN: 'BEGIN'>, <TokenType.SEMICOLON: 'SEMICOLON'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
def reset(self) -> None: View Source

    941    def reset(self) -> None:
    942        self.sql = ""
    943        self.size = 0
    944        self.tokens: t.List[Token] = []
    945        self._start = 0
    946        self._current = 0
    947        self._line = 1
    948        self._col = 0
    949        self._comments: t.List[str] = []
    950
    951        self._char = ""
    952        self._end = False
    953        self._peek = ""
    954        self._prev_token_line = -1

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

    956    def tokenize(self, sql: str) -> t.List[Token]:
    957        """Returns a list of tokens corresponding to the SQL string `sql`."""
    958        if USE_RS_TOKENIZER:
    959            return self.tokenize_rs(sql)
    960
    961        self.reset()
    962        self.sql = sql
    963        self.size = len(sql)
    964
    965        try:
    966            self._scan()
    967        except Exception as e:
    968            start = max(self._current - 50, 0)
    969            end = min(self._current + 50, self.size - 1)
    970            context = self.sql[start:end]
    971            raise TokenError(f"Error tokenizing '{context}'") from e
    972
    973        return self.tokens

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

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

    1389    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1390        if not self._RS_TOKENIZER:
    1391            raise SqlglotError("Rust tokenizer is not available")
    1392
    1393        try:
    1394            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1395            for token in tokens:
    1396                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1397            return tokens
    1398        except Exception as e:
    1399            raise TokenError(str(e))

size
sql
tokens