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

    422class Token:
    423    __slots__ = ("token_type", "text", "line", "col", "start", "end", "comments")
    424
    425    @classmethod
    426    def number(cls, number: int) -> Token:
    427        """Returns a NUMBER token with `number` as its text."""
    428        return cls(TokenType.NUMBER, str(number))
    429
    430    @classmethod
    431    def string(cls, string: str) -> Token:
    432        """Returns a STRING token with `string` as its text."""
    433        return cls(TokenType.STRING, string)
    434
    435    @classmethod
    436    def identifier(cls, identifier: str) -> Token:
    437        """Returns an IDENTIFIER token with `identifier` as its text."""
    438        return cls(TokenType.IDENTIFIER, identifier)
    439
    440    @classmethod
    441    def var(cls, var: str) -> Token:
    442        """Returns an VAR token with `var` as its text."""
    443        return cls(TokenType.VAR, var)
    444
    445    def __init__(
    446        self,
    447        token_type: TokenType,
    448        text: str,
    449        line: int = 1,
    450        col: int = 1,
    451        start: int = 0,
    452        end: int = 0,
    453        comments: t.Optional[t.List[str]] = None,
    454    ) -> None:
    455        """Token initializer.
    456
    457        Args:
    458            token_type: The TokenType Enum.
    459            text: The text of the token.
    460            line: The line that the token ends on.
    461            col: The column that the token ends on.
    462            start: The start index of the token.
    463            end: The ending index of the token.
    464            comments: The comments to attach to the token.
    465        """
    466        self.token_type = token_type
    467        self.text = text
    468        self.line = line
    469        self.col = col
    470        self.start = start
    471        self.end = end
    472        self.comments = [] if comments is None else comments
    473
    474    def __repr__(self) -> str:
    475        attributes = ", ".join(f"{k}: {getattr(self, k)}" for k in self.__slots__)
    476        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

    445    def __init__(
    446        self,
    447        token_type: TokenType,
    448        text: str,
    449        line: int = 1,
    450        col: int = 1,
    451        start: int = 0,
    452        end: int = 0,
    453        comments: t.Optional[t.List[str]] = None,
    454    ) -> None:
    455        """Token initializer.
    456
    457        Args:
    458            token_type: The TokenType Enum.
    459            text: The text of the token.
    460            line: The line that the token ends on.
    461            col: The column that the token ends on.
    462            start: The start index of the token.
    463            end: The ending index of the token.
    464            comments: The comments to attach to the token.
    465        """
    466        self.token_type = token_type
    467        self.text = text
    468        self.line = line
    469        self.col = col
    470        self.start = start
    471        self.end = end
    472        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

    425    @classmethod
    426    def number(cls, number: int) -> Token:
    427        """Returns a NUMBER token with `number` as its text."""
    428        return cls(TokenType.NUMBER, str(number))

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

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

    430    @classmethod
    431    def string(cls, string: str) -> Token:
    432        """Returns a STRING token with `string` as its text."""
    433        return cls(TokenType.STRING, string)

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

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

    435    @classmethod
    436    def identifier(cls, identifier: str) -> Token:
    437        """Returns an IDENTIFIER token with `identifier` as its text."""
    438        return cls(TokenType.IDENTIFIER, identifier)

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

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

    440    @classmethod
    441    def var(cls, var: str) -> Token:
    442        """Returns an VAR token with `var` as its text."""
    443        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

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

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

     996    def __init__(
     997        self, dialect: DialectType = None, use_rs_tokenizer: bool = USE_RS_TOKENIZER
     998    ) -> None:
     999        from sqlglot.dialects import Dialect
    1000
    1001        self.dialect = Dialect.get_or_raise(dialect)
    1002
    1003        # initialize `use_rs_tokenizer`, and allow it to be overwritten per Tokenizer instance
    1004        self.use_rs_tokenizer = use_rs_tokenizer
    1005
    1006        if USE_RS_TOKENIZER:
    1007            self._rs_dialect_settings = RsTokenizerDialectSettings(
    1008                unescaped_sequences=self.dialect.UNESCAPED_SEQUENCES,
    1009                identifiers_can_start_with_digit=self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT,
    1010                numbers_can_be_underscore_separated=self.dialect.NUMBERS_CAN_BE_UNDERSCORE_SEPARATED,
    1011            )
    1012
    1013        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]]] = ['"']
QUOTES: List[Union[str, Tuple[str, str]]] = ["'"]
STRING_ESCAPES = ["'"]
VAR_SINGLE_TOKENS: Set[str] = set()
IDENTIFIER_ESCAPES: List[str] = []
HEREDOC_TAG_IS_IDENTIFIER = False
HEREDOC_STRING_ALTERNATIVE = <TokenType.VAR: 'VAR'>
STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS = True
NESTED_COMMENTS = True
HINT_START = '/*+'
TOKENS_PRECEDING_HINT = {<TokenType.INSERT: 'INSERT'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.SELECT: 'SELECT'>, <TokenType.DELETE: 'DELETE'>}
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'>, '~~~': <TokenType.GLOB: 'GLOB'>, '~~': <TokenType.LIKE: 'LIKE'>, '~~*': <TokenType.ILIKE: 'ILIKE'>, '~*': <TokenType.IRLIKE: 'IRLIKE'>, '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'>, 'NAMESPACE': <TokenType.NAMESPACE: 'NAMESPACE'>, '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'>, 'RENAME': <TokenType.RENAME: 'RENAME'>, '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'>, 'STRAIGHT_JOIN': <TokenType.STRAIGHT_JOIN: 'STRAIGHT_JOIN'>, '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'>, 'UHUGEINT': <TokenType.UINT128: 'UINT128'>, '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'>, 'DECIMAL32': <TokenType.DECIMAL32: 'DECIMAL32'>, 'DECIMAL64': <TokenType.DECIMAL64: 'DECIMAL64'>, 'DECIMAL128': <TokenType.DECIMAL128: 'DECIMAL128'>, 'DECIMAL256': <TokenType.DECIMAL256: 'DECIMAL256'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'LIST': <TokenType.LIST: 'LIST'>, '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'>, 'JSONB': <TokenType.JSONB: 'JSONB'>, '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'>, 'VECTOR': <TokenType.VECTOR: 'VECTOR'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'SEQUENCE': <TokenType.SEQUENCE: 'SEQUENCE'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.ANALYZE: 'ANALYZE'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.GRANT: 'GRANT'>, '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.COMMAND: 'COMMAND'>, <TokenType.SHOW: 'SHOW'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.FETCH: 'FETCH'>, <TokenType.RENAME: 'RENAME'>}
COMMAND_PREFIX_TOKENS = {<TokenType.BEGIN: 'BEGIN'>, <TokenType.SEMICOLON: 'SEMICOLON'>}
NUMERIC_LITERALS: Dict[str, str] = {}
COMMENTS = ['--', ('/*', '*/')]
dialect
use_rs_tokenizer
def reset(self) -> None: View Source

    1015    def reset(self) -> None:
    1016        self.sql = ""
    1017        self.size = 0
    1018        self.tokens: t.List[Token] = []
    1019        self._start = 0
    1020        self._current = 0
    1021        self._line = 1
    1022        self._col = 0
    1023        self._comments: t.List[str] = []
    1024
    1025        self._char = ""
    1026        self._end = False
    1027        self._peek = ""
    1028        self._prev_token_line = -1

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

    1030    def tokenize(self, sql: str) -> t.List[Token]:
    1031        """Returns a list of tokens corresponding to the SQL string `sql`."""
    1032        if self.use_rs_tokenizer:
    1033            return self.tokenize_rs(sql)
    1034
    1035        self.reset()
    1036        self.sql = sql
    1037        self.size = len(sql)
    1038
    1039        try:
    1040            self._scan()
    1041        except Exception as e:
    1042            start = max(self._current - 50, 0)
    1043            end = min(self._current + 50, self.size - 1)
    1044            context = self.sql[start:end]
    1045            raise TokenError(f"Error tokenizing '{context}'") from e
    1046
    1047        return self.tokens

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

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

    1484    def tokenize_rs(self, sql: str) -> t.List[Token]:
    1485        if not self._RS_TOKENIZER:
    1486            raise SqlglotError("Rust tokenizer is not available")
    1487
    1488        try:
    1489            tokens = self._RS_TOKENIZER.tokenize(sql, self._rs_dialect_settings)
    1490            for token in tokens:
    1491                token.token_type = _ALL_TOKEN_TYPES[token.token_type_index]
    1492            return tokens
    1493        except Exception as e:
    1494            raise TokenError(str(e))

size
sql
tokens