Edit on GitHub

# sqlglot.tokens

View Source

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

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

     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    NATIONAL = auto()
     56    DAMP = 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
     77    # types
     78    BIT = auto()
     79    BOOLEAN = auto()
     80    TINYINT = auto()
     81    UTINYINT = auto()
     82    SMALLINT = auto()
     83    USMALLINT = auto()
     84    INT = auto()
     85    UINT = auto()
     86    BIGINT = auto()
     87    UBIGINT = auto()
     88    FLOAT = auto()
     89    DOUBLE = auto()
     90    DECIMAL = auto()
     91    BIGDECIMAL = auto()
     92    CHAR = auto()
     93    NCHAR = auto()
     94    VARCHAR = auto()
     95    NVARCHAR = auto()
     96    TEXT = auto()
     97    MEDIUMTEXT = auto()
     98    LONGTEXT = auto()
     99    MEDIUMBLOB = auto()
    100    LONGBLOB = auto()
    101    BINARY = auto()
    102    VARBINARY = auto()
    103    JSON = auto()
    104    JSONB = auto()
    105    TIME = auto()
    106    TIMESTAMP = auto()
    107    TIMESTAMPTZ = auto()
    108    TIMESTAMPLTZ = auto()
    109    DATETIME = auto()
    110    DATE = auto()
    111    UUID = auto()
    112    GEOGRAPHY = auto()
    113    NULLABLE = auto()
    114    GEOMETRY = auto()
    115    HLLSKETCH = auto()
    116    HSTORE = auto()
    117    SUPER = auto()
    118    SERIAL = auto()
    119    SMALLSERIAL = auto()
    120    BIGSERIAL = auto()
    121    XML = auto()
    122    UNIQUEIDENTIFIER = auto()
    123    MONEY = auto()
    124    SMALLMONEY = auto()
    125    ROWVERSION = auto()
    126    IMAGE = auto()
    127    VARIANT = auto()
    128    OBJECT = auto()
    129    INET = auto()
    130
    131    # keywords
    132    ALIAS = auto()
    133    ALTER = auto()
    134    ALWAYS = auto()
    135    ALL = auto()
    136    ANTI = auto()
    137    ANY = auto()
    138    APPLY = auto()
    139    ARRAY = auto()
    140    ASC = auto()
    141    ASOF = auto()
    142    AT_TIME_ZONE = auto()
    143    AUTO_INCREMENT = auto()
    144    BEGIN = auto()
    145    BETWEEN = auto()
    146    BOTH = auto()
    147    BUCKET = auto()
    148    BY_DEFAULT = auto()
    149    CACHE = auto()
    150    CASCADE = auto()
    151    CASE = auto()
    152    CHARACTER_SET = auto()
    153    CLUSTER_BY = auto()
    154    COLLATE = auto()
    155    COMMAND = auto()
    156    COMMENT = auto()
    157    COMMIT = auto()
    158    COMPOUND = auto()
    159    CONSTRAINT = auto()
    160    CREATE = auto()
    161    CROSS = auto()
    162    CUBE = auto()
    163    CURRENT_DATE = auto()
    164    CURRENT_DATETIME = auto()
    165    CURRENT_ROW = auto()
    166    CURRENT_TIME = auto()
    167    CURRENT_TIMESTAMP = auto()
    168    CURRENT_USER = auto()
    169    DEFAULT = auto()
    170    DELETE = auto()
    171    DESC = auto()
    172    DESCRIBE = auto()
    173    DISTINCT = auto()
    174    DISTINCT_FROM = auto()
    175    DISTRIBUTE_BY = auto()
    176    DIV = auto()
    177    DROP = auto()
    178    ELSE = auto()
    179    END = auto()
    180    ESCAPE = auto()
    181    EXCEPT = auto()
    182    EXECUTE = auto()
    183    EXISTS = auto()
    184    FALSE = auto()
    185    FETCH = auto()
    186    FILTER = auto()
    187    FINAL = auto()
    188    FIRST = auto()
    189    FOLLOWING = auto()
    190    FOR = auto()
    191    FOREIGN_KEY = auto()
    192    FORMAT = auto()
    193    FROM = auto()
    194    FULL = auto()
    195    FUNCTION = auto()
    196    GLOB = auto()
    197    GLOBAL = auto()
    198    GROUP_BY = auto()
    199    GROUPING_SETS = auto()
    200    HAVING = auto()
    201    HINT = auto()
    202    IF = auto()
    203    IGNORE_NULLS = auto()
    204    ILIKE = auto()
    205    ILIKE_ANY = auto()
    206    IN = auto()
    207    INDEX = auto()
    208    INNER = auto()
    209    INSERT = auto()
    210    INTERSECT = auto()
    211    INTERVAL = auto()
    212    INTO = auto()
    213    INTRODUCER = auto()
    214    IRLIKE = auto()
    215    IS = auto()
    216    ISNULL = auto()
    217    JOIN = auto()
    218    JOIN_MARKER = auto()
    219    KEEP = auto()
    220    LANGUAGE = auto()
    221    LATERAL = auto()
    222    LAZY = auto()
    223    LEADING = auto()
    224    LEFT = auto()
    225    LIKE = auto()
    226    LIKE_ANY = auto()
    227    LIMIT = auto()
    228    LOAD_DATA = auto()
    229    LOCAL = auto()
    230    MAP = auto()
    231    MATCH_RECOGNIZE = auto()
    232    MATERIALIZED = auto()
    233    MERGE = auto()
    234    MOD = auto()
    235    NATURAL = auto()
    236    NEXT = auto()
    237    NEXT_VALUE_FOR = auto()
    238    NO_ACTION = auto()
    239    NOTNULL = auto()
    240    NULL = auto()
    241    NULLS_FIRST = auto()
    242    NULLS_LAST = auto()
    243    OFFSET = auto()
    244    ON = auto()
    245    ONLY = auto()
    246    OPTIONS = auto()
    247    ORDER_BY = auto()
    248    ORDERED = auto()
    249    ORDINALITY = auto()
    250    OUTER = auto()
    251    OUT_OF = auto()
    252    OVER = auto()
    253    OVERLAPS = auto()
    254    OVERWRITE = auto()
    255    PARTITION = auto()
    256    PARTITION_BY = auto()
    257    PERCENT = auto()
    258    PIVOT = auto()
    259    PLACEHOLDER = auto()
    260    PRAGMA = auto()
    261    PRECEDING = auto()
    262    PRIMARY_KEY = auto()
    263    PROCEDURE = auto()
    264    PROPERTIES = auto()
    265    PSEUDO_TYPE = auto()
    266    QUALIFY = auto()
    267    QUOTE = auto()
    268    RANGE = auto()
    269    RECURSIVE = auto()
    270    REPLACE = auto()
    271    RESPECT_NULLS = auto()
    272    RETURNING = auto()
    273    REFERENCES = auto()
    274    RIGHT = auto()
    275    RLIKE = auto()
    276    ROLLBACK = auto()
    277    ROLLUP = auto()
    278    ROW = auto()
    279    ROWS = auto()
    280    SEED = auto()
    281    SELECT = auto()
    282    SEMI = auto()
    283    SEPARATOR = auto()
    284    SERDE_PROPERTIES = auto()
    285    SET = auto()
    286    SHOW = auto()
    287    SIMILAR_TO = auto()
    288    SOME = auto()
    289    SORTKEY = auto()
    290    SORT_BY = auto()
    291    STRUCT = auto()
    292    TABLE_SAMPLE = auto()
    293    TEMPORARY = auto()
    294    TOP = auto()
    295    THEN = auto()
    296    TRAILING = auto()
    297    TRUE = auto()
    298    UNBOUNDED = auto()
    299    UNCACHE = auto()
    300    UNION = auto()
    301    UNLOGGED = 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    WITH_TIME_ZONE = auto()
    315    WITH_LOCAL_TIME_ZONE = auto()
    316    WITHIN_GROUP = auto()
    317    WITHOUT_TIME_ZONE = auto()
    318    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'>
NATIONAL = <TokenType.NATIONAL: 'NATIONAL'>
DAMP = <TokenType.DAMP: 'DAMP'>
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'>
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'>
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'>
DATE = <TokenType.DATE: 'DATE'>
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'>
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'>
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'>
AT_TIME_ZONE = <TokenType.AT_TIME_ZONE: 'AT_TIME_ZONE'>
AUTO_INCREMENT = <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>
BEGIN = <TokenType.BEGIN: 'BEGIN'>
BETWEEN = <TokenType.BETWEEN: 'BETWEEN'>
BOTH = <TokenType.BOTH: 'BOTH'>
BUCKET = <TokenType.BUCKET: 'BUCKET'>
BY_DEFAULT = <TokenType.BY_DEFAULT: 'BY_DEFAULT'>
CACHE = <TokenType.CACHE: 'CACHE'>
CASCADE = <TokenType.CASCADE: 'CASCADE'>
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'>
COMPOUND = <TokenType.COMPOUND: 'COMPOUND'>
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_ROW = <TokenType.CURRENT_ROW: 'CURRENT_ROW'>
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'>
DISTINCT = <TokenType.DISTINCT: 'DISTINCT'>
DISTINCT_FROM = <TokenType.DISTINCT_FROM: 'DISTINCT_FROM'>
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'>
FOLLOWING = <TokenType.FOLLOWING: 'FOLLOWING'>
FOR = <TokenType.FOR: 'FOR'>
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_NULLS = <TokenType.IGNORE_NULLS: 'IGNORE_NULLS'>
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'>
LAZY = <TokenType.LAZY: 'LAZY'>
LEADING = <TokenType.LEADING: 'LEADING'>
LEFT = <TokenType.LEFT: 'LEFT'>
LIKE = <TokenType.LIKE: 'LIKE'>
LIKE_ANY = <TokenType.LIKE_ANY: 'LIKE_ANY'>
LIMIT = <TokenType.LIMIT: 'LIMIT'>
LOAD_DATA = <TokenType.LOAD_DATA: 'LOAD_DATA'>
LOCAL = <TokenType.LOCAL: 'LOCAL'>
MAP = <TokenType.MAP: 'MAP'>
MATCH_RECOGNIZE = <TokenType.MATCH_RECOGNIZE: 'MATCH_RECOGNIZE'>
MATERIALIZED = <TokenType.MATERIALIZED: 'MATERIALIZED'>
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'>
NO_ACTION = <TokenType.NO_ACTION: 'NO_ACTION'>
NOTNULL = <TokenType.NOTNULL: 'NOTNULL'>
NULL = <TokenType.NULL: 'NULL'>
NULLS_FIRST = <TokenType.NULLS_FIRST: 'NULLS_FIRST'>
NULLS_LAST = <TokenType.NULLS_LAST: 'NULLS_LAST'>
OFFSET = <TokenType.OFFSET: 'OFFSET'>
ON = <TokenType.ON: 'ON'>
ONLY = <TokenType.ONLY: 'ONLY'>
OPTIONS = <TokenType.OPTIONS: 'OPTIONS'>
ORDER_BY = <TokenType.ORDER_BY: 'ORDER_BY'>
ORDERED = <TokenType.ORDERED: 'ORDERED'>
ORDINALITY = <TokenType.ORDINALITY: 'ORDINALITY'>
OUTER = <TokenType.OUTER: 'OUTER'>
OUT_OF = <TokenType.OUT_OF: 'OUT_OF'>
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'>
PRECEDING = <TokenType.PRECEDING: 'PRECEDING'>
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'>
RESPECT_NULLS = <TokenType.RESPECT_NULLS: 'RESPECT_NULLS'>
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'>
SEED = <TokenType.SEED: 'SEED'>
SELECT = <TokenType.SELECT: 'SELECT'>
SEMI = <TokenType.SEMI: 'SEMI'>
SEPARATOR = <TokenType.SEPARATOR: 'SEPARATOR'>
SERDE_PROPERTIES = <TokenType.SERDE_PROPERTIES: 'SERDE_PROPERTIES'>
SET = <TokenType.SET: 'SET'>
SHOW = <TokenType.SHOW: 'SHOW'>
SIMILAR_TO = <TokenType.SIMILAR_TO: 'SIMILAR_TO'>
SOME = <TokenType.SOME: 'SOME'>
SORTKEY = <TokenType.SORTKEY: 'SORTKEY'>
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'>
TRAILING = <TokenType.TRAILING: 'TRAILING'>
TRUE = <TokenType.TRUE: 'TRUE'>
UNBOUNDED = <TokenType.UNBOUNDED: 'UNBOUNDED'>
UNCACHE = <TokenType.UNCACHE: 'UNCACHE'>
UNION = <TokenType.UNION: 'UNION'>
UNLOGGED = <TokenType.UNLOGGED: 'UNLOGGED'>
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'>
WITH_TIME_ZONE = <TokenType.WITH_TIME_ZONE: 'WITH_TIME_ZONE'>
WITH_LOCAL_TIME_ZONE = <TokenType.WITH_LOCAL_TIME_ZONE: 'WITH_LOCAL_TIME_ZONE'>
WITHIN_GROUP = <TokenType.WITHIN_GROUP: 'WITHIN_GROUP'>
WITHOUT_TIME_ZONE = <TokenType.WITHOUT_TIME_ZONE: 'WITHOUT_TIME_ZONE'>
UNIQUE = <TokenType.UNIQUE: 'UNIQUE'>

##### Inherited Members

enum.Enum
  name
  value

class Token: View Source

    321class Token:
    322    __slots__ = ("token_type", "text", "line", "col", "end", "comments")
    323
    324    @classmethod
    325    def number(cls, number: int) -> Token:
    326        """Returns a NUMBER token with `number` as its text."""
    327        return cls(TokenType.NUMBER, str(number))
    328
    329    @classmethod
    330    def string(cls, string: str) -> Token:
    331        """Returns a STRING token with `string` as its text."""
    332        return cls(TokenType.STRING, string)
    333
    334    @classmethod
    335    def identifier(cls, identifier: str) -> Token:
    336        """Returns an IDENTIFIER token with `identifier` as its text."""
    337        return cls(TokenType.IDENTIFIER, identifier)
    338
    339    @classmethod
    340    def var(cls, var: str) -> Token:
    341        """Returns an VAR token with `var` as its text."""
    342        return cls(TokenType.VAR, var)
    343
    344    def __init__(
    345        self,
    346        token_type: TokenType,
    347        text: str,
    348        line: int = 1,
    349        col: int = 1,
    350        end: int = 0,
    351        comments: t.List[str] = [],
    352    ) -> None:
    353        self.token_type = token_type
    354        self.text = text
    355        self.line = line
    356        size = len(text)
    357        self.col = col
    358        self.end = end if end else size
    359        self.comments = comments
    360
    361    @property
    362    def start(self) -> int:
    363        """Returns the start of the token."""
    364        return self.end - len(self.text)
    365
    366    def __repr__(self) -> str:
    367        attributes = ", ".join(f"{k}: {getattr(self, k)}" for k in self.__slots__)
    368        return f"<Token {attributes}>"

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

    344    def __init__(
    345        self,
    346        token_type: TokenType,
    347        text: str,
    348        line: int = 1,
    349        col: int = 1,
    350        end: int = 0,
    351        comments: t.List[str] = [],
    352    ) -> None:
    353        self.token_type = token_type
    354        self.text = text
    355        self.line = line
    356        size = len(text)
    357        self.col = col
    358        self.end = end if end else size
    359        self.comments = comments

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

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

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

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

    339    @classmethod
    340    def var(cls, var: str) -> Token:
    341        """Returns an VAR token with `var` as its text."""
    342        return cls(TokenType.VAR, var)

Returns an VAR token with `var` as its text.

start: int

Returns the start of the token.

class Tokenizer: View Source

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

def reset(self) -> None: View Source

    785    def reset(self) -> None:
    786        self.sql = ""
    787        self.size = 0
    788        self.tokens: t.List[Token] = []
    789        self._start = 0
    790        self._current = 0
    791        self._line = 1
    792        self._col = 1
    793        self._comments: t.List[str] = []
    794
    795        self._char = ""
    796        self._end = False
    797        self._peek = ""
    798        self._prev_token_line = -1
    799        self._prev_token_comments: t.List[str] = []
    800        self._prev_token_type: t.Optional[TokenType] = None

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

    802    def tokenize(self, sql: str) -> t.List[Token]:
    803        """Returns a list of tokens corresponding to the SQL string `sql`."""
    804        self.reset()
    805        self.sql = sql
    806        self.size = len(sql)
    807        try:
    808            self._scan()
    809        except Exception as e:
    810            start = self._current - 50
    811            end = self._current + 50
    812            start = start if start > 0 else 0
    813            end = end if end < self.size else self.size - 1
    814            context = self.sql[start:end]
    815            raise ValueError(f"Error tokenizing '{context}'") from e
    816
    817        return self.tokens

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