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

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

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

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

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

    323    @classmethod
    324    def number(cls, number: int) -> Token:
    325        """Returns a NUMBER token with `number` as its text."""
    326        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

    328    @classmethod
    329    def string(cls, string: str) -> Token:
    330        """Returns a STRING token with `string` as its text."""
    331        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

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

    338    @classmethod
    339    def var(cls, var: str) -> Token:
    340        """Returns an VAR token with `var` as its text."""
    341        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

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

    780    def reset(self) -> None:
    781        self.sql = ""
    782        self.size = 0
    783        self.tokens: t.List[Token] = []
    784        self._start = 0
    785        self._current = 0
    786        self._line = 1
    787        self._col = 0
    788        self._comments: t.List[str] = []
    789
    790        self._char = ""
    791        self._end = False
    792        self._peek = ""
    793        self._prev_token_line = -1

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

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

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

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

    877    def peek(self, i: int = 0) -> str:
    878        i = self._current + i
    879        if i < self.size:
    880            return self.sql[i]
    881        return ""

size
sql
tokens