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

##### Inherited Members

enum.Enum
  name
  value

class Token: View Source

    318class Token:
    319    __slots__ = ("token_type", "text", "line", "col", "start", "end", "comments")
    320
    321    @classmethod
    322    def number(cls, number: int) -> Token:
    323        """Returns a NUMBER token with `number` as its text."""
    324        return cls(TokenType.NUMBER, str(number))
    325
    326    @classmethod
    327    def string(cls, string: str) -> Token:
    328        """Returns a STRING token with `string` as its text."""
    329        return cls(TokenType.STRING, string)
    330
    331    @classmethod
    332    def identifier(cls, identifier: str) -> Token:
    333        """Returns an IDENTIFIER token with `identifier` as its text."""
    334        return cls(TokenType.IDENTIFIER, identifier)
    335
    336    @classmethod
    337    def var(cls, var: str) -> Token:
    338        """Returns an VAR token with `var` as its text."""
    339        return cls(TokenType.VAR, var)
    340
    341    def __init__(
    342        self,
    343        token_type: TokenType,
    344        text: str,
    345        line: int = 1,
    346        col: int = 1,
    347        start: int = 0,
    348        end: int = 0,
    349        comments: t.List[str] = [],
    350    ) -> None:
    351        """Token initializer.
    352
    353        Args:
    354            token_type: The TokenType Enum.
    355            text: The text of the token.
    356            line: The line that the token ends on.
    357            col: The column that the token ends on.
    358            start: The start index of the token.
    359            end: The ending index of the token.
    360            comments: The comments to attach to the token.
    361        """
    362        self.token_type = token_type
    363        self.text = text
    364        self.line = line
    365        self.col = col
    366        self.start = start
    367        self.end = end
    368        self.comments = comments
    369
    370    def __repr__(self) -> str:
    371        attributes = ", ".join(f"{k}: {getattr(self, k)}" for k in self.__slots__)
    372        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

    341    def __init__(
    342        self,
    343        token_type: TokenType,
    344        text: str,
    345        line: int = 1,
    346        col: int = 1,
    347        start: int = 0,
    348        end: int = 0,
    349        comments: t.List[str] = [],
    350    ) -> None:
    351        """Token initializer.
    352
    353        Args:
    354            token_type: The TokenType Enum.
    355            text: The text of the token.
    356            line: The line that the token ends on.
    357            col: The column that the token ends on.
    358            start: The start index of the token.
    359            end: The ending index of the token.
    360            comments: The comments to attach to the token.
    361        """
    362        self.token_type = token_type
    363        self.text = text
    364        self.line = line
    365        self.col = col
    366        self.start = start
    367        self.end = end
    368        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

    321    @classmethod
    322    def number(cls, number: int) -> Token:
    323        """Returns a NUMBER token with `number` as its text."""
    324        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

    326    @classmethod
    327    def string(cls, string: str) -> Token:
    328        """Returns a STRING token with `string` as its text."""
    329        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

    331    @classmethod
    332    def identifier(cls, identifier: str) -> Token:
    333        """Returns an IDENTIFIER token with `identifier` as its text."""
    334        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

    336    @classmethod
    337    def var(cls, var: str) -> Token:
    338        """Returns an VAR token with `var` as its text."""
    339        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

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

    778    def reset(self) -> None:
    779        self.sql = ""
    780        self.size = 0
    781        self.tokens: t.List[Token] = []
    782        self._start = 0
    783        self._current = 0
    784        self._line = 1
    785        self._col = 0
    786        self._comments: t.List[str] = []
    787
    788        self._char = ""
    789        self._end = False
    790        self._peek = ""
    791        self._prev_token_line = -1

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

    793    def tokenize(self, sql: str) -> t.List[Token]:
    794        """Returns a list of tokens corresponding to the SQL string `sql`."""
    795        self.reset()
    796        self.sql = sql
    797        self.size = len(sql)
    798
    799        try:
    800            self._scan()
    801        except Exception as e:
    802            start = max(self._current - 50, 0)
    803            end = min(self._current + 50, self.size - 1)
    804            context = self.sql[start:end]
    805            raise TokenError(f"Error tokenizing '{context}'") from e
    806
    807        return self.tokens

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

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

    875    def peek(self, i: int = 0) -> str:
    876        i = self._current + i
    877        if i < self.size:
    878            return self.sql[i]
    879        return ""

size
sql
tokens