sqlglot.tokens API documentation

Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

An enumeration.

L_PAREN = <TokenType.L_PAREN: 'L_PAREN'>
R_PAREN = <TokenType.R_PAREN: 'R_PAREN'>
L_BRACKET = <TokenType.L_BRACKET: 'L_BRACKET'>
R_BRACKET = <TokenType.R_BRACKET: 'R_BRACKET'>
L_BRACE = <TokenType.L_BRACE: 'L_BRACE'>
R_BRACE = <TokenType.R_BRACE: 'R_BRACE'>
COMMA = <TokenType.COMMA: 'COMMA'>
DOT = <TokenType.DOT: 'DOT'>
DASH = <TokenType.DASH: 'DASH'>
PLUS = <TokenType.PLUS: 'PLUS'>
COLON = <TokenType.COLON: 'COLON'>
DCOLON = <TokenType.DCOLON: 'DCOLON'>
DQMARK = <TokenType.DQMARK: 'DQMARK'>
SEMICOLON = <TokenType.SEMICOLON: 'SEMICOLON'>
STAR = <TokenType.STAR: 'STAR'>
BACKSLASH = <TokenType.BACKSLASH: 'BACKSLASH'>
SLASH = <TokenType.SLASH: 'SLASH'>
LT = <TokenType.LT: 'LT'>
LTE = <TokenType.LTE: 'LTE'>
GT = <TokenType.GT: 'GT'>
GTE = <TokenType.GTE: 'GTE'>
NOT = <TokenType.NOT: 'NOT'>
EQ = <TokenType.EQ: 'EQ'>
NEQ = <TokenType.NEQ: 'NEQ'>
NULLSAFE_EQ = <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>
AND = <TokenType.AND: 'AND'>
OR = <TokenType.OR: 'OR'>
AMP = <TokenType.AMP: 'AMP'>
DPIPE = <TokenType.DPIPE: 'DPIPE'>
PIPE = <TokenType.PIPE: 'PIPE'>
CARET = <TokenType.CARET: 'CARET'>
TILDA = <TokenType.TILDA: 'TILDA'>
ARROW = <TokenType.ARROW: 'ARROW'>
DARROW = <TokenType.DARROW: 'DARROW'>
FARROW = <TokenType.FARROW: 'FARROW'>
HASH = <TokenType.HASH: 'HASH'>
HASH_ARROW = <TokenType.HASH_ARROW: 'HASH_ARROW'>
DHASH_ARROW = <TokenType.DHASH_ARROW: 'DHASH_ARROW'>
LR_ARROW = <TokenType.LR_ARROW: 'LR_ARROW'>
DAT = <TokenType.DAT: 'DAT'>
LT_AT = <TokenType.LT_AT: 'LT_AT'>
AT_GT = <TokenType.AT_GT: 'AT_GT'>
DOLLAR = <TokenType.DOLLAR: 'DOLLAR'>
PARAMETER = <TokenType.PARAMETER: 'PARAMETER'>
SESSION_PARAMETER = <TokenType.SESSION_PARAMETER: 'SESSION_PARAMETER'>
DAMP = <TokenType.DAMP: 'DAMP'>
XOR = <TokenType.XOR: 'XOR'>
BLOCK_START = <TokenType.BLOCK_START: 'BLOCK_START'>
BLOCK_END = <TokenType.BLOCK_END: 'BLOCK_END'>
SPACE = <TokenType.SPACE: 'SPACE'>
BREAK = <TokenType.BREAK: 'BREAK'>
STRING = <TokenType.STRING: 'STRING'>
NUMBER = <TokenType.NUMBER: 'NUMBER'>
IDENTIFIER = <TokenType.IDENTIFIER: 'IDENTIFIER'>
DATABASE = <TokenType.DATABASE: 'DATABASE'>
COLUMN = <TokenType.COLUMN: 'COLUMN'>
COLUMN_DEF = <TokenType.COLUMN_DEF: 'COLUMN_DEF'>
SCHEMA = <TokenType.SCHEMA: 'SCHEMA'>
TABLE = <TokenType.TABLE: 'TABLE'>
VAR = <TokenType.VAR: 'VAR'>
BIT_STRING = <TokenType.BIT_STRING: 'BIT_STRING'>
HEX_STRING = <TokenType.HEX_STRING: 'HEX_STRING'>
BYTE_STRING = <TokenType.BYTE_STRING: 'BYTE_STRING'>
NATIONAL_STRING = <TokenType.NATIONAL_STRING: 'NATIONAL_STRING'>
RAW_STRING = <TokenType.RAW_STRING: 'RAW_STRING'>
BIT = <TokenType.BIT: 'BIT'>
BOOLEAN = <TokenType.BOOLEAN: 'BOOLEAN'>
TINYINT = <TokenType.TINYINT: 'TINYINT'>
UTINYINT = <TokenType.UTINYINT: 'UTINYINT'>
SMALLINT = <TokenType.SMALLINT: 'SMALLINT'>
USMALLINT = <TokenType.USMALLINT: 'USMALLINT'>
MEDIUMINT = <TokenType.MEDIUMINT: 'MEDIUMINT'>
UMEDIUMINT = <TokenType.UMEDIUMINT: 'UMEDIUMINT'>
INT = <TokenType.INT: 'INT'>
UINT = <TokenType.UINT: 'UINT'>
BIGINT = <TokenType.BIGINT: 'BIGINT'>
UBIGINT = <TokenType.UBIGINT: 'UBIGINT'>
INT128 = <TokenType.INT128: 'INT128'>
UINT128 = <TokenType.UINT128: 'UINT128'>
INT256 = <TokenType.INT256: 'INT256'>
UINT256 = <TokenType.UINT256: 'UINT256'>
FLOAT = <TokenType.FLOAT: 'FLOAT'>
DOUBLE = <TokenType.DOUBLE: 'DOUBLE'>
DECIMAL = <TokenType.DECIMAL: 'DECIMAL'>
BIGDECIMAL = <TokenType.BIGDECIMAL: 'BIGDECIMAL'>
CHAR = <TokenType.CHAR: 'CHAR'>
NCHAR = <TokenType.NCHAR: 'NCHAR'>
VARCHAR = <TokenType.VARCHAR: 'VARCHAR'>
NVARCHAR = <TokenType.NVARCHAR: 'NVARCHAR'>
TEXT = <TokenType.TEXT: 'TEXT'>
MEDIUMTEXT = <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <TokenType.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <TokenType.LONGBLOB: 'LONGBLOB'>
TINYBLOB = <TokenType.TINYBLOB: 'TINYBLOB'>
TINYTEXT = <TokenType.TINYTEXT: 'TINYTEXT'>
BINARY = <TokenType.BINARY: 'BINARY'>
VARBINARY = <TokenType.VARBINARY: 'VARBINARY'>
JSON = <TokenType.JSON: 'JSON'>
JSONB = <TokenType.JSONB: 'JSONB'>
TIME = <TokenType.TIME: 'TIME'>
TIMETZ = <TokenType.TIMETZ: 'TIMETZ'>
TIMESTAMP = <TokenType.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
DATETIME = <TokenType.DATETIME: 'DATETIME'>
DATETIME64 = <TokenType.DATETIME64: 'DATETIME64'>
DATE = <TokenType.DATE: 'DATE'>
INT4RANGE = <TokenType.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <TokenType.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <TokenType.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <TokenType.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <TokenType.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <TokenType.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>
UUID = <TokenType.UUID: 'UUID'>
GEOGRAPHY = <TokenType.GEOGRAPHY: 'GEOGRAPHY'>
NULLABLE = <TokenType.NULLABLE: 'NULLABLE'>
GEOMETRY = <TokenType.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <TokenType.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <TokenType.HSTORE: 'HSTORE'>
SUPER = <TokenType.SUPER: 'SUPER'>
SERIAL = <TokenType.SERIAL: 'SERIAL'>
SMALLSERIAL = <TokenType.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <TokenType.BIGSERIAL: 'BIGSERIAL'>
XML = <TokenType.XML: 'XML'>
YEAR = <TokenType.YEAR: 'YEAR'>
UNIQUEIDENTIFIER = <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
USERDEFINED = <TokenType.USERDEFINED: 'USERDEFINED'>
MONEY = <TokenType.MONEY: 'MONEY'>
SMALLMONEY = <TokenType.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <TokenType.ROWVERSION: 'ROWVERSION'>
IMAGE = <TokenType.IMAGE: 'IMAGE'>
VARIANT = <TokenType.VARIANT: 'VARIANT'>
OBJECT = <TokenType.OBJECT: 'OBJECT'>
INET = <TokenType.INET: 'INET'>
IPADDRESS = <TokenType.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <TokenType.IPPREFIX: 'IPPREFIX'>
ENUM = <TokenType.ENUM: 'ENUM'>
ENUM8 = <TokenType.ENUM8: 'ENUM8'>
ENUM16 = <TokenType.ENUM16: 'ENUM16'>
FIXEDSTRING = <TokenType.FIXEDSTRING: 'FIXEDSTRING'>
LOWCARDINALITY = <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>
NESTED = <TokenType.NESTED: 'NESTED'>
UNKNOWN = <TokenType.UNKNOWN: 'UNKNOWN'>
ALIAS = <TokenType.ALIAS: 'ALIAS'>
ALTER = <TokenType.ALTER: 'ALTER'>
ALWAYS = <TokenType.ALWAYS: 'ALWAYS'>
ALL = <TokenType.ALL: 'ALL'>
ANTI = <TokenType.ANTI: 'ANTI'>
ANY = <TokenType.ANY: 'ANY'>
APPLY = <TokenType.APPLY: 'APPLY'>
ARRAY = <TokenType.ARRAY: 'ARRAY'>
ASC = <TokenType.ASC: 'ASC'>
ASOF = <TokenType.ASOF: 'ASOF'>
AUTO_INCREMENT = <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>
BEGIN = <TokenType.BEGIN: 'BEGIN'>
BETWEEN = <TokenType.BETWEEN: 'BETWEEN'>
CACHE = <TokenType.CACHE: 'CACHE'>
CASE = <TokenType.CASE: 'CASE'>
CHARACTER_SET = <TokenType.CHARACTER_SET: 'CHARACTER_SET'>
CLUSTER_BY = <TokenType.CLUSTER_BY: 'CLUSTER_BY'>
COLLATE = <TokenType.COLLATE: 'COLLATE'>
COMMAND = <TokenType.COMMAND: 'COMMAND'>
COMMENT = <TokenType.COMMENT: 'COMMENT'>
COMMIT = <TokenType.COMMIT: 'COMMIT'>
CONNECT_BY = <TokenType.CONNECT_BY: 'CONNECT_BY'>
CONSTRAINT = <TokenType.CONSTRAINT: 'CONSTRAINT'>
CREATE = <TokenType.CREATE: 'CREATE'>
CROSS = <TokenType.CROSS: 'CROSS'>
CUBE = <TokenType.CUBE: 'CUBE'>
CURRENT_DATE = <TokenType.CURRENT_DATE: 'CURRENT_DATE'>
CURRENT_DATETIME = <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>
CURRENT_TIME = <TokenType.CURRENT_TIME: 'CURRENT_TIME'>
CURRENT_TIMESTAMP = <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>
CURRENT_USER = <TokenType.CURRENT_USER: 'CURRENT_USER'>
DEFAULT = <TokenType.DEFAULT: 'DEFAULT'>
DELETE = <TokenType.DELETE: 'DELETE'>
DESC = <TokenType.DESC: 'DESC'>
DESCRIBE = <TokenType.DESCRIBE: 'DESCRIBE'>
DICTIONARY = <TokenType.DICTIONARY: 'DICTIONARY'>
DISTINCT = <TokenType.DISTINCT: 'DISTINCT'>
DISTRIBUTE_BY = <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>
DIV = <TokenType.DIV: 'DIV'>
DROP = <TokenType.DROP: 'DROP'>
ELSE = <TokenType.ELSE: 'ELSE'>
END = <TokenType.END: 'END'>
ESCAPE = <TokenType.ESCAPE: 'ESCAPE'>
EXCEPT = <TokenType.EXCEPT: 'EXCEPT'>
EXECUTE = <TokenType.EXECUTE: 'EXECUTE'>
EXISTS = <TokenType.EXISTS: 'EXISTS'>
FALSE = <TokenType.FALSE: 'FALSE'>
FETCH = <TokenType.FETCH: 'FETCH'>
FILTER = <TokenType.FILTER: 'FILTER'>
FINAL = <TokenType.FINAL: 'FINAL'>
FIRST = <TokenType.FIRST: 'FIRST'>
FOR = <TokenType.FOR: 'FOR'>
FORCE = <TokenType.FORCE: 'FORCE'>
FOREIGN_KEY = <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>
FORMAT = <TokenType.FORMAT: 'FORMAT'>
FROM = <TokenType.FROM: 'FROM'>
FULL = <TokenType.FULL: 'FULL'>
FUNCTION = <TokenType.FUNCTION: 'FUNCTION'>
GLOB = <TokenType.GLOB: 'GLOB'>
GLOBAL = <TokenType.GLOBAL: 'GLOBAL'>
GROUP_BY = <TokenType.GROUP_BY: 'GROUP_BY'>
GROUPING_SETS = <TokenType.GROUPING_SETS: 'GROUPING_SETS'>
HAVING = <TokenType.HAVING: 'HAVING'>
HINT = <TokenType.HINT: 'HINT'>
IGNORE = <TokenType.IGNORE: 'IGNORE'>
ILIKE = <TokenType.ILIKE: 'ILIKE'>
ILIKE_ANY = <TokenType.ILIKE_ANY: 'ILIKE_ANY'>
IN = <TokenType.IN: 'IN'>
INDEX = <TokenType.INDEX: 'INDEX'>
INNER = <TokenType.INNER: 'INNER'>
INSERT = <TokenType.INSERT: 'INSERT'>
INTERSECT = <TokenType.INTERSECT: 'INTERSECT'>
INTERVAL = <TokenType.INTERVAL: 'INTERVAL'>
INTO = <TokenType.INTO: 'INTO'>
INTRODUCER = <TokenType.INTRODUCER: 'INTRODUCER'>
IRLIKE = <TokenType.IRLIKE: 'IRLIKE'>
IS = <TokenType.IS: 'IS'>
ISNULL = <TokenType.ISNULL: 'ISNULL'>
JOIN = <TokenType.JOIN: 'JOIN'>
JOIN_MARKER = <TokenType.JOIN_MARKER: 'JOIN_MARKER'>
KEEP = <TokenType.KEEP: 'KEEP'>
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

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

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

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

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

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

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

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

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

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

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

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

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

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

SINGLE_TOKENS = {'(': <TokenType.L_PAREN: 'L_PAREN'>, ')': <TokenType.R_PAREN: 'R_PAREN'>, '[': <TokenType.L_BRACKET: 'L_BRACKET'>, ']': <TokenType.R_BRACKET: 'R_BRACKET'>, '{': <TokenType.L_BRACE: 'L_BRACE'>, '}': <TokenType.R_BRACE: 'R_BRACE'>, '&': <TokenType.AMP: 'AMP'>, '^': <TokenType.CARET: 'CARET'>, ':': <TokenType.COLON: 'COLON'>, ',': <TokenType.COMMA: 'COMMA'>, '.': <TokenType.DOT: 'DOT'>, '-': <TokenType.DASH: 'DASH'>, '=': <TokenType.EQ: 'EQ'>, '>': <TokenType.GT: 'GT'>, '<': <TokenType.LT: 'LT'>, '%': <TokenType.MOD: 'MOD'>, '!': <TokenType.NOT: 'NOT'>, '|': <TokenType.PIPE: 'PIPE'>, '+': <TokenType.PLUS: 'PLUS'>, ';': <TokenType.SEMICOLON: 'SEMICOLON'>, '/': <TokenType.SLASH: 'SLASH'>, '\\': <TokenType.BACKSLASH: 'BACKSLASH'>, '*': <TokenType.STAR: 'STAR'>, '~': <TokenType.TILDA: 'TILDA'>, '?': <TokenType.PLACEHOLDER: 'PLACEHOLDER'>, '@': <TokenType.PARAMETER: 'PARAMETER'>, "'": <TokenType.QUOTE: 'QUOTE'>, '`': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '"': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '#': <TokenType.HASH: 'HASH'>}
BIT_STRINGS: List[Union[str, Tuple[str, str]]] = []
BYTE_STRINGS: List[Union[str, Tuple[str, str]]] = []
HEX_STRINGS: List[Union[str, Tuple[str, str]]] = []
RAW_STRINGS: List[Union[str, Tuple[str, str]]] = []
IDENTIFIERS: List[Union[str, Tuple[str, str]]] = ['"']
IDENTIFIER_ESCAPES = ['"']
QUOTES: List[Union[str, Tuple[str, str]]] = ["'"]
STRING_ESCAPES = ["'"]
VAR_SINGLE_TOKENS: Set[str] = set()
IDENTIFIERS_CAN_START_WITH_DIGIT: bool = False
KEYWORDS: Dict[str, TokenType] = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, '??': <TokenType.DQMARK: 'DQMARK'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, '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.COMMAND: 'COMMAND'>, <TokenType.FETCH: 'FETCH'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.SHOW: 'SHOW'>}
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

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

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

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

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

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

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

size
sql
tokens