sqlglot.tokens API documentation

Edit on GitHub

# sqlglot.tokens

View Source

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

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

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

An enumeration.

L_PAREN = <TokenType.L_PAREN: 'L_PAREN'>
R_PAREN = <TokenType.R_PAREN: 'R_PAREN'>
L_BRACKET = <TokenType.L_BRACKET: 'L_BRACKET'>
R_BRACKET = <TokenType.R_BRACKET: 'R_BRACKET'>
L_BRACE = <TokenType.L_BRACE: 'L_BRACE'>
R_BRACE = <TokenType.R_BRACE: 'R_BRACE'>
COMMA = <TokenType.COMMA: 'COMMA'>
DOT = <TokenType.DOT: 'DOT'>
DASH = <TokenType.DASH: 'DASH'>
PLUS = <TokenType.PLUS: 'PLUS'>
COLON = <TokenType.COLON: 'COLON'>
DCOLON = <TokenType.DCOLON: 'DCOLON'>
DQMARK = <TokenType.DQMARK: 'DQMARK'>
SEMICOLON = <TokenType.SEMICOLON: 'SEMICOLON'>
STAR = <TokenType.STAR: 'STAR'>
BACKSLASH = <TokenType.BACKSLASH: 'BACKSLASH'>
SLASH = <TokenType.SLASH: 'SLASH'>
LT = <TokenType.LT: 'LT'>
LTE = <TokenType.LTE: 'LTE'>
GT = <TokenType.GT: 'GT'>
GTE = <TokenType.GTE: 'GTE'>
NOT = <TokenType.NOT: 'NOT'>
EQ = <TokenType.EQ: 'EQ'>
NEQ = <TokenType.NEQ: 'NEQ'>
NULLSAFE_EQ = <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>
COLON_EQ = <TokenType.COLON_EQ: 'COLON_EQ'>
AND = <TokenType.AND: 'AND'>
OR = <TokenType.OR: 'OR'>
AMP = <TokenType.AMP: 'AMP'>
DPIPE = <TokenType.DPIPE: 'DPIPE'>
PIPE = <TokenType.PIPE: 'PIPE'>
CARET = <TokenType.CARET: 'CARET'>
TILDA = <TokenType.TILDA: 'TILDA'>
ARROW = <TokenType.ARROW: 'ARROW'>
DARROW = <TokenType.DARROW: 'DARROW'>
FARROW = <TokenType.FARROW: 'FARROW'>
HASH = <TokenType.HASH: 'HASH'>
HASH_ARROW = <TokenType.HASH_ARROW: 'HASH_ARROW'>
DHASH_ARROW = <TokenType.DHASH_ARROW: 'DHASH_ARROW'>
LR_ARROW = <TokenType.LR_ARROW: 'LR_ARROW'>
DAT = <TokenType.DAT: 'DAT'>
LT_AT = <TokenType.LT_AT: 'LT_AT'>
AT_GT = <TokenType.AT_GT: 'AT_GT'>
DOLLAR = <TokenType.DOLLAR: 'DOLLAR'>
PARAMETER = <TokenType.PARAMETER: 'PARAMETER'>
SESSION_PARAMETER = <TokenType.SESSION_PARAMETER: 'SESSION_PARAMETER'>
DAMP = <TokenType.DAMP: 'DAMP'>
XOR = <TokenType.XOR: 'XOR'>
DSTAR = <TokenType.DSTAR: 'DSTAR'>
BLOCK_START = <TokenType.BLOCK_START: 'BLOCK_START'>
BLOCK_END = <TokenType.BLOCK_END: 'BLOCK_END'>
SPACE = <TokenType.SPACE: 'SPACE'>
BREAK = <TokenType.BREAK: 'BREAK'>
STRING = <TokenType.STRING: 'STRING'>
NUMBER = <TokenType.NUMBER: 'NUMBER'>
IDENTIFIER = <TokenType.IDENTIFIER: 'IDENTIFIER'>
DATABASE = <TokenType.DATABASE: 'DATABASE'>
COLUMN = <TokenType.COLUMN: 'COLUMN'>
COLUMN_DEF = <TokenType.COLUMN_DEF: 'COLUMN_DEF'>
SCHEMA = <TokenType.SCHEMA: 'SCHEMA'>
TABLE = <TokenType.TABLE: 'TABLE'>
VAR = <TokenType.VAR: 'VAR'>
BIT_STRING = <TokenType.BIT_STRING: 'BIT_STRING'>
HEX_STRING = <TokenType.HEX_STRING: 'HEX_STRING'>
BYTE_STRING = <TokenType.BYTE_STRING: 'BYTE_STRING'>
NATIONAL_STRING = <TokenType.NATIONAL_STRING: 'NATIONAL_STRING'>
RAW_STRING = <TokenType.RAW_STRING: 'RAW_STRING'>
HEREDOC_STRING = <TokenType.HEREDOC_STRING: 'HEREDOC_STRING'>
BIT = <TokenType.BIT: 'BIT'>
BOOLEAN = <TokenType.BOOLEAN: 'BOOLEAN'>
TINYINT = <TokenType.TINYINT: 'TINYINT'>
UTINYINT = <TokenType.UTINYINT: 'UTINYINT'>
SMALLINT = <TokenType.SMALLINT: 'SMALLINT'>
USMALLINT = <TokenType.USMALLINT: 'USMALLINT'>
MEDIUMINT = <TokenType.MEDIUMINT: 'MEDIUMINT'>
UMEDIUMINT = <TokenType.UMEDIUMINT: 'UMEDIUMINT'>
INT = <TokenType.INT: 'INT'>
UINT = <TokenType.UINT: 'UINT'>
BIGINT = <TokenType.BIGINT: 'BIGINT'>
UBIGINT = <TokenType.UBIGINT: 'UBIGINT'>
INT128 = <TokenType.INT128: 'INT128'>
UINT128 = <TokenType.UINT128: 'UINT128'>
INT256 = <TokenType.INT256: 'INT256'>
UINT256 = <TokenType.UINT256: 'UINT256'>
FLOAT = <TokenType.FLOAT: 'FLOAT'>
DOUBLE = <TokenType.DOUBLE: 'DOUBLE'>
DECIMAL = <TokenType.DECIMAL: 'DECIMAL'>
UDECIMAL = <TokenType.UDECIMAL: 'UDECIMAL'>
BIGDECIMAL = <TokenType.BIGDECIMAL: 'BIGDECIMAL'>
CHAR = <TokenType.CHAR: 'CHAR'>
NCHAR = <TokenType.NCHAR: 'NCHAR'>
VARCHAR = <TokenType.VARCHAR: 'VARCHAR'>
NVARCHAR = <TokenType.NVARCHAR: 'NVARCHAR'>
TEXT = <TokenType.TEXT: 'TEXT'>
MEDIUMTEXT = <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <TokenType.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <TokenType.LONGBLOB: 'LONGBLOB'>
TINYBLOB = <TokenType.TINYBLOB: 'TINYBLOB'>
TINYTEXT = <TokenType.TINYTEXT: 'TINYTEXT'>
BINARY = <TokenType.BINARY: 'BINARY'>
VARBINARY = <TokenType.VARBINARY: 'VARBINARY'>
JSON = <TokenType.JSON: 'JSON'>
JSONB = <TokenType.JSONB: 'JSONB'>
TIME = <TokenType.TIME: 'TIME'>
TIMETZ = <TokenType.TIMETZ: 'TIMETZ'>
TIMESTAMP = <TokenType.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMP_S = <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>
TIMESTAMP_MS = <TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>
TIMESTAMP_NS = <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>
DATETIME = <TokenType.DATETIME: 'DATETIME'>
DATETIME64 = <TokenType.DATETIME64: 'DATETIME64'>
DATE = <TokenType.DATE: 'DATE'>
INT4RANGE = <TokenType.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <TokenType.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <TokenType.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <TokenType.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <TokenType.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <TokenType.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>
UUID = <TokenType.UUID: 'UUID'>
GEOGRAPHY = <TokenType.GEOGRAPHY: 'GEOGRAPHY'>
NULLABLE = <TokenType.NULLABLE: 'NULLABLE'>
GEOMETRY = <TokenType.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <TokenType.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <TokenType.HSTORE: 'HSTORE'>
SUPER = <TokenType.SUPER: 'SUPER'>
SERIAL = <TokenType.SERIAL: 'SERIAL'>
SMALLSERIAL = <TokenType.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <TokenType.BIGSERIAL: 'BIGSERIAL'>
XML = <TokenType.XML: 'XML'>
YEAR = <TokenType.YEAR: 'YEAR'>
UNIQUEIDENTIFIER = <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
USERDEFINED = <TokenType.USERDEFINED: 'USERDEFINED'>
MONEY = <TokenType.MONEY: 'MONEY'>
SMALLMONEY = <TokenType.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <TokenType.ROWVERSION: 'ROWVERSION'>
IMAGE = <TokenType.IMAGE: 'IMAGE'>
VARIANT = <TokenType.VARIANT: 'VARIANT'>
OBJECT = <TokenType.OBJECT: 'OBJECT'>
INET = <TokenType.INET: 'INET'>
IPADDRESS = <TokenType.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <TokenType.IPPREFIX: 'IPPREFIX'>
ENUM = <TokenType.ENUM: 'ENUM'>
ENUM8 = <TokenType.ENUM8: 'ENUM8'>
ENUM16 = <TokenType.ENUM16: 'ENUM16'>
FIXEDSTRING = <TokenType.FIXEDSTRING: 'FIXEDSTRING'>
LOWCARDINALITY = <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>
NESTED = <TokenType.NESTED: 'NESTED'>
UNKNOWN = <TokenType.UNKNOWN: 'UNKNOWN'>
ALIAS = <TokenType.ALIAS: 'ALIAS'>
ALTER = <TokenType.ALTER: 'ALTER'>
ALWAYS = <TokenType.ALWAYS: 'ALWAYS'>
ALL = <TokenType.ALL: 'ALL'>
ANTI = <TokenType.ANTI: 'ANTI'>
ANY = <TokenType.ANY: 'ANY'>
APPLY = <TokenType.APPLY: 'APPLY'>
ARRAY = <TokenType.ARRAY: 'ARRAY'>
ASC = <TokenType.ASC: 'ASC'>
ASOF = <TokenType.ASOF: 'ASOF'>
AUTO_INCREMENT = <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>
BEGIN = <TokenType.BEGIN: 'BEGIN'>
BETWEEN = <TokenType.BETWEEN: 'BETWEEN'>
CACHE = <TokenType.CACHE: 'CACHE'>
CASE = <TokenType.CASE: 'CASE'>
CHARACTER_SET = <TokenType.CHARACTER_SET: 'CHARACTER_SET'>
CLUSTER_BY = <TokenType.CLUSTER_BY: 'CLUSTER_BY'>
COLLATE = <TokenType.COLLATE: 'COLLATE'>
COMMAND = <TokenType.COMMAND: 'COMMAND'>
COMMENT = <TokenType.COMMENT: 'COMMENT'>
COMMIT = <TokenType.COMMIT: 'COMMIT'>
CONNECT_BY = <TokenType.CONNECT_BY: 'CONNECT_BY'>
CONSTRAINT = <TokenType.CONSTRAINT: 'CONSTRAINT'>
CREATE = <TokenType.CREATE: 'CREATE'>
CROSS = <TokenType.CROSS: 'CROSS'>
CUBE = <TokenType.CUBE: 'CUBE'>
CURRENT_DATE = <TokenType.CURRENT_DATE: 'CURRENT_DATE'>
CURRENT_DATETIME = <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>
CURRENT_TIME = <TokenType.CURRENT_TIME: 'CURRENT_TIME'>
CURRENT_TIMESTAMP = <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>
CURRENT_USER = <TokenType.CURRENT_USER: 'CURRENT_USER'>
DEFAULT = <TokenType.DEFAULT: 'DEFAULT'>
DELETE = <TokenType.DELETE: 'DELETE'>
DESC = <TokenType.DESC: 'DESC'>
DESCRIBE = <TokenType.DESCRIBE: 'DESCRIBE'>
DICTIONARY = <TokenType.DICTIONARY: 'DICTIONARY'>
DISTINCT = <TokenType.DISTINCT: 'DISTINCT'>
DISTRIBUTE_BY = <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>
DIV = <TokenType.DIV: 'DIV'>
DROP = <TokenType.DROP: 'DROP'>
ELSE = <TokenType.ELSE: 'ELSE'>
END = <TokenType.END: 'END'>
ESCAPE = <TokenType.ESCAPE: 'ESCAPE'>
EXCEPT = <TokenType.EXCEPT: 'EXCEPT'>
EXECUTE = <TokenType.EXECUTE: 'EXECUTE'>
EXISTS = <TokenType.EXISTS: 'EXISTS'>
FALSE = <TokenType.FALSE: 'FALSE'>
FETCH = <TokenType.FETCH: 'FETCH'>
FILTER = <TokenType.FILTER: 'FILTER'>
FINAL = <TokenType.FINAL: 'FINAL'>
FIRST = <TokenType.FIRST: 'FIRST'>
FOR = <TokenType.FOR: 'FOR'>
FORCE = <TokenType.FORCE: 'FORCE'>
FOREIGN_KEY = <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>
FORMAT = <TokenType.FORMAT: 'FORMAT'>
FROM = <TokenType.FROM: 'FROM'>
FULL = <TokenType.FULL: 'FULL'>
FUNCTION = <TokenType.FUNCTION: 'FUNCTION'>
GLOB = <TokenType.GLOB: 'GLOB'>
GLOBAL = <TokenType.GLOBAL: 'GLOBAL'>
GROUP_BY = <TokenType.GROUP_BY: 'GROUP_BY'>
GROUPING_SETS = <TokenType.GROUPING_SETS: 'GROUPING_SETS'>
HAVING = <TokenType.HAVING: 'HAVING'>
HINT = <TokenType.HINT: 'HINT'>
IGNORE = <TokenType.IGNORE: 'IGNORE'>
ILIKE = <TokenType.ILIKE: 'ILIKE'>
ILIKE_ANY = <TokenType.ILIKE_ANY: 'ILIKE_ANY'>
IN = <TokenType.IN: 'IN'>
INDEX = <TokenType.INDEX: 'INDEX'>
INNER = <TokenType.INNER: 'INNER'>
INSERT = <TokenType.INSERT: 'INSERT'>
INTERSECT = <TokenType.INTERSECT: 'INTERSECT'>
INTERVAL = <TokenType.INTERVAL: 'INTERVAL'>
INTO = <TokenType.INTO: 'INTO'>
INTRODUCER = <TokenType.INTRODUCER: 'INTRODUCER'>
IRLIKE = <TokenType.IRLIKE: 'IRLIKE'>
IS = <TokenType.IS: 'IS'>
ISNULL = <TokenType.ISNULL: 'ISNULL'>
JOIN = <TokenType.JOIN: 'JOIN'>
JOIN_MARKER = <TokenType.JOIN_MARKER: 'JOIN_MARKER'>
KEEP = <TokenType.KEEP: 'KEEP'>
KILL = <TokenType.KILL: 'KILL'>
LANGUAGE = <TokenType.LANGUAGE: 'LANGUAGE'>
LATERAL = <TokenType.LATERAL: 'LATERAL'>
LEFT = <TokenType.LEFT: 'LEFT'>
LIKE = <TokenType.LIKE: 'LIKE'>
LIKE_ANY = <TokenType.LIKE_ANY: 'LIKE_ANY'>
LIMIT = <TokenType.LIMIT: 'LIMIT'>
LOAD = <TokenType.LOAD: 'LOAD'>
LOCK = <TokenType.LOCK: 'LOCK'>
MAP = <TokenType.MAP: 'MAP'>
MATCH_RECOGNIZE = <TokenType.MATCH_RECOGNIZE: 'MATCH_RECOGNIZE'>
MEMBER_OF = <TokenType.MEMBER_OF: 'MEMBER_OF'>
MERGE = <TokenType.MERGE: 'MERGE'>
MOD = <TokenType.MOD: 'MOD'>
MODEL = <TokenType.MODEL: 'MODEL'>
NATURAL = <TokenType.NATURAL: 'NATURAL'>
NEXT = <TokenType.NEXT: 'NEXT'>
NOTNULL = <TokenType.NOTNULL: 'NOTNULL'>
NULL = <TokenType.NULL: 'NULL'>
OBJECT_IDENTIFIER = <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>
OFFSET = <TokenType.OFFSET: 'OFFSET'>
ON = <TokenType.ON: 'ON'>
OPERATOR = <TokenType.OPERATOR: 'OPERATOR'>
ORDER_BY = <TokenType.ORDER_BY: 'ORDER_BY'>
ORDERED = <TokenType.ORDERED: 'ORDERED'>
ORDINALITY = <TokenType.ORDINALITY: 'ORDINALITY'>
OUTER = <TokenType.OUTER: 'OUTER'>
OVER = <TokenType.OVER: 'OVER'>
OVERLAPS = <TokenType.OVERLAPS: 'OVERLAPS'>
OVERWRITE = <TokenType.OVERWRITE: 'OVERWRITE'>
PARTITION = <TokenType.PARTITION: 'PARTITION'>
PARTITION_BY = <TokenType.PARTITION_BY: 'PARTITION_BY'>
PERCENT = <TokenType.PERCENT: 'PERCENT'>
PIVOT = <TokenType.PIVOT: 'PIVOT'>
PLACEHOLDER = <TokenType.PLACEHOLDER: 'PLACEHOLDER'>
PRAGMA = <TokenType.PRAGMA: 'PRAGMA'>
PRIMARY_KEY = <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>
PROCEDURE = <TokenType.PROCEDURE: 'PROCEDURE'>
PROPERTIES = <TokenType.PROPERTIES: 'PROPERTIES'>
PSEUDO_TYPE = <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>
QUALIFY = <TokenType.QUALIFY: 'QUALIFY'>
QUOTE = <TokenType.QUOTE: 'QUOTE'>
RANGE = <TokenType.RANGE: 'RANGE'>
RECURSIVE = <TokenType.RECURSIVE: 'RECURSIVE'>
REFRESH = <TokenType.REFRESH: 'REFRESH'>
REPLACE = <TokenType.REPLACE: 'REPLACE'>
RETURNING = <TokenType.RETURNING: 'RETURNING'>
REFERENCES = <TokenType.REFERENCES: 'REFERENCES'>
RIGHT = <TokenType.RIGHT: 'RIGHT'>
RLIKE = <TokenType.RLIKE: 'RLIKE'>
ROLLBACK = <TokenType.ROLLBACK: 'ROLLBACK'>
ROLLUP = <TokenType.ROLLUP: 'ROLLUP'>
ROW = <TokenType.ROW: 'ROW'>
ROWS = <TokenType.ROWS: 'ROWS'>
SELECT = <TokenType.SELECT: 'SELECT'>
SEMI = <TokenType.SEMI: 'SEMI'>
SEPARATOR = <TokenType.SEPARATOR: 'SEPARATOR'>
SERDE_PROPERTIES = <TokenType.SERDE_PROPERTIES: 'SERDE_PROPERTIES'>
SET = <TokenType.SET: 'SET'>
SETTINGS = <TokenType.SETTINGS: 'SETTINGS'>
SHOW = <TokenType.SHOW: 'SHOW'>
SIMILAR_TO = <TokenType.SIMILAR_TO: 'SIMILAR_TO'>
SOME = <TokenType.SOME: 'SOME'>
SORT_BY = <TokenType.SORT_BY: 'SORT_BY'>
START_WITH = <TokenType.START_WITH: 'START_WITH'>
STRUCT = <TokenType.STRUCT: 'STRUCT'>
TABLE_SAMPLE = <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>
TEMPORARY = <TokenType.TEMPORARY: 'TEMPORARY'>
TOP = <TokenType.TOP: 'TOP'>
THEN = <TokenType.THEN: 'THEN'>
TRUE = <TokenType.TRUE: 'TRUE'>
UNCACHE = <TokenType.UNCACHE: 'UNCACHE'>
UNION = <TokenType.UNION: 'UNION'>
UNNEST = <TokenType.UNNEST: 'UNNEST'>
UNPIVOT = <TokenType.UNPIVOT: 'UNPIVOT'>
UPDATE = <TokenType.UPDATE: 'UPDATE'>
USE = <TokenType.USE: 'USE'>
USING = <TokenType.USING: 'USING'>
VALUES = <TokenType.VALUES: 'VALUES'>
VIEW = <TokenType.VIEW: 'VIEW'>
VOLATILE = <TokenType.VOLATILE: 'VOLATILE'>
WHEN = <TokenType.WHEN: 'WHEN'>
WHERE = <TokenType.WHERE: 'WHERE'>
WINDOW = <TokenType.WINDOW: 'WINDOW'>
WITH = <TokenType.WITH: 'WITH'>
UNIQUE = <TokenType.UNIQUE: 'UNIQUE'>
VERSION_SNAPSHOT = <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>
TIMESTAMP_SNAPSHOT = <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>

##### Inherited Members

enum.Enum
  name
  value

class Token: View Source

    351class Token:
    352    __slots__ = ("token_type", "text", "line", "col", "start", "end", "comments")
    353
    354    @classmethod
    355    def number(cls, number: int) -> Token:
    356        """Returns a NUMBER token with `number` as its text."""
    357        return cls(TokenType.NUMBER, str(number))
    358
    359    @classmethod
    360    def string(cls, string: str) -> Token:
    361        """Returns a STRING token with `string` as its text."""
    362        return cls(TokenType.STRING, string)
    363
    364    @classmethod
    365    def identifier(cls, identifier: str) -> Token:
    366        """Returns an IDENTIFIER token with `identifier` as its text."""
    367        return cls(TokenType.IDENTIFIER, identifier)
    368
    369    @classmethod
    370    def var(cls, var: str) -> Token:
    371        """Returns an VAR token with `var` as its text."""
    372        return cls(TokenType.VAR, var)
    373
    374    def __init__(
    375        self,
    376        token_type: TokenType,
    377        text: str,
    378        line: int = 1,
    379        col: int = 1,
    380        start: int = 0,
    381        end: int = 0,
    382        comments: t.Optional[t.List[str]] = None,
    383    ) -> None:
    384        """Token initializer.
    385
    386        Args:
    387            token_type: The TokenType Enum.
    388            text: The text of the token.
    389            line: The line that the token ends on.
    390            col: The column that the token ends on.
    391            start: The start index of the token.
    392            end: The ending index of the token.
    393            comments: The comments to attach to the token.
    394        """
    395        self.token_type = token_type
    396        self.text = text
    397        self.line = line
    398        self.col = col
    399        self.start = start
    400        self.end = end
    401        self.comments = [] if comments is None else comments
    402
    403    def __repr__(self) -> str:
    404        attributes = ", ".join(f"{k}: {getattr(self, k)}" for k in self.__slots__)
    405        return f"<Token {attributes}>"

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

    374    def __init__(
    375        self,
    376        token_type: TokenType,
    377        text: str,
    378        line: int = 1,
    379        col: int = 1,
    380        start: int = 0,
    381        end: int = 0,
    382        comments: t.Optional[t.List[str]] = None,
    383    ) -> None:
    384        """Token initializer.
    385
    386        Args:
    387            token_type: The TokenType Enum.
    388            text: The text of the token.
    389            line: The line that the token ends on.
    390            col: The column that the token ends on.
    391            start: The start index of the token.
    392            end: The ending index of the token.
    393            comments: The comments to attach to the token.
    394        """
    395        self.token_type = token_type
    396        self.text = text
    397        self.line = line
    398        self.col = col
    399        self.start = start
    400        self.end = end
    401        self.comments = [] if comments is None else comments

Token initializer.

###### Arguments:

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

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

    354    @classmethod
    355    def number(cls, number: int) -> Token:
    356        """Returns a NUMBER token with `number` as its text."""
    357        return cls(TokenType.NUMBER, str(number))

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

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

    359    @classmethod
    360    def string(cls, string: str) -> Token:
    361        """Returns a STRING token with `string` as its text."""
    362        return cls(TokenType.STRING, string)

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

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

    364    @classmethod
    365    def identifier(cls, identifier: str) -> Token:
    366        """Returns an IDENTIFIER token with `identifier` as its text."""
    367        return cls(TokenType.IDENTIFIER, identifier)

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

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

    369    @classmethod
    370    def var(cls, var: str) -> Token:
    371        """Returns an VAR token with `var` as its text."""
    372        return cls(TokenType.VAR, var)

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

token_type
text
line
col
start
end
comments
class Tokenizer: View Source

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

Tokenizer( dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None) View Source

    828    def __init__(self, dialect: DialectType = None) -> None:
    829        from sqlglot.dialects import Dialect
    830
    831        self.dialect = Dialect.get_or_raise(dialect)
    832        self.reset()

SINGLE_TOKENS = {'(': <TokenType.L_PAREN: 'L_PAREN'>, ')': <TokenType.R_PAREN: 'R_PAREN'>, '[': <TokenType.L_BRACKET: 'L_BRACKET'>, ']': <TokenType.R_BRACKET: 'R_BRACKET'>, '{': <TokenType.L_BRACE: 'L_BRACE'>, '}': <TokenType.R_BRACE: 'R_BRACE'>, '&': <TokenType.AMP: 'AMP'>, '^': <TokenType.CARET: 'CARET'>, ':': <TokenType.COLON: 'COLON'>, ',': <TokenType.COMMA: 'COMMA'>, '.': <TokenType.DOT: 'DOT'>, '-': <TokenType.DASH: 'DASH'>, '=': <TokenType.EQ: 'EQ'>, '>': <TokenType.GT: 'GT'>, '<': <TokenType.LT: 'LT'>, '%': <TokenType.MOD: 'MOD'>, '!': <TokenType.NOT: 'NOT'>, '|': <TokenType.PIPE: 'PIPE'>, '+': <TokenType.PLUS: 'PLUS'>, ';': <TokenType.SEMICOLON: 'SEMICOLON'>, '/': <TokenType.SLASH: 'SLASH'>, '\\': <TokenType.BACKSLASH: 'BACKSLASH'>, '*': <TokenType.STAR: 'STAR'>, '~': <TokenType.TILDA: 'TILDA'>, '?': <TokenType.PLACEHOLDER: 'PLACEHOLDER'>, '@': <TokenType.PARAMETER: 'PARAMETER'>, "'": <TokenType.QUOTE: 'QUOTE'>, '`': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '"': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '#': <TokenType.HASH: 'HASH'>}
BIT_STRINGS: List[Union[str, Tuple[str, str]]] = []
BYTE_STRINGS: List[Union[str, Tuple[str, str]]] = []
HEX_STRINGS: List[Union[str, Tuple[str, str]]] = []
RAW_STRINGS: List[Union[str, Tuple[str, str]]] = []
HEREDOC_STRINGS: List[Union[str, Tuple[str, str]]] = []
IDENTIFIERS: List[Union[str, Tuple[str, str]]] = ['"']
IDENTIFIER_ESCAPES = ['"']
QUOTES: List[Union[str, Tuple[str, str]]] = ["'"]
STRING_ESCAPES = ["'"]
VAR_SINGLE_TOKENS: Set[str] = set()
KEYWORDS: Dict[str, TokenType] = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, ':=': <TokenType.COLON_EQ: 'COLON_EQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, '??': <TokenType.DQMARK: 'DQMARK'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'KILL': <TokenType.KILL: 'KILL'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'START WITH': <TokenType.START_WITH: 'START_WITH'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'MEDIUMINT': <TokenType.MEDIUMINT: 'MEDIUMINT'>, 'INT1': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'INT16': <TokenType.SMALLINT: 'SMALLINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT128': <TokenType.INT128: 'INT128'>, 'HUGEINT': <TokenType.INT128: 'INT128'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'INT32': <TokenType.INT: 'INT'>, 'INT64': <TokenType.BIGINT: 'BIGINT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.TINYINT: 'TINYINT'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'COPY': <TokenType.COMMAND: 'COMMAND'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'TRUNCATE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>}
WHITE_SPACE: Dict[Optional[str], TokenType] = {' ': <TokenType.SPACE: 'SPACE'>, '\t': <TokenType.SPACE: 'SPACE'>, '\n': <TokenType.BREAK: 'BREAK'>, '\r': <TokenType.BREAK: 'BREAK'>}
COMMANDS = {<TokenType.SHOW: 'SHOW'>, <TokenType.FETCH: 'FETCH'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.COMMAND: 'COMMAND'>}
COMMAND_PREFIX_TOKENS = {<TokenType.BEGIN: 'BEGIN'>, <TokenType.SEMICOLON: 'SEMICOLON'>}
NUMERIC_LITERALS: Dict[str, str] = {}
ENCODE: Optional[str] = None
COMMENTS = ['--', ('/*', '*/')]
dialect
def reset(self) -> None: View Source

    834    def reset(self) -> None:
    835        self.sql = ""
    836        self.size = 0
    837        self.tokens: t.List[Token] = []
    838        self._start = 0
    839        self._current = 0
    840        self._line = 1
    841        self._col = 0
    842        self._comments: t.List[str] = []
    843
    844        self._char = ""
    845        self._end = False
    846        self._peek = ""
    847        self._prev_token_line = -1

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

    849    def tokenize(self, sql: str) -> t.List[Token]:
    850        """Returns a list of tokens corresponding to the SQL string `sql`."""
    851        self.reset()
    852        self.sql = sql
    853        self.size = len(sql)
    854
    855        try:
    856            self._scan()
    857        except Exception as e:
    858            start = max(self._current - 50, 0)
    859            end = min(self._current + 50, self.size - 1)
    860            context = self.sql[start:end]
    861            raise TokenError(f"Error tokenizing '{context}'") from e
    862
    863        return self.tokens

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

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

    948    def peek(self, i: int = 0) -> str:
    949        i = self._current + i
    950        if i < self.size:
    951            return self.sql[i]
    952        return ""

size
sql
tokens