sqlglot.tokens API documentation

Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

##### Inherited Members

enum.Enum
  name
  value

class Token: View Source

    315class Token:
    316    __slots__ = ("token_type", "text", "line", "col", "start", "end", "comments")
    317
    318    @classmethod
    319    def number(cls, number: int) -> Token:
    320        """Returns a NUMBER token with `number` as its text."""
    321        return cls(TokenType.NUMBER, str(number))
    322
    323    @classmethod
    324    def string(cls, string: str) -> Token:
    325        """Returns a STRING token with `string` as its text."""
    326        return cls(TokenType.STRING, string)
    327
    328    @classmethod
    329    def identifier(cls, identifier: str) -> Token:
    330        """Returns an IDENTIFIER token with `identifier` as its text."""
    331        return cls(TokenType.IDENTIFIER, identifier)
    332
    333    @classmethod
    334    def var(cls, var: str) -> Token:
    335        """Returns an VAR token with `var` as its text."""
    336        return cls(TokenType.VAR, var)
    337
    338    def __init__(
    339        self,
    340        token_type: TokenType,
    341        text: str,
    342        line: int = 1,
    343        col: int = 1,
    344        start: int = 0,
    345        end: int = 0,
    346        comments: t.List[str] = [],
    347    ) -> None:
    348        """Token initializer.
    349
    350        Args:
    351            token_type: The TokenType Enum.
    352            text: The text of the token.
    353            line: The line that the token ends on.
    354            col: The column that the token ends on.
    355            start: The start index of the token.
    356            end: The ending index of the token.
    357            comments: The comments to attach to the token.
    358        """
    359        self.token_type = token_type
    360        self.text = text
    361        self.line = line
    362        self.col = col
    363        self.start = start
    364        self.end = end
    365        self.comments = comments
    366
    367    def __repr__(self) -> str:
    368        attributes = ", ".join(f"{k}: {getattr(self, k)}" for k in self.__slots__)
    369        return f"<Token {attributes}>"

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

    338    def __init__(
    339        self,
    340        token_type: TokenType,
    341        text: str,
    342        line: int = 1,
    343        col: int = 1,
    344        start: int = 0,
    345        end: int = 0,
    346        comments: t.List[str] = [],
    347    ) -> None:
    348        """Token initializer.
    349
    350        Args:
    351            token_type: The TokenType Enum.
    352            text: The text of the token.
    353            line: The line that the token ends on.
    354            col: The column that the token ends on.
    355            start: The start index of the token.
    356            end: The ending index of the token.
    357            comments: The comments to attach to the token.
    358        """
    359        self.token_type = token_type
    360        self.text = text
    361        self.line = line
    362        self.col = col
    363        self.start = start
    364        self.end = end
    365        self.comments = 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) -> sqlglot.tokens.Token: View Source

    318    @classmethod
    319    def number(cls, number: int) -> Token:
    320        """Returns a NUMBER token with `number` as its text."""
    321        return cls(TokenType.NUMBER, str(number))

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

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

    323    @classmethod
    324    def string(cls, string: str) -> Token:
    325        """Returns a STRING token with `string` as its text."""
    326        return cls(TokenType.STRING, string)

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

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

    328    @classmethod
    329    def identifier(cls, identifier: str) -> Token:
    330        """Returns an IDENTIFIER token with `identifier` as its text."""
    331        return cls(TokenType.IDENTIFIER, identifier)

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

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

    333    @classmethod
    334    def var(cls, var: str) -> Token:
    335        """Returns an VAR token with `var` as its text."""
    336        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

     425class Tokenizer(metaclass=_Tokenizer):
     426    SINGLE_TOKENS = {
     427        "(": TokenType.L_PAREN,
     428        ")": TokenType.R_PAREN,
     429        "[": TokenType.L_BRACKET,
     430        "]": TokenType.R_BRACKET,
     431        "{": TokenType.L_BRACE,
     432        "}": TokenType.R_BRACE,
     433        "&": TokenType.AMP,
     434        "^": TokenType.CARET,
     435        ":": TokenType.COLON,
     436        ",": TokenType.COMMA,
     437        ".": TokenType.DOT,
     438        "-": TokenType.DASH,
     439        "=": TokenType.EQ,
     440        ">": TokenType.GT,
     441        "<": TokenType.LT,
     442        "%": TokenType.MOD,
     443        "!": TokenType.NOT,
     444        "|": TokenType.PIPE,
     445        "+": TokenType.PLUS,
     446        ";": TokenType.SEMICOLON,
     447        "/": TokenType.SLASH,
     448        "\\": TokenType.BACKSLASH,
     449        "*": TokenType.STAR,
     450        "~": TokenType.TILDA,
     451        "?": TokenType.PLACEHOLDER,
     452        "@": TokenType.PARAMETER,
     453        # used for breaking a var like x'y' but nothing else
     454        # the token type doesn't matter
     455        "'": TokenType.QUOTE,
     456        "`": TokenType.IDENTIFIER,
     457        '"': TokenType.IDENTIFIER,
     458        "#": TokenType.HASH,
     459    }
     460
     461    BIT_STRINGS: t.List[str | t.Tuple[str, str]] = []
     462    BYTE_STRINGS: t.List[str | t.Tuple[str, str]] = []
     463    HEX_STRINGS: t.List[str | t.Tuple[str, str]] = []
     464    RAW_STRINGS: t.List[str | t.Tuple[str, str]] = []
     465    IDENTIFIERS: t.List[str | t.Tuple[str, str]] = ['"']
     466    IDENTIFIER_ESCAPES = ['"']
     467    QUOTES: t.List[t.Tuple[str, str] | str] = ["'"]
     468    STRING_ESCAPES = ["'"]
     469    VAR_SINGLE_TOKENS: t.Set[str] = set()
     470
     471    # Autofilled
     472    IDENTIFIERS_CAN_START_WITH_DIGIT: bool = False
     473
     474    _COMMENTS: t.Dict[str, str] = {}
     475    _FORMAT_STRINGS: t.Dict[str, t.Tuple[str, TokenType]] = {}
     476    _IDENTIFIERS: t.Dict[str, str] = {}
     477    _IDENTIFIER_ESCAPES: t.Set[str] = set()
     478    _QUOTES: t.Dict[str, str] = {}
     479    _STRING_ESCAPES: t.Set[str] = set()
     480    _KEYWORD_TRIE: t.Dict = {}
     481
     482    KEYWORDS: t.Dict[str, TokenType] = {
     483        **{f"{{%{postfix}": TokenType.BLOCK_START for postfix in ("", "+", "-")},
     484        **{f"{prefix}%}}": TokenType.BLOCK_END for prefix in ("", "+", "-")},
     485        **{f"{{{{{postfix}": TokenType.BLOCK_START for postfix in ("+", "-")},
     486        **{f"{prefix}}}}}": TokenType.BLOCK_END for prefix in ("+", "-")},
     487        "/*+": TokenType.HINT,
     488        "==": TokenType.EQ,
     489        "::": TokenType.DCOLON,
     490        "||": TokenType.DPIPE,
     491        ">=": TokenType.GTE,
     492        "<=": TokenType.LTE,
     493        "<>": TokenType.NEQ,
     494        "!=": TokenType.NEQ,
     495        "<=>": TokenType.NULLSAFE_EQ,
     496        "->": TokenType.ARROW,
     497        "->>": TokenType.DARROW,
     498        "=>": TokenType.FARROW,
     499        "#>": TokenType.HASH_ARROW,
     500        "#>>": TokenType.DHASH_ARROW,
     501        "<->": TokenType.LR_ARROW,
     502        "&&": TokenType.DAMP,
     503        "ALL": TokenType.ALL,
     504        "ALWAYS": TokenType.ALWAYS,
     505        "AND": TokenType.AND,
     506        "ANTI": TokenType.ANTI,
     507        "ANY": TokenType.ANY,
     508        "ASC": TokenType.ASC,
     509        "AS": TokenType.ALIAS,
     510        "ASOF": TokenType.ASOF,
     511        "AUTOINCREMENT": TokenType.AUTO_INCREMENT,
     512        "AUTO_INCREMENT": TokenType.AUTO_INCREMENT,
     513        "BEGIN": TokenType.BEGIN,
     514        "BETWEEN": TokenType.BETWEEN,
     515        "CACHE": TokenType.CACHE,
     516        "UNCACHE": TokenType.UNCACHE,
     517        "CASE": TokenType.CASE,
     518        "CHARACTER SET": TokenType.CHARACTER_SET,
     519        "CLUSTER BY": TokenType.CLUSTER_BY,
     520        "COLLATE": TokenType.COLLATE,
     521        "COLUMN": TokenType.COLUMN,
     522        "COMMIT": TokenType.COMMIT,
     523        "CONSTRAINT": TokenType.CONSTRAINT,
     524        "CREATE": TokenType.CREATE,
     525        "CROSS": TokenType.CROSS,
     526        "CUBE": TokenType.CUBE,
     527        "CURRENT_DATE": TokenType.CURRENT_DATE,
     528        "CURRENT_TIME": TokenType.CURRENT_TIME,
     529        "CURRENT_TIMESTAMP": TokenType.CURRENT_TIMESTAMP,
     530        "CURRENT_USER": TokenType.CURRENT_USER,
     531        "DATABASE": TokenType.DATABASE,
     532        "DEFAULT": TokenType.DEFAULT,
     533        "DELETE": TokenType.DELETE,
     534        "DESC": TokenType.DESC,
     535        "DESCRIBE": TokenType.DESCRIBE,
     536        "DISTINCT": TokenType.DISTINCT,
     537        "DISTRIBUTE BY": TokenType.DISTRIBUTE_BY,
     538        "DIV": TokenType.DIV,
     539        "DROP": TokenType.DROP,
     540        "ELSE": TokenType.ELSE,
     541        "END": TokenType.END,
     542        "ESCAPE": TokenType.ESCAPE,
     543        "EXCEPT": TokenType.EXCEPT,
     544        "EXECUTE": TokenType.EXECUTE,
     545        "EXISTS": TokenType.EXISTS,
     546        "FALSE": TokenType.FALSE,
     547        "FETCH": TokenType.FETCH,
     548        "FILTER": TokenType.FILTER,
     549        "FIRST": TokenType.FIRST,
     550        "FULL": TokenType.FULL,
     551        "FUNCTION": TokenType.FUNCTION,
     552        "FOR": TokenType.FOR,
     553        "FOREIGN KEY": TokenType.FOREIGN_KEY,
     554        "FORMAT": TokenType.FORMAT,
     555        "FROM": TokenType.FROM,
     556        "GEOGRAPHY": TokenType.GEOGRAPHY,
     557        "GEOMETRY": TokenType.GEOMETRY,
     558        "GLOB": TokenType.GLOB,
     559        "GROUP BY": TokenType.GROUP_BY,
     560        "GROUPING SETS": TokenType.GROUPING_SETS,
     561        "HAVING": TokenType.HAVING,
     562        "IF": TokenType.IF,
     563        "ILIKE": TokenType.ILIKE,
     564        "IN": TokenType.IN,
     565        "INDEX": TokenType.INDEX,
     566        "INET": TokenType.INET,
     567        "INNER": TokenType.INNER,
     568        "INSERT": TokenType.INSERT,
     569        "INTERVAL": TokenType.INTERVAL,
     570        "INTERSECT": TokenType.INTERSECT,
     571        "INTO": TokenType.INTO,
     572        "IS": TokenType.IS,
     573        "ISNULL": TokenType.ISNULL,
     574        "JOIN": TokenType.JOIN,
     575        "KEEP": TokenType.KEEP,
     576        "LATERAL": TokenType.LATERAL,
     577        "LEFT": TokenType.LEFT,
     578        "LIKE": TokenType.LIKE,
     579        "LIMIT": TokenType.LIMIT,
     580        "LOAD": TokenType.LOAD,
     581        "LOCK": TokenType.LOCK,
     582        "MERGE": TokenType.MERGE,
     583        "NATURAL": TokenType.NATURAL,
     584        "NEXT": TokenType.NEXT,
     585        "NEXT VALUE FOR": TokenType.NEXT_VALUE_FOR,
     586        "NOT": TokenType.NOT,
     587        "NOTNULL": TokenType.NOTNULL,
     588        "NULL": TokenType.NULL,
     589        "OBJECT": TokenType.OBJECT,
     590        "OFFSET": TokenType.OFFSET,
     591        "ON": TokenType.ON,
     592        "OR": TokenType.OR,
     593        "ORDER BY": TokenType.ORDER_BY,
     594        "ORDINALITY": TokenType.ORDINALITY,
     595        "OUTER": TokenType.OUTER,
     596        "OVER": TokenType.OVER,
     597        "OVERLAPS": TokenType.OVERLAPS,
     598        "OVERWRITE": TokenType.OVERWRITE,
     599        "PARTITION": TokenType.PARTITION,
     600        "PARTITION BY": TokenType.PARTITION_BY,
     601        "PARTITIONED BY": TokenType.PARTITION_BY,
     602        "PARTITIONED_BY": TokenType.PARTITION_BY,
     603        "PERCENT": TokenType.PERCENT,
     604        "PIVOT": TokenType.PIVOT,
     605        "PRAGMA": TokenType.PRAGMA,
     606        "PRIMARY KEY": TokenType.PRIMARY_KEY,
     607        "PROCEDURE": TokenType.PROCEDURE,
     608        "QUALIFY": TokenType.QUALIFY,
     609        "RANGE": TokenType.RANGE,
     610        "RECURSIVE": TokenType.RECURSIVE,
     611        "REGEXP": TokenType.RLIKE,
     612        "REPLACE": TokenType.REPLACE,
     613        "RETURNING": TokenType.RETURNING,
     614        "REFERENCES": TokenType.REFERENCES,
     615        "RIGHT": TokenType.RIGHT,
     616        "RLIKE": TokenType.RLIKE,
     617        "ROLLBACK": TokenType.ROLLBACK,
     618        "ROLLUP": TokenType.ROLLUP,
     619        "ROW": TokenType.ROW,
     620        "ROWS": TokenType.ROWS,
     621        "SCHEMA": TokenType.SCHEMA,
     622        "SELECT": TokenType.SELECT,
     623        "SEMI": TokenType.SEMI,
     624        "SET": TokenType.SET,
     625        "SETTINGS": TokenType.SETTINGS,
     626        "SHOW": TokenType.SHOW,
     627        "SIMILAR TO": TokenType.SIMILAR_TO,
     628        "SOME": TokenType.SOME,
     629        "SORT BY": TokenType.SORT_BY,
     630        "TABLE": TokenType.TABLE,
     631        "TABLESAMPLE": TokenType.TABLE_SAMPLE,
     632        "TEMP": TokenType.TEMPORARY,
     633        "TEMPORARY": TokenType.TEMPORARY,
     634        "THEN": TokenType.THEN,
     635        "TRUE": TokenType.TRUE,
     636        "UNION": TokenType.UNION,
     637        "UNNEST": TokenType.UNNEST,
     638        "UNPIVOT": TokenType.UNPIVOT,
     639        "UPDATE": TokenType.UPDATE,
     640        "USE": TokenType.USE,
     641        "USING": TokenType.USING,
     642        "UUID": TokenType.UUID,
     643        "VALUES": TokenType.VALUES,
     644        "VIEW": TokenType.VIEW,
     645        "VOLATILE": TokenType.VOLATILE,
     646        "WHEN": TokenType.WHEN,
     647        "WHERE": TokenType.WHERE,
     648        "WINDOW": TokenType.WINDOW,
     649        "WITH": TokenType.WITH,
     650        "APPLY": TokenType.APPLY,
     651        "ARRAY": TokenType.ARRAY,
     652        "BIT": TokenType.BIT,
     653        "BOOL": TokenType.BOOLEAN,
     654        "BOOLEAN": TokenType.BOOLEAN,
     655        "BYTE": TokenType.TINYINT,
     656        "TINYINT": TokenType.TINYINT,
     657        "SHORT": TokenType.SMALLINT,
     658        "SMALLINT": TokenType.SMALLINT,
     659        "INT2": TokenType.SMALLINT,
     660        "INTEGER": TokenType.INT,
     661        "INT": TokenType.INT,
     662        "INT4": TokenType.INT,
     663        "LONG": TokenType.BIGINT,
     664        "BIGINT": TokenType.BIGINT,
     665        "INT8": TokenType.BIGINT,
     666        "DEC": TokenType.DECIMAL,
     667        "DECIMAL": TokenType.DECIMAL,
     668        "BIGDECIMAL": TokenType.BIGDECIMAL,
     669        "BIGNUMERIC": TokenType.BIGDECIMAL,
     670        "MAP": TokenType.MAP,
     671        "NULLABLE": TokenType.NULLABLE,
     672        "NUMBER": TokenType.DECIMAL,
     673        "NUMERIC": TokenType.DECIMAL,
     674        "FIXED": TokenType.DECIMAL,
     675        "REAL": TokenType.FLOAT,
     676        "FLOAT": TokenType.FLOAT,
     677        "FLOAT4": TokenType.FLOAT,
     678        "FLOAT8": TokenType.DOUBLE,
     679        "DOUBLE": TokenType.DOUBLE,
     680        "DOUBLE PRECISION": TokenType.DOUBLE,
     681        "JSON": TokenType.JSON,
     682        "CHAR": TokenType.CHAR,
     683        "CHARACTER": TokenType.CHAR,
     684        "NCHAR": TokenType.NCHAR,
     685        "VARCHAR": TokenType.VARCHAR,
     686        "VARCHAR2": TokenType.VARCHAR,
     687        "NVARCHAR": TokenType.NVARCHAR,
     688        "NVARCHAR2": TokenType.NVARCHAR,
     689        "STR": TokenType.TEXT,
     690        "STRING": TokenType.TEXT,
     691        "TEXT": TokenType.TEXT,
     692        "CLOB": TokenType.TEXT,
     693        "LONGVARCHAR": TokenType.TEXT,
     694        "BINARY": TokenType.BINARY,
     695        "BLOB": TokenType.VARBINARY,
     696        "BYTEA": TokenType.VARBINARY,
     697        "VARBINARY": TokenType.VARBINARY,
     698        "TIME": TokenType.TIME,
     699        "TIMESTAMP": TokenType.TIMESTAMP,
     700        "TIMESTAMPTZ": TokenType.TIMESTAMPTZ,
     701        "TIMESTAMPLTZ": TokenType.TIMESTAMPLTZ,
     702        "DATE": TokenType.DATE,
     703        "DATETIME": TokenType.DATETIME,
     704        "INT4RANGE": TokenType.INT4RANGE,
     705        "INT4MULTIRANGE": TokenType.INT4MULTIRANGE,
     706        "INT8RANGE": TokenType.INT8RANGE,
     707        "INT8MULTIRANGE": TokenType.INT8MULTIRANGE,
     708        "NUMRANGE": TokenType.NUMRANGE,
     709        "NUMMULTIRANGE": TokenType.NUMMULTIRANGE,
     710        "TSRANGE": TokenType.TSRANGE,
     711        "TSMULTIRANGE": TokenType.TSMULTIRANGE,
     712        "TSTZRANGE": TokenType.TSTZRANGE,
     713        "TSTZMULTIRANGE": TokenType.TSTZMULTIRANGE,
     714        "DATERANGE": TokenType.DATERANGE,
     715        "DATEMULTIRANGE": TokenType.DATEMULTIRANGE,
     716        "UNIQUE": TokenType.UNIQUE,
     717        "STRUCT": TokenType.STRUCT,
     718        "VARIANT": TokenType.VARIANT,
     719        "ALTER": TokenType.ALTER,
     720        "ANALYZE": TokenType.COMMAND,
     721        "CALL": TokenType.COMMAND,
     722        "COMMENT": TokenType.COMMENT,
     723        "COPY": TokenType.COMMAND,
     724        "EXPLAIN": TokenType.COMMAND,
     725        "GRANT": TokenType.COMMAND,
     726        "OPTIMIZE": TokenType.COMMAND,
     727        "PREPARE": TokenType.COMMAND,
     728        "TRUNCATE": TokenType.COMMAND,
     729        "VACUUM": TokenType.COMMAND,
     730        "USER-DEFINED": TokenType.USERDEFINED,
     731    }
     732
     733    WHITE_SPACE: t.Dict[t.Optional[str], TokenType] = {
     734        " ": TokenType.SPACE,
     735        "\t": TokenType.SPACE,
     736        "\n": TokenType.BREAK,
     737        "\r": TokenType.BREAK,
     738        "\r\n": TokenType.BREAK,
     739    }
     740
     741    COMMANDS = {
     742        TokenType.COMMAND,
     743        TokenType.EXECUTE,
     744        TokenType.FETCH,
     745        TokenType.SHOW,
     746    }
     747
     748    COMMAND_PREFIX_TOKENS = {TokenType.SEMICOLON, TokenType.BEGIN}
     749
     750    # handle numeric literals like in hive (3L = BIGINT)
     751    NUMERIC_LITERALS: t.Dict[str, str] = {}
     752    ENCODE: t.Optional[str] = None
     753
     754    COMMENTS = ["--", ("/*", "*/")]
     755
     756    __slots__ = (
     757        "sql",
     758        "size",
     759        "tokens",
     760        "_start",
     761        "_current",
     762        "_line",
     763        "_col",
     764        "_comments",
     765        "_char",
     766        "_end",
     767        "_peek",
     768        "_prev_token_line",
     769    )
     770
     771    def __init__(self) -> None:
     772        self.reset()
     773
     774    def reset(self) -> None:
     775        self.sql = ""
     776        self.size = 0
     777        self.tokens: t.List[Token] = []
     778        self._start = 0
     779        self._current = 0
     780        self._line = 1
     781        self._col = 0
     782        self._comments: t.List[str] = []
     783
     784        self._char = ""
     785        self._end = False
     786        self._peek = ""
     787        self._prev_token_line = -1
     788
     789    def tokenize(self, sql: str) -> t.List[Token]:
     790        """Returns a list of tokens corresponding to the SQL string `sql`."""
     791        self.reset()
     792        self.sql = sql
     793        self.size = len(sql)
     794
     795        try:
     796            self._scan()
     797        except Exception as e:
     798            start = max(self._current - 50, 0)
     799            end = min(self._current + 50, self.size - 1)
     800            context = self.sql[start:end]
     801            raise ValueError(f"Error tokenizing '{context}'") from e
     802
     803        return self.tokens
     804
     805    def _scan(self, until: t.Optional[t.Callable] = None) -> None:
     806        while self.size and not self._end:
     807            self._start = self._current
     808            self._advance()
     809
     810            if self._char is None:
     811                break
     812
     813            if self._char not in self.WHITE_SPACE:
     814                if self._char.isdigit():
     815                    self._scan_number()
     816                elif self._char in self._IDENTIFIERS:
     817                    self._scan_identifier(self._IDENTIFIERS[self._char])
     818                else:
     819                    self._scan_keywords()
     820
     821            if until and until():
     822                break
     823
     824        if self.tokens and self._comments:
     825            self.tokens[-1].comments.extend(self._comments)
     826
     827    def _chars(self, size: int) -> str:
     828        if size == 1:
     829            return self._char
     830
     831        start = self._current - 1
     832        end = start + size
     833
     834        return self.sql[start:end] if end <= self.size else ""
     835
     836    def _advance(self, i: int = 1, alnum: bool = False) -> None:
     837        if self.WHITE_SPACE.get(self._char) is TokenType.BREAK:
     838            self._col = 1
     839            self._line += 1
     840        else:
     841            self._col += i
     842
     843        self._current += i
     844        self._end = self._current >= self.size
     845        self._char = self.sql[self._current - 1]
     846        self._peek = "" if self._end else self.sql[self._current]
     847
     848        if alnum and self._char.isalnum():
     849            # Here we use local variables instead of attributes for better performance
     850            _col = self._col
     851            _current = self._current
     852            _end = self._end
     853            _peek = self._peek
     854
     855            while _peek.isalnum():
     856                _col += 1
     857                _current += 1
     858                _end = _current >= self.size
     859                _peek = "" if _end else self.sql[_current]
     860
     861            self._col = _col
     862            self._current = _current
     863            self._end = _end
     864            self._peek = _peek
     865            self._char = self.sql[_current - 1]
     866
     867    @property
     868    def _text(self) -> str:
     869        return self.sql[self._start : self._current]
     870
     871    def peek(self, i: int = 0) -> str:
     872        i = self._current + i
     873        if i < self.size:
     874            return self.sql[i]
     875        return ""
     876
     877    def _add(self, token_type: TokenType, text: t.Optional[str] = None) -> None:
     878        self._prev_token_line = self._line
     879        self.tokens.append(
     880            Token(
     881                token_type,
     882                text=self._text if text is None else text,
     883                line=self._line,
     884                col=self._col,
     885                start=self._start,
     886                end=self._current - 1,
     887                comments=self._comments,
     888            )
     889        )
     890        self._comments = []
     891
     892        # If we have either a semicolon or a begin token before the command's token, we'll parse
     893        # whatever follows the command's token as a string
     894        if (
     895            token_type in self.COMMANDS
     896            and self._peek != ";"
     897            and (len(self.tokens) == 1 or self.tokens[-2].token_type in self.COMMAND_PREFIX_TOKENS)
     898        ):
     899            start = self._current
     900            tokens = len(self.tokens)
     901            self._scan(lambda: self._peek == ";")
     902            self.tokens = self.tokens[:tokens]
     903            text = self.sql[start : self._current].strip()
     904            if text:
     905                self._add(TokenType.STRING, text)
     906
     907    def _scan_keywords(self) -> None:
     908        size = 0
     909        word = None
     910        chars = self._text
     911        char = chars
     912        prev_space = False
     913        skip = False
     914        trie = self._KEYWORD_TRIE
     915        single_token = char in self.SINGLE_TOKENS
     916
     917        while chars:
     918            if skip:
     919                result = TrieResult.PREFIX
     920            else:
     921                result, trie = in_trie(trie, char.upper())
     922
     923            if result == TrieResult.FAILED:
     924                break
     925            if result == TrieResult.EXISTS:
     926                word = chars
     927
     928            size += 1
     929            end = self._current - 1 + size
     930
     931            if end < self.size:
     932                char = self.sql[end]
     933                single_token = single_token or char in self.SINGLE_TOKENS
     934                is_space = char in self.WHITE_SPACE
     935
     936                if not is_space or not prev_space:
     937                    if is_space:
     938                        char = " "
     939                    chars += char
     940                    prev_space = is_space
     941                    skip = False
     942                else:
     943                    skip = True
     944            else:
     945                char = ""
     946                chars = " "
     947
     948        word = None if not single_token and chars[-1] not in self.WHITE_SPACE else word
     949
     950        if not word:
     951            if self._char in self.SINGLE_TOKENS:
     952                self._add(self.SINGLE_TOKENS[self._char], text=self._char)
     953                return
     954            self._scan_var()
     955            return
     956
     957        if self._scan_string(word):
     958            return
     959        if self._scan_comment(word):
     960            return
     961
     962        self._advance(size - 1)
     963        word = word.upper()
     964        self._add(self.KEYWORDS[word], text=word)
     965
     966    def _scan_comment(self, comment_start: str) -> bool:
     967        if comment_start not in self._COMMENTS:
     968            return False
     969
     970        comment_start_line = self._line
     971        comment_start_size = len(comment_start)
     972        comment_end = self._COMMENTS[comment_start]
     973
     974        if comment_end:
     975            # Skip the comment's start delimiter
     976            self._advance(comment_start_size)
     977
     978            comment_end_size = len(comment_end)
     979            while not self._end and self._chars(comment_end_size) != comment_end:
     980                self._advance(alnum=True)
     981
     982            self._comments.append(self._text[comment_start_size : -comment_end_size + 1])
     983            self._advance(comment_end_size - 1)
     984        else:
     985            while not self._end and not self.WHITE_SPACE.get(self._peek) is TokenType.BREAK:
     986                self._advance(alnum=True)
     987            self._comments.append(self._text[comment_start_size:])
     988
     989        # Leading comment is attached to the succeeding token, whilst trailing comment to the preceding.
     990        # Multiple consecutive comments are preserved by appending them to the current comments list.
     991        if comment_start_line == self._prev_token_line:
     992            self.tokens[-1].comments.extend(self._comments)
     993            self._comments = []
     994            self._prev_token_line = self._line
     995
     996        return True
     997
     998    def _scan_number(self) -> None:
     999        if self._char == "0":
    1000            peek = self._peek.upper()
    1001            if peek == "B":
    1002                return self._scan_bits() if self.BIT_STRINGS else self._add(TokenType.NUMBER)
    1003            elif peek == "X":
    1004                return self._scan_hex() if self.HEX_STRINGS else self._add(TokenType.NUMBER)
    1005
    1006        decimal = False
    1007        scientific = 0
    1008
    1009        while True:
    1010            if self._peek.isdigit():
    1011                self._advance()
    1012            elif self._peek == "." and not decimal:
    1013                after = self.peek(1)
    1014                if after.isdigit() or not after.isalpha():
    1015                    decimal = True
    1016                    self._advance()
    1017                else:
    1018                    return self._add(TokenType.VAR)
    1019            elif self._peek in ("-", "+") and scientific == 1:
    1020                scientific += 1
    1021                self._advance()
    1022            elif self._peek.upper() == "E" and not scientific:
    1023                scientific += 1
    1024                self._advance()
    1025            elif self._peek.isidentifier():
    1026                number_text = self._text
    1027                literal = ""
    1028
    1029                while self._peek.strip() and self._peek not in self.SINGLE_TOKENS:
    1030                    literal += self._peek.upper()
    1031                    self._advance()
    1032
    1033                token_type = self.KEYWORDS.get(self.NUMERIC_LITERALS.get(literal, ""))
    1034
    1035                if token_type:
    1036                    self._add(TokenType.NUMBER, number_text)
    1037                    self._add(TokenType.DCOLON, "::")
    1038                    return self._add(token_type, literal)
    1039                elif self.IDENTIFIERS_CAN_START_WITH_DIGIT:
    1040                    return self._add(TokenType.VAR)
    1041
    1042                self._add(TokenType.NUMBER, number_text)
    1043                return self._advance(-len(literal))
    1044            else:
    1045                return self._add(TokenType.NUMBER)
    1046
    1047    def _scan_bits(self) -> None:
    1048        self._advance()
    1049        value = self._extract_value()
    1050        try:
    1051            # If `value` can't be converted to a binary, fallback to tokenizing it as an identifier
    1052            int(value, 2)
    1053            self._add(TokenType.BIT_STRING, value[2:])  # Drop the 0b
    1054        except ValueError:
    1055            self._add(TokenType.IDENTIFIER)
    1056
    1057    def _scan_hex(self) -> None:
    1058        self._advance()
    1059        value = self._extract_value()
    1060        try:
    1061            # If `value` can't be converted to a hex, fallback to tokenizing it as an identifier
    1062            int(value, 16)
    1063            self._add(TokenType.HEX_STRING, value[2:])  # Drop the 0x
    1064        except ValueError:
    1065            self._add(TokenType.IDENTIFIER)
    1066
    1067    def _extract_value(self) -> str:
    1068        while True:
    1069            char = self._peek.strip()
    1070            if char and char not in self.SINGLE_TOKENS:
    1071                self._advance(alnum=True)
    1072            else:
    1073                break
    1074
    1075        return self._text
    1076
    1077    def _scan_string(self, start: str) -> bool:
    1078        base = None
    1079        token_type = TokenType.STRING
    1080
    1081        if start in self._QUOTES:
    1082            end = self._QUOTES[start]
    1083        elif start in self._FORMAT_STRINGS:
    1084            end, token_type = self._FORMAT_STRINGS[start]
    1085
    1086            if token_type == TokenType.HEX_STRING:
    1087                base = 16
    1088            elif token_type == TokenType.BIT_STRING:
    1089                base = 2
    1090        else:
    1091            return False
    1092
    1093        self._advance(len(start))
    1094        text = self._extract_string(end)
    1095
    1096        if base:
    1097            try:
    1098                int(text, base)
    1099            except:
    1100                raise RuntimeError(
    1101                    f"Numeric string contains invalid characters from {self._line}:{self._start}"
    1102                )
    1103        else:
    1104            text = text.encode(self.ENCODE).decode(self.ENCODE) if self.ENCODE else text
    1105
    1106        self._add(token_type, text)
    1107        return True
    1108
    1109    def _scan_identifier(self, identifier_end: str) -> None:
    1110        self._advance()
    1111        text = self._extract_string(identifier_end, self._IDENTIFIER_ESCAPES)
    1112        self._add(TokenType.IDENTIFIER, text)
    1113
    1114    def _scan_var(self) -> None:
    1115        while True:
    1116            char = self._peek.strip()
    1117            if char and (char in self.VAR_SINGLE_TOKENS or char not in self.SINGLE_TOKENS):
    1118                self._advance(alnum=True)
    1119            else:
    1120                break
    1121
    1122        self._add(
    1123            TokenType.VAR
    1124            if self.tokens and self.tokens[-1].token_type == TokenType.PARAMETER
    1125            else self.KEYWORDS.get(self._text.upper(), TokenType.VAR)
    1126        )
    1127
    1128    def _extract_string(self, delimiter: str, escapes=None) -> str:
    1129        text = ""
    1130        delim_size = len(delimiter)
    1131        escapes = self._STRING_ESCAPES if escapes is None else escapes
    1132
    1133        while True:
    1134            if self._char in escapes and (self._peek == delimiter or self._peek in escapes):
    1135                if self._peek == delimiter:
    1136                    text += self._peek
    1137                else:
    1138                    text += self._char + self._peek
    1139
    1140                if self._current + 1 < self.size:
    1141                    self._advance(2)
    1142                else:
    1143                    raise RuntimeError(f"Missing {delimiter} from {self._line}:{self._current}")
    1144            else:
    1145                if self._chars(delim_size) == delimiter:
    1146                    if delim_size > 1:
    1147                        self._advance(delim_size - 1)
    1148                    break
    1149
    1150                if self._end:
    1151                    raise RuntimeError(f"Missing {delimiter} from {self._line}:{self._start}")
    1152
    1153                current = self._current - 1
    1154                self._advance(alnum=True)
    1155                text += self.sql[current : self._current - 1]
    1156
    1157        return text

SINGLE_TOKENS = {'(': <TokenType.L_PAREN: 'L_PAREN'>, ')': <TokenType.R_PAREN: 'R_PAREN'>, '[': <TokenType.L_BRACKET: 'L_BRACKET'>, ']': <TokenType.R_BRACKET: 'R_BRACKET'>, '{': <TokenType.L_BRACE: 'L_BRACE'>, '}': <TokenType.R_BRACE: 'R_BRACE'>, '&': <TokenType.AMP: 'AMP'>, '^': <TokenType.CARET: 'CARET'>, ':': <TokenType.COLON: 'COLON'>, ',': <TokenType.COMMA: 'COMMA'>, '.': <TokenType.DOT: 'DOT'>, '-': <TokenType.DASH: 'DASH'>, '=': <TokenType.EQ: 'EQ'>, '>': <TokenType.GT: 'GT'>, '<': <TokenType.LT: 'LT'>, '%': <TokenType.MOD: 'MOD'>, '!': <TokenType.NOT: 'NOT'>, '|': <TokenType.PIPE: 'PIPE'>, '+': <TokenType.PLUS: 'PLUS'>, ';': <TokenType.SEMICOLON: 'SEMICOLON'>, '/': <TokenType.SLASH: 'SLASH'>, '\\': <TokenType.BACKSLASH: 'BACKSLASH'>, '*': <TokenType.STAR: 'STAR'>, '~': <TokenType.TILDA: 'TILDA'>, '?': <TokenType.PLACEHOLDER: 'PLACEHOLDER'>, '@': <TokenType.PARAMETER: 'PARAMETER'>, "'": <TokenType.QUOTE: 'QUOTE'>, '`': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '"': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '#': <TokenType.HASH: 'HASH'>}
BIT_STRINGS: List[Union[str, Tuple[str, str]]] = []
BYTE_STRINGS: List[Union[str, Tuple[str, str]]] = []
HEX_STRINGS: List[Union[str, Tuple[str, str]]] = []
RAW_STRINGS: List[Union[str, Tuple[str, str]]] = []
IDENTIFIERS: List[Union[str, Tuple[str, str]]] = ['"']
IDENTIFIER_ESCAPES = ['"']
QUOTES: List[Union[str, Tuple[str, str]]] = ["'"]
STRING_ESCAPES = ["'"]
VAR_SINGLE_TOKENS: Set[str] = set()
IDENTIFIERS_CAN_START_WITH_DIGIT: bool = False
KEYWORDS: Dict[str, sqlglot.tokens.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.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'>, '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'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'IF': <TokenType.IF: 'IF'>, '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'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NEXT VALUE FOR': <TokenType.NEXT_VALUE_FOR: 'NEXT_VALUE_FOR'>, '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'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'UNION': <TokenType.UNION: 'UNION'>, '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'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.BIGINT: 'BIGINT'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'COPY': <TokenType.COMMAND: 'COMMAND'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'TRUNCATE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>}
WHITE_SPACE: Dict[Optional[str], sqlglot.tokens.TokenType] = {' ': <TokenType.SPACE: 'SPACE'>, '\t': <TokenType.SPACE: 'SPACE'>, '\n': <TokenType.BREAK: 'BREAK'>, '\r': <TokenType.BREAK: 'BREAK'>, '\r\n': <TokenType.BREAK: 'BREAK'>}
COMMANDS = {<TokenType.EXECUTE: 'EXECUTE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.SHOW: 'SHOW'>, <TokenType.FETCH: 'FETCH'>}
COMMAND_PREFIX_TOKENS = {<TokenType.BEGIN: 'BEGIN'>, <TokenType.SEMICOLON: 'SEMICOLON'>}
NUMERIC_LITERALS: Dict[str, str] = {}
ENCODE: Optional[str] = None
COMMENTS = ['--', ('/*', '*/')]
def reset(self) -> None: View Source

    774    def reset(self) -> None:
    775        self.sql = ""
    776        self.size = 0
    777        self.tokens: t.List[Token] = []
    778        self._start = 0
    779        self._current = 0
    780        self._line = 1
    781        self._col = 0
    782        self._comments: t.List[str] = []
    783
    784        self._char = ""
    785        self._end = False
    786        self._peek = ""
    787        self._prev_token_line = -1

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

    789    def tokenize(self, sql: str) -> t.List[Token]:
    790        """Returns a list of tokens corresponding to the SQL string `sql`."""
    791        self.reset()
    792        self.sql = sql
    793        self.size = len(sql)
    794
    795        try:
    796            self._scan()
    797        except Exception as e:
    798            start = max(self._current - 50, 0)
    799            end = min(self._current + 50, self.size - 1)
    800            context = self.sql[start:end]
    801            raise ValueError(f"Error tokenizing '{context}'") from e
    802
    803        return self.tokens

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

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

    871    def peek(self, i: int = 0) -> str:
    872        i = self._current + i
    873        if i < self.size:
    874            return self.sql[i]
    875        return ""

size
sql
tokens