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

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

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

    347    @classmethod
    348    def number(cls, number: int) -> Token:
    349        """Returns a NUMBER token with `number` as its text."""
    350        return cls(TokenType.NUMBER, str(number))

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

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

    352    @classmethod
    353    def string(cls, string: str) -> Token:
    354        """Returns a STRING token with `string` as its text."""
    355        return cls(TokenType.STRING, string)

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

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

    357    @classmethod
    358    def identifier(cls, identifier: str) -> Token:
    359        """Returns an IDENTIFIER token with `identifier` as its text."""
    360        return cls(TokenType.IDENTIFIER, identifier)

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

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

    362    @classmethod
    363    def var(cls, var: str) -> Token:
    364        """Returns an VAR token with `var` as its text."""
    365        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

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

    821    def reset(self) -> None:
    822        self.sql = ""
    823        self.size = 0
    824        self.tokens: t.List[Token] = []
    825        self._start = 0
    826        self._current = 0
    827        self._line = 1
    828        self._col = 0
    829        self._comments: t.List[str] = []
    830
    831        self._char = ""
    832        self._end = False
    833        self._peek = ""
    834        self._prev_token_line = -1

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

    836    def tokenize(self, sql: str) -> t.List[Token]:
    837        """Returns a list of tokens corresponding to the SQL string `sql`."""
    838        self.reset()
    839        self.sql = sql
    840        self.size = len(sql)
    841
    842        try:
    843            self._scan()
    844        except Exception as e:
    845            start = max(self._current - 50, 0)
    846            end = min(self._current + 50, self.size - 1)
    847            context = self.sql[start:end]
    848            raise TokenError(f"Error tokenizing '{context}'") from e
    849
    850        return self.tokens

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

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

    918    def peek(self, i: int = 0) -> str:
    919        i = self._current + i
    920        if i < self.size:
    921            return self.sql[i]
    922        return ""

size
sql
tokens