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

An enumeration.

L_PAREN = <TokenType.L_PAREN: 'L_PAREN'>
R_PAREN = <TokenType.R_PAREN: 'R_PAREN'>
L_BRACKET = <TokenType.L_BRACKET: 'L_BRACKET'>
R_BRACKET = <TokenType.R_BRACKET: 'R_BRACKET'>
L_BRACE = <TokenType.L_BRACE: 'L_BRACE'>
R_BRACE = <TokenType.R_BRACE: 'R_BRACE'>
COMMA = <TokenType.COMMA: 'COMMA'>
DOT = <TokenType.DOT: 'DOT'>
DASH = <TokenType.DASH: 'DASH'>
PLUS = <TokenType.PLUS: 'PLUS'>
COLON = <TokenType.COLON: 'COLON'>
DCOLON = <TokenType.DCOLON: 'DCOLON'>
DQMARK = <TokenType.DQMARK: 'DQMARK'>
SEMICOLON = <TokenType.SEMICOLON: 'SEMICOLON'>
STAR = <TokenType.STAR: 'STAR'>
BACKSLASH = <TokenType.BACKSLASH: 'BACKSLASH'>
SLASH = <TokenType.SLASH: 'SLASH'>
LT = <TokenType.LT: 'LT'>
LTE = <TokenType.LTE: 'LTE'>
GT = <TokenType.GT: 'GT'>
GTE = <TokenType.GTE: 'GTE'>
NOT = <TokenType.NOT: 'NOT'>
EQ = <TokenType.EQ: 'EQ'>
NEQ = <TokenType.NEQ: 'NEQ'>
NULLSAFE_EQ = <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>
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'>
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'>
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

    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}>"

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

    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

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

    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))

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

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

    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)

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

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

    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)

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

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

    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)

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

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

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

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

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

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

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

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

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

size
sql
tokens