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

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

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

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

Token initializer.

###### Arguments:

- token_type: The TokenType Enum.
- text: The text of the token.
- line: The line that the token ends on.
- col: The column that the token ends on.
- start: The start index of the token.
- end: The ending index of the token.
- comments: The comments to attach to the token.

@classmethod
def number(cls, number: int) -> sqlglot.tokens.Token: View Source

    336    @classmethod
    337    def number(cls, number: int) -> Token:
    338        """Returns a NUMBER token with `number` as its text."""
    339        return cls(TokenType.NUMBER, str(number))

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

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

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

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

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

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

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

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

    351    @classmethod
    352    def var(cls, var: str) -> Token:
    353        """Returns an VAR token with `var` as its text."""
    354        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

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

SINGLE_TOKENS = {'(': <TokenType.L_PAREN: 'L_PAREN'>, ')': <TokenType.R_PAREN: 'R_PAREN'>, '[': <TokenType.L_BRACKET: 'L_BRACKET'>, ']': <TokenType.R_BRACKET: 'R_BRACKET'>, '{': <TokenType.L_BRACE: 'L_BRACE'>, '}': <TokenType.R_BRACE: 'R_BRACE'>, '&': <TokenType.AMP: 'AMP'>, '^': <TokenType.CARET: 'CARET'>, ':': <TokenType.COLON: 'COLON'>, ',': <TokenType.COMMA: 'COMMA'>, '.': <TokenType.DOT: 'DOT'>, '-': <TokenType.DASH: 'DASH'>, '=': <TokenType.EQ: 'EQ'>, '>': <TokenType.GT: 'GT'>, '<': <TokenType.LT: 'LT'>, '%': <TokenType.MOD: 'MOD'>, '!': <TokenType.NOT: 'NOT'>, '|': <TokenType.PIPE: 'PIPE'>, '+': <TokenType.PLUS: 'PLUS'>, ';': <TokenType.SEMICOLON: 'SEMICOLON'>, '/': <TokenType.SLASH: 'SLASH'>, '\\': <TokenType.BACKSLASH: 'BACKSLASH'>, '*': <TokenType.STAR: 'STAR'>, '~': <TokenType.TILDA: 'TILDA'>, '?': <TokenType.PLACEHOLDER: 'PLACEHOLDER'>, '@': <TokenType.PARAMETER: 'PARAMETER'>, "'": <TokenType.QUOTE: 'QUOTE'>, '`': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '"': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '#': <TokenType.HASH: 'HASH'>}
BIT_STRINGS: List[Union[str, Tuple[str, str]]] = []
BYTE_STRINGS: List[Union[str, Tuple[str, str]]] = []
HEX_STRINGS: List[Union[str, Tuple[str, str]]] = []
RAW_STRINGS: List[Union[str, Tuple[str, str]]] = []
IDENTIFIERS: List[Union[str, Tuple[str, str]]] = ['"']
IDENTIFIER_ESCAPES = ['"']
QUOTES: List[Union[str, Tuple[str, str]]] = ["'"]
STRING_ESCAPES = ["'"]
VAR_SINGLE_TOKENS: Set[str] = set()
IDENTIFIERS_CAN_START_WITH_DIGIT: bool = False
KEYWORDS: Dict[str, sqlglot.tokens.TokenType] = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, '??': <TokenType.DQMARK: 'DQMARK'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'START WITH': <TokenType.START_WITH: 'START_WITH'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, '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'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, '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], sqlglot.tokens.TokenType] = {' ': <TokenType.SPACE: 'SPACE'>, '\t': <TokenType.SPACE: 'SPACE'>, '\n': <TokenType.BREAK: 'BREAK'>, '\r': <TokenType.BREAK: 'BREAK'>, '\r\n': <TokenType.BREAK: 'BREAK'>}
COMMANDS = {<TokenType.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

    799    def reset(self) -> None:
    800        self.sql = ""
    801        self.size = 0
    802        self.tokens: t.List[Token] = []
    803        self._start = 0
    804        self._current = 0
    805        self._line = 1
    806        self._col = 0
    807        self._comments: t.List[str] = []
    808
    809        self._char = ""
    810        self._end = False
    811        self._peek = ""
    812        self._prev_token_line = -1

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

    814    def tokenize(self, sql: str) -> t.List[Token]:
    815        """Returns a list of tokens corresponding to the SQL string `sql`."""
    816        self.reset()
    817        self.sql = sql
    818        self.size = len(sql)
    819
    820        try:
    821            self._scan()
    822        except Exception as e:
    823            start = max(self._current - 50, 0)
    824            end = min(self._current + 50, self.size - 1)
    825            context = self.sql[start:end]
    826            raise TokenError(f"Error tokenizing '{context}'") from e
    827
    828        return self.tokens

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

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

    896    def peek(self, i: int = 0) -> str:
    897        i = self._current + i
    898        if i < self.size:
    899            return self.sql[i]
    900        return ""

size
sql
tokens