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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    914    def peek(self, i: int = 0) -> str:
    915        i = self._current + i
    916        if i < self.size:
    917            return self.sql[i]
    918        return ""

size
sql
tokens