sqlglot.tokens API documentation

Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

An enumeration.

L_PAREN = <TokenType.L_PAREN: 'L_PAREN'>
R_PAREN = <TokenType.R_PAREN: 'R_PAREN'>
L_BRACKET = <TokenType.L_BRACKET: 'L_BRACKET'>
R_BRACKET = <TokenType.R_BRACKET: 'R_BRACKET'>
L_BRACE = <TokenType.L_BRACE: 'L_BRACE'>
R_BRACE = <TokenType.R_BRACE: 'R_BRACE'>
COMMA = <TokenType.COMMA: 'COMMA'>
DOT = <TokenType.DOT: 'DOT'>
DASH = <TokenType.DASH: 'DASH'>
PLUS = <TokenType.PLUS: 'PLUS'>
COLON = <TokenType.COLON: 'COLON'>
DCOLON = <TokenType.DCOLON: 'DCOLON'>
DQMARK = <TokenType.DQMARK: 'DQMARK'>
SEMICOLON = <TokenType.SEMICOLON: 'SEMICOLON'>
STAR = <TokenType.STAR: 'STAR'>
BACKSLASH = <TokenType.BACKSLASH: 'BACKSLASH'>
SLASH = <TokenType.SLASH: 'SLASH'>
LT = <TokenType.LT: 'LT'>
LTE = <TokenType.LTE: 'LTE'>
GT = <TokenType.GT: 'GT'>
GTE = <TokenType.GTE: 'GTE'>
NOT = <TokenType.NOT: 'NOT'>
EQ = <TokenType.EQ: 'EQ'>
NEQ = <TokenType.NEQ: 'NEQ'>
NULLSAFE_EQ = <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>
AND = <TokenType.AND: 'AND'>
OR = <TokenType.OR: 'OR'>
AMP = <TokenType.AMP: 'AMP'>
DPIPE = <TokenType.DPIPE: 'DPIPE'>
PIPE = <TokenType.PIPE: 'PIPE'>
CARET = <TokenType.CARET: 'CARET'>
TILDA = <TokenType.TILDA: 'TILDA'>
ARROW = <TokenType.ARROW: 'ARROW'>
DARROW = <TokenType.DARROW: 'DARROW'>
FARROW = <TokenType.FARROW: 'FARROW'>
HASH = <TokenType.HASH: 'HASH'>
HASH_ARROW = <TokenType.HASH_ARROW: 'HASH_ARROW'>
DHASH_ARROW = <TokenType.DHASH_ARROW: 'DHASH_ARROW'>
LR_ARROW = <TokenType.LR_ARROW: 'LR_ARROW'>
DAT = <TokenType.DAT: 'DAT'>
LT_AT = <TokenType.LT_AT: 'LT_AT'>
AT_GT = <TokenType.AT_GT: 'AT_GT'>
DOLLAR = <TokenType.DOLLAR: 'DOLLAR'>
PARAMETER = <TokenType.PARAMETER: 'PARAMETER'>
SESSION_PARAMETER = <TokenType.SESSION_PARAMETER: 'SESSION_PARAMETER'>
DAMP = <TokenType.DAMP: 'DAMP'>
XOR = <TokenType.XOR: 'XOR'>
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'>
MEDIUMINT = <TokenType.MEDIUMINT: 'MEDIUMINT'>
UMEDIUMINT = <TokenType.UMEDIUMINT: 'UMEDIUMINT'>
INT = <TokenType.INT: 'INT'>
UINT = <TokenType.UINT: 'UINT'>
BIGINT = <TokenType.BIGINT: 'BIGINT'>
UBIGINT = <TokenType.UBIGINT: 'UBIGINT'>
INT128 = <TokenType.INT128: 'INT128'>
UINT128 = <TokenType.UINT128: 'UINT128'>
INT256 = <TokenType.INT256: 'INT256'>
UINT256 = <TokenType.UINT256: 'UINT256'>
FLOAT = <TokenType.FLOAT: 'FLOAT'>
DOUBLE = <TokenType.DOUBLE: 'DOUBLE'>
DECIMAL = <TokenType.DECIMAL: 'DECIMAL'>
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'>
TINYBLOB = <TokenType.TINYBLOB: 'TINYBLOB'>
TINYTEXT = <TokenType.TINYTEXT: 'TINYTEXT'>
BINARY = <TokenType.BINARY: 'BINARY'>
VARBINARY = <TokenType.VARBINARY: 'VARBINARY'>
JSON = <TokenType.JSON: 'JSON'>
JSONB = <TokenType.JSONB: 'JSONB'>
TIME = <TokenType.TIME: 'TIME'>
TIMETZ = <TokenType.TIMETZ: 'TIMETZ'>
TIMESTAMP = <TokenType.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
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'>
YEAR = <TokenType.YEAR: 'YEAR'>
UNIQUEIDENTIFIER = <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
USERDEFINED = <TokenType.USERDEFINED: 'USERDEFINED'>
MONEY = <TokenType.MONEY: 'MONEY'>
SMALLMONEY = <TokenType.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <TokenType.ROWVERSION: 'ROWVERSION'>
IMAGE = <TokenType.IMAGE: 'IMAGE'>
VARIANT = <TokenType.VARIANT: 'VARIANT'>
OBJECT = <TokenType.OBJECT: 'OBJECT'>
INET = <TokenType.INET: 'INET'>
IPADDRESS = <TokenType.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <TokenType.IPPREFIX: 'IPPREFIX'>
ENUM = <TokenType.ENUM: 'ENUM'>
ENUM8 = <TokenType.ENUM8: 'ENUM8'>
ENUM16 = <TokenType.ENUM16: 'ENUM16'>
FIXEDSTRING = <TokenType.FIXEDSTRING: 'FIXEDSTRING'>
LOWCARDINALITY = <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>
NESTED = <TokenType.NESTED: 'NESTED'>
UNKNOWN = <TokenType.UNKNOWN: 'UNKNOWN'>
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'>
CONNECT_BY = <TokenType.CONNECT_BY: 'CONNECT_BY'>
CONSTRAINT = <TokenType.CONSTRAINT: 'CONSTRAINT'>
CREATE = <TokenType.CREATE: 'CREATE'>
CROSS = <TokenType.CROSS: 'CROSS'>
CUBE = <TokenType.CUBE: 'CUBE'>
CURRENT_DATE = <TokenType.CURRENT_DATE: 'CURRENT_DATE'>
CURRENT_DATETIME = <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>
CURRENT_TIME = <TokenType.CURRENT_TIME: 'CURRENT_TIME'>
CURRENT_TIMESTAMP = <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>
CURRENT_USER = <TokenType.CURRENT_USER: 'CURRENT_USER'>
DEFAULT = <TokenType.DEFAULT: 'DEFAULT'>
DELETE = <TokenType.DELETE: 'DELETE'>
DESC = <TokenType.DESC: 'DESC'>
DESCRIBE = <TokenType.DESCRIBE: 'DESCRIBE'>
DICTIONARY = <TokenType.DICTIONARY: 'DICTIONARY'>
DISTINCT = <TokenType.DISTINCT: 'DISTINCT'>
DISTRIBUTE_BY = <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>
DIV = <TokenType.DIV: 'DIV'>
DROP = <TokenType.DROP: 'DROP'>
ELSE = <TokenType.ELSE: 'ELSE'>
END = <TokenType.END: 'END'>
ESCAPE = <TokenType.ESCAPE: 'ESCAPE'>
EXCEPT = <TokenType.EXCEPT: 'EXCEPT'>
EXECUTE = <TokenType.EXECUTE: 'EXECUTE'>
EXISTS = <TokenType.EXISTS: 'EXISTS'>
FALSE = <TokenType.FALSE: 'FALSE'>
FETCH = <TokenType.FETCH: 'FETCH'>
FILTER = <TokenType.FILTER: 'FILTER'>
FINAL = <TokenType.FINAL: 'FINAL'>
FIRST = <TokenType.FIRST: 'FIRST'>
FOR = <TokenType.FOR: 'FOR'>
FORCE = <TokenType.FORCE: 'FORCE'>
FOREIGN_KEY = <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>
FORMAT = <TokenType.FORMAT: 'FORMAT'>
FROM = <TokenType.FROM: 'FROM'>
FULL = <TokenType.FULL: 'FULL'>
FUNCTION = <TokenType.FUNCTION: 'FUNCTION'>
GLOB = <TokenType.GLOB: 'GLOB'>
GLOBAL = <TokenType.GLOBAL: 'GLOBAL'>
GROUP_BY = <TokenType.GROUP_BY: 'GROUP_BY'>
GROUPING_SETS = <TokenType.GROUPING_SETS: 'GROUPING_SETS'>
HAVING = <TokenType.HAVING: 'HAVING'>
HINT = <TokenType.HINT: 'HINT'>
IGNORE = <TokenType.IGNORE: 'IGNORE'>
ILIKE = <TokenType.ILIKE: 'ILIKE'>
ILIKE_ANY = <TokenType.ILIKE_ANY: 'ILIKE_ANY'>
IN = <TokenType.IN: 'IN'>
INDEX = <TokenType.INDEX: 'INDEX'>
INNER = <TokenType.INNER: 'INNER'>
INSERT = <TokenType.INSERT: 'INSERT'>
INTERSECT = <TokenType.INTERSECT: 'INTERSECT'>
INTERVAL = <TokenType.INTERVAL: 'INTERVAL'>
INTO = <TokenType.INTO: 'INTO'>
INTRODUCER = <TokenType.INTRODUCER: 'INTRODUCER'>
IRLIKE = <TokenType.IRLIKE: 'IRLIKE'>
IS = <TokenType.IS: 'IS'>
ISNULL = <TokenType.ISNULL: 'ISNULL'>
JOIN = <TokenType.JOIN: 'JOIN'>
JOIN_MARKER = <TokenType.JOIN_MARKER: 'JOIN_MARKER'>
KEEP = <TokenType.KEEP: 'KEEP'>
LANGUAGE = <TokenType.LANGUAGE: 'LANGUAGE'>
LATERAL = <TokenType.LATERAL: 'LATERAL'>
LEFT = <TokenType.LEFT: 'LEFT'>
LIKE = <TokenType.LIKE: 'LIKE'>
LIKE_ANY = <TokenType.LIKE_ANY: 'LIKE_ANY'>
LIMIT = <TokenType.LIMIT: 'LIMIT'>
LOAD = <TokenType.LOAD: 'LOAD'>
LOCK = <TokenType.LOCK: 'LOCK'>
MAP = <TokenType.MAP: 'MAP'>
MATCH_RECOGNIZE = <TokenType.MATCH_RECOGNIZE: 'MATCH_RECOGNIZE'>
MEMBER_OF = <TokenType.MEMBER_OF: 'MEMBER_OF'>
MERGE = <TokenType.MERGE: 'MERGE'>
MOD = <TokenType.MOD: 'MOD'>
NATURAL = <TokenType.NATURAL: 'NATURAL'>
NEXT = <TokenType.NEXT: 'NEXT'>
NOTNULL = <TokenType.NOTNULL: 'NOTNULL'>
NULL = <TokenType.NULL: 'NULL'>
OBJECT_IDENTIFIER = <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>
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'>
START_WITH = <TokenType.START_WITH: 'START_WITH'>
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'>
VERSION_SNAPSHOT = <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>
TIMESTAMP_SNAPSHOT = <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>

##### Inherited Members

enum.Enum
  name
  value

class Token: View Source

    337class Token:
    338    __slots__ = ("token_type", "text", "line", "col", "start", "end", "comments")
    339
    340    @classmethod
    341    def number(cls, number: int) -> Token:
    342        """Returns a NUMBER token with `number` as its text."""
    343        return cls(TokenType.NUMBER, str(number))
    344
    345    @classmethod
    346    def string(cls, string: str) -> Token:
    347        """Returns a STRING token with `string` as its text."""
    348        return cls(TokenType.STRING, string)
    349
    350    @classmethod
    351    def identifier(cls, identifier: str) -> Token:
    352        """Returns an IDENTIFIER token with `identifier` as its text."""
    353        return cls(TokenType.IDENTIFIER, identifier)
    354
    355    @classmethod
    356    def var(cls, var: str) -> Token:
    357        """Returns an VAR token with `var` as its text."""
    358        return cls(TokenType.VAR, var)
    359
    360    def __init__(
    361        self,
    362        token_type: TokenType,
    363        text: str,
    364        line: int = 1,
    365        col: int = 1,
    366        start: int = 0,
    367        end: int = 0,
    368        comments: t.List[str] = [],
    369    ) -> None:
    370        """Token initializer.
    371
    372        Args:
    373            token_type: The TokenType Enum.
    374            text: The text of the token.
    375            line: The line that the token ends on.
    376            col: The column that the token ends on.
    377            start: The start index of the token.
    378            end: The ending index of the token.
    379            comments: The comments to attach to the token.
    380        """
    381        self.token_type = token_type
    382        self.text = text
    383        self.line = line
    384        self.col = col
    385        self.start = start
    386        self.end = end
    387        self.comments = comments
    388
    389    def __repr__(self) -> str:
    390        attributes = ", ".join(f"{k}: {getattr(self, k)}" for k in self.__slots__)
    391        return f"<Token {attributes}>"

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

    360    def __init__(
    361        self,
    362        token_type: TokenType,
    363        text: str,
    364        line: int = 1,
    365        col: int = 1,
    366        start: int = 0,
    367        end: int = 0,
    368        comments: t.List[str] = [],
    369    ) -> None:
    370        """Token initializer.
    371
    372        Args:
    373            token_type: The TokenType Enum.
    374            text: The text of the token.
    375            line: The line that the token ends on.
    376            col: The column that the token ends on.
    377            start: The start index of the token.
    378            end: The ending index of the token.
    379            comments: The comments to attach to the token.
    380        """
    381        self.token_type = token_type
    382        self.text = text
    383        self.line = line
    384        self.col = col
    385        self.start = start
    386        self.end = end
    387        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) -> Token: View Source

    340    @classmethod
    341    def number(cls, number: int) -> Token:
    342        """Returns a NUMBER token with `number` as its text."""
    343        return cls(TokenType.NUMBER, str(number))

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

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

    345    @classmethod
    346    def string(cls, string: str) -> Token:
    347        """Returns a STRING token with `string` as its text."""
    348        return cls(TokenType.STRING, string)

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

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

    350    @classmethod
    351    def identifier(cls, identifier: str) -> Token:
    352        """Returns an IDENTIFIER token with `identifier` as its text."""
    353        return cls(TokenType.IDENTIFIER, identifier)

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

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

    355    @classmethod
    356    def var(cls, var: str) -> Token:
    357        """Returns an VAR token with `var` as its text."""
    358        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

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

    810    def reset(self) -> None:
    811        self.sql = ""
    812        self.size = 0
    813        self.tokens: t.List[Token] = []
    814        self._start = 0
    815        self._current = 0
    816        self._line = 1
    817        self._col = 0
    818        self._comments: t.List[str] = []
    819
    820        self._char = ""
    821        self._end = False
    822        self._peek = ""
    823        self._prev_token_line = -1

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

    825    def tokenize(self, sql: str) -> t.List[Token]:
    826        """Returns a list of tokens corresponding to the SQL string `sql`."""
    827        self.reset()
    828        self.sql = sql
    829        self.size = len(sql)
    830
    831        try:
    832            self._scan()
    833        except Exception as e:
    834            start = max(self._current - 50, 0)
    835            end = min(self._current + 50, self.size - 1)
    836            context = self.sql[start:end]
    837            raise TokenError(f"Error tokenizing '{context}'") from e
    838
    839        return self.tokens

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

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

    907    def peek(self, i: int = 0) -> str:
    908        i = self._current + i
    909        if i < self.size:
    910            return self.sql[i]
    911        return ""

size
sql
tokens