Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

An enumeration.

L_PAREN = <TokenType.L_PAREN: 'L_PAREN'>
R_PAREN = <TokenType.R_PAREN: 'R_PAREN'>
L_BRACKET = <TokenType.L_BRACKET: 'L_BRACKET'>
R_BRACKET = <TokenType.R_BRACKET: 'R_BRACKET'>
L_BRACE = <TokenType.L_BRACE: 'L_BRACE'>
R_BRACE = <TokenType.R_BRACE: 'R_BRACE'>
COMMA = <TokenType.COMMA: 'COMMA'>
DOT = <TokenType.DOT: 'DOT'>
DASH = <TokenType.DASH: 'DASH'>
PLUS = <TokenType.PLUS: 'PLUS'>
COLON = <TokenType.COLON: 'COLON'>
DCOLON = <TokenType.DCOLON: 'DCOLON'>
SEMICOLON = <TokenType.SEMICOLON: 'SEMICOLON'>
STAR = <TokenType.STAR: 'STAR'>
BACKSLASH = <TokenType.BACKSLASH: 'BACKSLASH'>
SLASH = <TokenType.SLASH: 'SLASH'>
LT = <TokenType.LT: 'LT'>
LTE = <TokenType.LTE: 'LTE'>
GT = <TokenType.GT: 'GT'>
GTE = <TokenType.GTE: 'GTE'>
NOT = <TokenType.NOT: 'NOT'>
EQ = <TokenType.EQ: 'EQ'>
NEQ = <TokenType.NEQ: 'NEQ'>
NULLSAFE_EQ = <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>
AND = <TokenType.AND: 'AND'>
OR = <TokenType.OR: 'OR'>
AMP = <TokenType.AMP: 'AMP'>
DPIPE = <TokenType.DPIPE: 'DPIPE'>
PIPE = <TokenType.PIPE: 'PIPE'>
CARET = <TokenType.CARET: 'CARET'>
TILDA = <TokenType.TILDA: 'TILDA'>
ARROW = <TokenType.ARROW: 'ARROW'>
DARROW = <TokenType.DARROW: 'DARROW'>
FARROW = <TokenType.FARROW: 'FARROW'>
HASH = <TokenType.HASH: 'HASH'>
HASH_ARROW = <TokenType.HASH_ARROW: 'HASH_ARROW'>
DHASH_ARROW = <TokenType.DHASH_ARROW: 'DHASH_ARROW'>
LR_ARROW = <TokenType.LR_ARROW: 'LR_ARROW'>
LT_AT = <TokenType.LT_AT: 'LT_AT'>
AT_GT = <TokenType.AT_GT: 'AT_GT'>
DOLLAR = <TokenType.DOLLAR: 'DOLLAR'>
PARAMETER = <TokenType.PARAMETER: 'PARAMETER'>
SESSION_PARAMETER = <TokenType.SESSION_PARAMETER: 'SESSION_PARAMETER'>
DAMP = <TokenType.DAMP: 'DAMP'>
XOR = <TokenType.XOR: 'XOR'>
BLOCK_START = <TokenType.BLOCK_START: 'BLOCK_START'>
BLOCK_END = <TokenType.BLOCK_END: 'BLOCK_END'>
SPACE = <TokenType.SPACE: 'SPACE'>
BREAK = <TokenType.BREAK: 'BREAK'>
STRING = <TokenType.STRING: 'STRING'>
NUMBER = <TokenType.NUMBER: 'NUMBER'>
IDENTIFIER = <TokenType.IDENTIFIER: 'IDENTIFIER'>
DATABASE = <TokenType.DATABASE: 'DATABASE'>
COLUMN = <TokenType.COLUMN: 'COLUMN'>
COLUMN_DEF = <TokenType.COLUMN_DEF: 'COLUMN_DEF'>
SCHEMA = <TokenType.SCHEMA: 'SCHEMA'>
TABLE = <TokenType.TABLE: 'TABLE'>
VAR = <TokenType.VAR: 'VAR'>
BIT_STRING = <TokenType.BIT_STRING: 'BIT_STRING'>
HEX_STRING = <TokenType.HEX_STRING: 'HEX_STRING'>
BYTE_STRING = <TokenType.BYTE_STRING: 'BYTE_STRING'>
NATIONAL_STRING = <TokenType.NATIONAL_STRING: 'NATIONAL_STRING'>
RAW_STRING = <TokenType.RAW_STRING: 'RAW_STRING'>
BIT = <TokenType.BIT: 'BIT'>
BOOLEAN = <TokenType.BOOLEAN: 'BOOLEAN'>
TINYINT = <TokenType.TINYINT: 'TINYINT'>
UTINYINT = <TokenType.UTINYINT: 'UTINYINT'>
SMALLINT = <TokenType.SMALLINT: 'SMALLINT'>
USMALLINT = <TokenType.USMALLINT: 'USMALLINT'>
INT = <TokenType.INT: 'INT'>
UINT = <TokenType.UINT: 'UINT'>
BIGINT = <TokenType.BIGINT: 'BIGINT'>
UBIGINT = <TokenType.UBIGINT: 'UBIGINT'>
INT128 = <TokenType.INT128: 'INT128'>
UINT128 = <TokenType.UINT128: 'UINT128'>
INT256 = <TokenType.INT256: 'INT256'>
UINT256 = <TokenType.UINT256: 'UINT256'>
FLOAT = <TokenType.FLOAT: 'FLOAT'>
DOUBLE = <TokenType.DOUBLE: 'DOUBLE'>
DECIMAL = <TokenType.DECIMAL: 'DECIMAL'>
BIGDECIMAL = <TokenType.BIGDECIMAL: 'BIGDECIMAL'>
CHAR = <TokenType.CHAR: 'CHAR'>
NCHAR = <TokenType.NCHAR: 'NCHAR'>
VARCHAR = <TokenType.VARCHAR: 'VARCHAR'>
NVARCHAR = <TokenType.NVARCHAR: 'NVARCHAR'>
TEXT = <TokenType.TEXT: 'TEXT'>
MEDIUMTEXT = <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <TokenType.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <TokenType.LONGBLOB: 'LONGBLOB'>
BINARY = <TokenType.BINARY: 'BINARY'>
VARBINARY = <TokenType.VARBINARY: 'VARBINARY'>
JSON = <TokenType.JSON: 'JSON'>
JSONB = <TokenType.JSONB: 'JSONB'>
TIME = <TokenType.TIME: 'TIME'>
TIMESTAMP = <TokenType.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
DATETIME = <TokenType.DATETIME: 'DATETIME'>
DATETIME64 = <TokenType.DATETIME64: 'DATETIME64'>
DATE = <TokenType.DATE: 'DATE'>
INT4RANGE = <TokenType.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <TokenType.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <TokenType.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <TokenType.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <TokenType.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <TokenType.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>
UUID = <TokenType.UUID: 'UUID'>
GEOGRAPHY = <TokenType.GEOGRAPHY: 'GEOGRAPHY'>
NULLABLE = <TokenType.NULLABLE: 'NULLABLE'>
GEOMETRY = <TokenType.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <TokenType.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <TokenType.HSTORE: 'HSTORE'>
SUPER = <TokenType.SUPER: 'SUPER'>
SERIAL = <TokenType.SERIAL: 'SERIAL'>
SMALLSERIAL = <TokenType.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <TokenType.BIGSERIAL: 'BIGSERIAL'>
XML = <TokenType.XML: 'XML'>
UNIQUEIDENTIFIER = <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
USERDEFINED = <TokenType.USERDEFINED: 'USERDEFINED'>
MONEY = <TokenType.MONEY: 'MONEY'>
SMALLMONEY = <TokenType.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <TokenType.ROWVERSION: 'ROWVERSION'>
IMAGE = <TokenType.IMAGE: 'IMAGE'>
VARIANT = <TokenType.VARIANT: 'VARIANT'>
OBJECT = <TokenType.OBJECT: 'OBJECT'>
INET = <TokenType.INET: 'INET'>
ENUM = <TokenType.ENUM: 'ENUM'>
ALIAS = <TokenType.ALIAS: 'ALIAS'>
ALTER = <TokenType.ALTER: 'ALTER'>
ALWAYS = <TokenType.ALWAYS: 'ALWAYS'>
ALL = <TokenType.ALL: 'ALL'>
ANTI = <TokenType.ANTI: 'ANTI'>
ANY = <TokenType.ANY: 'ANY'>
APPLY = <TokenType.APPLY: 'APPLY'>
ARRAY = <TokenType.ARRAY: 'ARRAY'>
ASC = <TokenType.ASC: 'ASC'>
ASOF = <TokenType.ASOF: 'ASOF'>
AUTO_INCREMENT = <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>
BEGIN = <TokenType.BEGIN: 'BEGIN'>
BETWEEN = <TokenType.BETWEEN: 'BETWEEN'>
CACHE = <TokenType.CACHE: 'CACHE'>
CASE = <TokenType.CASE: 'CASE'>
CHARACTER_SET = <TokenType.CHARACTER_SET: 'CHARACTER_SET'>
CLUSTER_BY = <TokenType.CLUSTER_BY: 'CLUSTER_BY'>
COLLATE = <TokenType.COLLATE: 'COLLATE'>
COMMAND = <TokenType.COMMAND: 'COMMAND'>
COMMENT = <TokenType.COMMENT: 'COMMENT'>
COMMIT = <TokenType.COMMIT: 'COMMIT'>
CONSTRAINT = <TokenType.CONSTRAINT: 'CONSTRAINT'>
CREATE = <TokenType.CREATE: 'CREATE'>
CROSS = <TokenType.CROSS: 'CROSS'>
CUBE = <TokenType.CUBE: 'CUBE'>
CURRENT_DATE = <TokenType.CURRENT_DATE: 'CURRENT_DATE'>
CURRENT_DATETIME = <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>
CURRENT_TIME = <TokenType.CURRENT_TIME: 'CURRENT_TIME'>
CURRENT_TIMESTAMP = <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>
CURRENT_USER = <TokenType.CURRENT_USER: 'CURRENT_USER'>
DEFAULT = <TokenType.DEFAULT: 'DEFAULT'>
DELETE = <TokenType.DELETE: 'DELETE'>
DESC = <TokenType.DESC: 'DESC'>
DESCRIBE = <TokenType.DESCRIBE: 'DESCRIBE'>
DICTIONARY = <TokenType.DICTIONARY: 'DICTIONARY'>
DISTINCT = <TokenType.DISTINCT: 'DISTINCT'>
DISTRIBUTE_BY = <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>
DIV = <TokenType.DIV: 'DIV'>
DROP = <TokenType.DROP: 'DROP'>
ELSE = <TokenType.ELSE: 'ELSE'>
END = <TokenType.END: 'END'>
ESCAPE = <TokenType.ESCAPE: 'ESCAPE'>
EXCEPT = <TokenType.EXCEPT: 'EXCEPT'>
EXECUTE = <TokenType.EXECUTE: 'EXECUTE'>
EXISTS = <TokenType.EXISTS: 'EXISTS'>
FALSE = <TokenType.FALSE: 'FALSE'>
FETCH = <TokenType.FETCH: 'FETCH'>
FILTER = <TokenType.FILTER: 'FILTER'>
FINAL = <TokenType.FINAL: 'FINAL'>
FIRST = <TokenType.FIRST: 'FIRST'>
FOR = <TokenType.FOR: 'FOR'>
FORCE = <TokenType.FORCE: 'FORCE'>
FOREIGN_KEY = <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>
FORMAT = <TokenType.FORMAT: 'FORMAT'>
FROM = <TokenType.FROM: 'FROM'>
FULL = <TokenType.FULL: 'FULL'>
FUNCTION = <TokenType.FUNCTION: 'FUNCTION'>
GLOB = <TokenType.GLOB: 'GLOB'>
GLOBAL = <TokenType.GLOBAL: 'GLOBAL'>
GROUP_BY = <TokenType.GROUP_BY: 'GROUP_BY'>
GROUPING_SETS = <TokenType.GROUPING_SETS: 'GROUPING_SETS'>
HAVING = <TokenType.HAVING: 'HAVING'>
HINT = <TokenType.HINT: 'HINT'>
IF = <TokenType.IF: 'IF'>
IGNORE = <TokenType.IGNORE: 'IGNORE'>
ILIKE = <TokenType.ILIKE: 'ILIKE'>
ILIKE_ANY = <TokenType.ILIKE_ANY: 'ILIKE_ANY'>
IN = <TokenType.IN: 'IN'>
INDEX = <TokenType.INDEX: 'INDEX'>
INNER = <TokenType.INNER: 'INNER'>
INSERT = <TokenType.INSERT: 'INSERT'>
INTERSECT = <TokenType.INTERSECT: 'INTERSECT'>
INTERVAL = <TokenType.INTERVAL: 'INTERVAL'>
INTO = <TokenType.INTO: 'INTO'>
INTRODUCER = <TokenType.INTRODUCER: 'INTRODUCER'>
IRLIKE = <TokenType.IRLIKE: 'IRLIKE'>
IS = <TokenType.IS: 'IS'>
ISNULL = <TokenType.ISNULL: 'ISNULL'>
JOIN = <TokenType.JOIN: 'JOIN'>
JOIN_MARKER = <TokenType.JOIN_MARKER: 'JOIN_MARKER'>
KEEP = <TokenType.KEEP: 'KEEP'>
LANGUAGE = <TokenType.LANGUAGE: 'LANGUAGE'>
LATERAL = <TokenType.LATERAL: 'LATERAL'>
LEFT = <TokenType.LEFT: 'LEFT'>
LIKE = <TokenType.LIKE: 'LIKE'>
LIKE_ANY = <TokenType.LIKE_ANY: 'LIKE_ANY'>
LIMIT = <TokenType.LIMIT: 'LIMIT'>
LOAD = <TokenType.LOAD: 'LOAD'>
LOCK = <TokenType.LOCK: 'LOCK'>
MAP = <TokenType.MAP: 'MAP'>
MATCH_RECOGNIZE = <TokenType.MATCH_RECOGNIZE: 'MATCH_RECOGNIZE'>
MEMBER_OF = <TokenType.MEMBER_OF: 'MEMBER_OF'>
MERGE = <TokenType.MERGE: 'MERGE'>
MOD = <TokenType.MOD: 'MOD'>
NATURAL = <TokenType.NATURAL: 'NATURAL'>
NEXT = <TokenType.NEXT: 'NEXT'>
NEXT_VALUE_FOR = <TokenType.NEXT_VALUE_FOR: 'NEXT_VALUE_FOR'>
NOTNULL = <TokenType.NOTNULL: 'NOTNULL'>
NULL = <TokenType.NULL: 'NULL'>
OFFSET = <TokenType.OFFSET: 'OFFSET'>
ON = <TokenType.ON: 'ON'>
ORDER_BY = <TokenType.ORDER_BY: 'ORDER_BY'>
ORDERED = <TokenType.ORDERED: 'ORDERED'>
ORDINALITY = <TokenType.ORDINALITY: 'ORDINALITY'>
OUTER = <TokenType.OUTER: 'OUTER'>
OVER = <TokenType.OVER: 'OVER'>
OVERLAPS = <TokenType.OVERLAPS: 'OVERLAPS'>
OVERWRITE = <TokenType.OVERWRITE: 'OVERWRITE'>
PARTITION = <TokenType.PARTITION: 'PARTITION'>
PARTITION_BY = <TokenType.PARTITION_BY: 'PARTITION_BY'>
PERCENT = <TokenType.PERCENT: 'PERCENT'>
PIVOT = <TokenType.PIVOT: 'PIVOT'>
PLACEHOLDER = <TokenType.PLACEHOLDER: 'PLACEHOLDER'>
PRAGMA = <TokenType.PRAGMA: 'PRAGMA'>
PRIMARY_KEY = <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>
PROCEDURE = <TokenType.PROCEDURE: 'PROCEDURE'>
PROPERTIES = <TokenType.PROPERTIES: 'PROPERTIES'>
PSEUDO_TYPE = <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>
QUALIFY = <TokenType.QUALIFY: 'QUALIFY'>
QUOTE = <TokenType.QUOTE: 'QUOTE'>
RANGE = <TokenType.RANGE: 'RANGE'>
RECURSIVE = <TokenType.RECURSIVE: 'RECURSIVE'>
REPLACE = <TokenType.REPLACE: 'REPLACE'>
RETURNING = <TokenType.RETURNING: 'RETURNING'>
REFERENCES = <TokenType.REFERENCES: 'REFERENCES'>
RIGHT = <TokenType.RIGHT: 'RIGHT'>
RLIKE = <TokenType.RLIKE: 'RLIKE'>
ROLLBACK = <TokenType.ROLLBACK: 'ROLLBACK'>
ROLLUP = <TokenType.ROLLUP: 'ROLLUP'>
ROW = <TokenType.ROW: 'ROW'>
ROWS = <TokenType.ROWS: 'ROWS'>
SELECT = <TokenType.SELECT: 'SELECT'>
SEMI = <TokenType.SEMI: 'SEMI'>
SEPARATOR = <TokenType.SEPARATOR: 'SEPARATOR'>
SERDE_PROPERTIES = <TokenType.SERDE_PROPERTIES: 'SERDE_PROPERTIES'>
SET = <TokenType.SET: 'SET'>
SETTINGS = <TokenType.SETTINGS: 'SETTINGS'>
SHOW = <TokenType.SHOW: 'SHOW'>
SIMILAR_TO = <TokenType.SIMILAR_TO: 'SIMILAR_TO'>
SOME = <TokenType.SOME: 'SOME'>
SORT_BY = <TokenType.SORT_BY: 'SORT_BY'>
STRUCT = <TokenType.STRUCT: 'STRUCT'>
TABLE_SAMPLE = <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>
TEMPORARY = <TokenType.TEMPORARY: 'TEMPORARY'>
TOP = <TokenType.TOP: 'TOP'>
THEN = <TokenType.THEN: 'THEN'>
TRUE = <TokenType.TRUE: 'TRUE'>
UNCACHE = <TokenType.UNCACHE: 'UNCACHE'>
UNION = <TokenType.UNION: 'UNION'>
UNNEST = <TokenType.UNNEST: 'UNNEST'>
UNPIVOT = <TokenType.UNPIVOT: 'UNPIVOT'>
UPDATE = <TokenType.UPDATE: 'UPDATE'>
USE = <TokenType.USE: 'USE'>
USING = <TokenType.USING: 'USING'>
VALUES = <TokenType.VALUES: 'VALUES'>
VIEW = <TokenType.VIEW: 'VIEW'>
VOLATILE = <TokenType.VOLATILE: 'VOLATILE'>
WHEN = <TokenType.WHEN: 'WHEN'>
WHERE = <TokenType.WHERE: 'WHERE'>
WINDOW = <TokenType.WINDOW: 'WINDOW'>
WITH = <TokenType.WITH: 'WITH'>
UNIQUE = <TokenType.UNIQUE: 'UNIQUE'>

##### Inherited Members

enum.Enum
  name
  value

class Token: View Source

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

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

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

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

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

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

     427class Tokenizer(metaclass=_Tokenizer):
     428    SINGLE_TOKENS = {
     429        "(": TokenType.L_PAREN,
     430        ")": TokenType.R_PAREN,
     431        "[": TokenType.L_BRACKET,
     432        "]": TokenType.R_BRACKET,
     433        "{": TokenType.L_BRACE,
     434        "}": TokenType.R_BRACE,
     435        "&": TokenType.AMP,
     436        "^": TokenType.CARET,
     437        ":": TokenType.COLON,
     438        ",": TokenType.COMMA,
     439        ".": TokenType.DOT,
     440        "-": TokenType.DASH,
     441        "=": TokenType.EQ,
     442        ">": TokenType.GT,
     443        "<": TokenType.LT,
     444        "%": TokenType.MOD,
     445        "!": TokenType.NOT,
     446        "|": TokenType.PIPE,
     447        "+": TokenType.PLUS,
     448        ";": TokenType.SEMICOLON,
     449        "/": TokenType.SLASH,
     450        "\\": TokenType.BACKSLASH,
     451        "*": TokenType.STAR,
     452        "~": TokenType.TILDA,
     453        "?": TokenType.PLACEHOLDER,
     454        "@": TokenType.PARAMETER,
     455        # used for breaking a var like x'y' but nothing else
     456        # the token type doesn't matter
     457        "'": TokenType.QUOTE,
     458        "`": TokenType.IDENTIFIER,
     459        '"': TokenType.IDENTIFIER,
     460        "#": TokenType.HASH,
     461    }
     462
     463    BIT_STRINGS: t.List[str | t.Tuple[str, str]] = []
     464    BYTE_STRINGS: t.List[str | t.Tuple[str, str]] = []
     465    HEX_STRINGS: t.List[str | t.Tuple[str, str]] = []
     466    RAW_STRINGS: t.List[str | t.Tuple[str, str]] = []
     467    IDENTIFIERS: t.List[str | t.Tuple[str, str]] = ['"']
     468    IDENTIFIER_ESCAPES = ['"']
     469    QUOTES: t.List[t.Tuple[str, str] | str] = ["'"]
     470    STRING_ESCAPES = ["'"]
     471    VAR_SINGLE_TOKENS: t.Set[str] = set()
     472
     473    # Autofilled
     474    IDENTIFIERS_CAN_START_WITH_DIGIT: bool = False
     475
     476    _COMMENTS: t.Dict[str, str] = {}
     477    _FORMAT_STRINGS: t.Dict[str, t.Tuple[str, TokenType]] = {}
     478    _IDENTIFIERS: t.Dict[str, str] = {}
     479    _IDENTIFIER_ESCAPES: t.Set[str] = set()
     480    _QUOTES: t.Dict[str, str] = {}
     481    _STRING_ESCAPES: t.Set[str] = set()
     482    _KEYWORD_TRIE: t.Dict = {}
     483
     484    KEYWORDS: t.Dict[str, TokenType] = {
     485        **{f"{{%{postfix}": TokenType.BLOCK_START for postfix in ("", "+", "-")},
     486        **{f"{prefix}%}}": TokenType.BLOCK_END for prefix in ("", "+", "-")},
     487        **{f"{{{{{postfix}": TokenType.BLOCK_START for postfix in ("+", "-")},
     488        **{f"{prefix}}}}}": TokenType.BLOCK_END for prefix in ("+", "-")},
     489        "/*+": TokenType.HINT,
     490        "==": TokenType.EQ,
     491        "::": TokenType.DCOLON,
     492        "||": TokenType.DPIPE,
     493        ">=": TokenType.GTE,
     494        "<=": TokenType.LTE,
     495        "<>": TokenType.NEQ,
     496        "!=": TokenType.NEQ,
     497        "<=>": TokenType.NULLSAFE_EQ,
     498        "->": TokenType.ARROW,
     499        "->>": TokenType.DARROW,
     500        "=>": TokenType.FARROW,
     501        "#>": TokenType.HASH_ARROW,
     502        "#>>": TokenType.DHASH_ARROW,
     503        "<->": TokenType.LR_ARROW,
     504        "&&": TokenType.DAMP,
     505        "ALL": TokenType.ALL,
     506        "ALWAYS": TokenType.ALWAYS,
     507        "AND": TokenType.AND,
     508        "ANTI": TokenType.ANTI,
     509        "ANY": TokenType.ANY,
     510        "ASC": TokenType.ASC,
     511        "AS": TokenType.ALIAS,
     512        "ASOF": TokenType.ASOF,
     513        "AUTOINCREMENT": TokenType.AUTO_INCREMENT,
     514        "AUTO_INCREMENT": TokenType.AUTO_INCREMENT,
     515        "BEGIN": TokenType.BEGIN,
     516        "BETWEEN": TokenType.BETWEEN,
     517        "CACHE": TokenType.CACHE,
     518        "UNCACHE": TokenType.UNCACHE,
     519        "CASE": TokenType.CASE,
     520        "CHARACTER SET": TokenType.CHARACTER_SET,
     521        "CLUSTER BY": TokenType.CLUSTER_BY,
     522        "COLLATE": TokenType.COLLATE,
     523        "COLUMN": TokenType.COLUMN,
     524        "COMMIT": TokenType.COMMIT,
     525        "CONSTRAINT": TokenType.CONSTRAINT,
     526        "CREATE": TokenType.CREATE,
     527        "CROSS": TokenType.CROSS,
     528        "CUBE": TokenType.CUBE,
     529        "CURRENT_DATE": TokenType.CURRENT_DATE,
     530        "CURRENT_TIME": TokenType.CURRENT_TIME,
     531        "CURRENT_TIMESTAMP": TokenType.CURRENT_TIMESTAMP,
     532        "CURRENT_USER": TokenType.CURRENT_USER,
     533        "DATABASE": TokenType.DATABASE,
     534        "DEFAULT": TokenType.DEFAULT,
     535        "DELETE": TokenType.DELETE,
     536        "DESC": TokenType.DESC,
     537        "DESCRIBE": TokenType.DESCRIBE,
     538        "DISTINCT": TokenType.DISTINCT,
     539        "DISTRIBUTE BY": TokenType.DISTRIBUTE_BY,
     540        "DIV": TokenType.DIV,
     541        "DROP": TokenType.DROP,
     542        "ELSE": TokenType.ELSE,
     543        "END": TokenType.END,
     544        "ESCAPE": TokenType.ESCAPE,
     545        "EXCEPT": TokenType.EXCEPT,
     546        "EXECUTE": TokenType.EXECUTE,
     547        "EXISTS": TokenType.EXISTS,
     548        "FALSE": TokenType.FALSE,
     549        "FETCH": TokenType.FETCH,
     550        "FILTER": TokenType.FILTER,
     551        "FIRST": TokenType.FIRST,
     552        "FULL": TokenType.FULL,
     553        "FUNCTION": TokenType.FUNCTION,
     554        "FOR": TokenType.FOR,
     555        "FOREIGN KEY": TokenType.FOREIGN_KEY,
     556        "FORMAT": TokenType.FORMAT,
     557        "FROM": TokenType.FROM,
     558        "GEOGRAPHY": TokenType.GEOGRAPHY,
     559        "GEOMETRY": TokenType.GEOMETRY,
     560        "GLOB": TokenType.GLOB,
     561        "GROUP BY": TokenType.GROUP_BY,
     562        "GROUPING SETS": TokenType.GROUPING_SETS,
     563        "HAVING": TokenType.HAVING,
     564        "IF": TokenType.IF,
     565        "ILIKE": TokenType.ILIKE,
     566        "IN": TokenType.IN,
     567        "INDEX": TokenType.INDEX,
     568        "INET": TokenType.INET,
     569        "INNER": TokenType.INNER,
     570        "INSERT": TokenType.INSERT,
     571        "INTERVAL": TokenType.INTERVAL,
     572        "INTERSECT": TokenType.INTERSECT,
     573        "INTO": TokenType.INTO,
     574        "IS": TokenType.IS,
     575        "ISNULL": TokenType.ISNULL,
     576        "JOIN": TokenType.JOIN,
     577        "KEEP": TokenType.KEEP,
     578        "LATERAL": TokenType.LATERAL,
     579        "LEFT": TokenType.LEFT,
     580        "LIKE": TokenType.LIKE,
     581        "LIMIT": TokenType.LIMIT,
     582        "LOAD": TokenType.LOAD,
     583        "LOCK": TokenType.LOCK,
     584        "MERGE": TokenType.MERGE,
     585        "NATURAL": TokenType.NATURAL,
     586        "NEXT": TokenType.NEXT,
     587        "NEXT VALUE FOR": TokenType.NEXT_VALUE_FOR,
     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 ValueError(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 RuntimeError(
    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 RuntimeError(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 RuntimeError(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

SINGLE_TOKENS = {'(': <TokenType.L_PAREN: 'L_PAREN'>, ')': <TokenType.R_PAREN: 'R_PAREN'>, '[': <TokenType.L_BRACKET: 'L_BRACKET'>, ']': <TokenType.R_BRACKET: 'R_BRACKET'>, '{': <TokenType.L_BRACE: 'L_BRACE'>, '}': <TokenType.R_BRACE: 'R_BRACE'>, '&': <TokenType.AMP: 'AMP'>, '^': <TokenType.CARET: 'CARET'>, ':': <TokenType.COLON: 'COLON'>, ',': <TokenType.COMMA: 'COMMA'>, '.': <TokenType.DOT: 'DOT'>, '-': <TokenType.DASH: 'DASH'>, '=': <TokenType.EQ: 'EQ'>, '>': <TokenType.GT: 'GT'>, '<': <TokenType.LT: 'LT'>, '%': <TokenType.MOD: 'MOD'>, '!': <TokenType.NOT: 'NOT'>, '|': <TokenType.PIPE: 'PIPE'>, '+': <TokenType.PLUS: 'PLUS'>, ';': <TokenType.SEMICOLON: 'SEMICOLON'>, '/': <TokenType.SLASH: 'SLASH'>, '\\': <TokenType.BACKSLASH: 'BACKSLASH'>, '*': <TokenType.STAR: 'STAR'>, '~': <TokenType.TILDA: 'TILDA'>, '?': <TokenType.PLACEHOLDER: 'PLACEHOLDER'>, '@': <TokenType.PARAMETER: 'PARAMETER'>, "'": <TokenType.QUOTE: 'QUOTE'>, '`': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '"': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '#': <TokenType.HASH: 'HASH'>}
BIT_STRINGS: List[Union[str, Tuple[str, str]]] = []
BYTE_STRINGS: List[Union[str, Tuple[str, str]]] = []
HEX_STRINGS: List[Union[str, Tuple[str, str]]] = []
RAW_STRINGS: List[Union[str, Tuple[str, str]]] = []
IDENTIFIERS: List[Union[str, Tuple[str, str]]] = ['"']
IDENTIFIER_ESCAPES = ['"']
QUOTES: List[Union[str, Tuple[str, str]]] = ["'"]
STRING_ESCAPES = ["'"]
VAR_SINGLE_TOKENS: Set[str] = set()
IDENTIFIERS_CAN_START_WITH_DIGIT: bool = False
KEYWORDS: Dict[str, sqlglot.tokens.TokenType] = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'IF': <TokenType.IF: 'IF'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NEXT VALUE FOR': <TokenType.NEXT_VALUE_FOR: 'NEXT_VALUE_FOR'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.BIGINT: 'BIGINT'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'COPY': <TokenType.COMMAND: 'COMMAND'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'TRUNCATE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>}
WHITE_SPACE: Dict[Optional[str], sqlglot.tokens.TokenType] = {' ': <TokenType.SPACE: 'SPACE'>, '\t': <TokenType.SPACE: 'SPACE'>, '\n': <TokenType.BREAK: 'BREAK'>, '\r': <TokenType.BREAK: 'BREAK'>, '\r\n': <TokenType.BREAK: 'BREAK'>}
COMMANDS = {<TokenType.EXECUTE: 'EXECUTE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.SHOW: 'SHOW'>, <TokenType.FETCH: 'FETCH'>}
COMMAND_PREFIX_TOKENS = {<TokenType.BEGIN: 'BEGIN'>, <TokenType.SEMICOLON: 'SEMICOLON'>}
NUMERIC_LITERALS: Dict[str, str] = {}
ENCODE: Optional[str] = None
COMMENTS = ['--', ('/*', '*/')]
def reset(self) -> None: View Source

    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

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

    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 ValueError(f"Error tokenizing '{context}'") from e
    805
    806        return self.tokens

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

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

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

size
sql
tokens