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

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

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

An enumeration.

L_PAREN = <TokenType.L_PAREN: 'L_PAREN'>
R_PAREN = <TokenType.R_PAREN: 'R_PAREN'>
L_BRACKET = <TokenType.L_BRACKET: 'L_BRACKET'>
R_BRACKET = <TokenType.R_BRACKET: 'R_BRACKET'>
L_BRACE = <TokenType.L_BRACE: 'L_BRACE'>
R_BRACE = <TokenType.R_BRACE: 'R_BRACE'>
COMMA = <TokenType.COMMA: 'COMMA'>
DOT = <TokenType.DOT: 'DOT'>
DASH = <TokenType.DASH: 'DASH'>
PLUS = <TokenType.PLUS: 'PLUS'>
COLON = <TokenType.COLON: 'COLON'>
DCOLON = <TokenType.DCOLON: 'DCOLON'>
SEMICOLON = <TokenType.SEMICOLON: 'SEMICOLON'>
STAR = <TokenType.STAR: 'STAR'>
BACKSLASH = <TokenType.BACKSLASH: 'BACKSLASH'>
SLASH = <TokenType.SLASH: 'SLASH'>
LT = <TokenType.LT: 'LT'>
LTE = <TokenType.LTE: 'LTE'>
GT = <TokenType.GT: 'GT'>
GTE = <TokenType.GTE: 'GTE'>
NOT = <TokenType.NOT: 'NOT'>
EQ = <TokenType.EQ: 'EQ'>
NEQ = <TokenType.NEQ: 'NEQ'>
NULLSAFE_EQ = <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>
AND = <TokenType.AND: 'AND'>
OR = <TokenType.OR: 'OR'>
AMP = <TokenType.AMP: 'AMP'>
DPIPE = <TokenType.DPIPE: 'DPIPE'>
PIPE = <TokenType.PIPE: 'PIPE'>
CARET = <TokenType.CARET: 'CARET'>
TILDA = <TokenType.TILDA: 'TILDA'>
ARROW = <TokenType.ARROW: 'ARROW'>
DARROW = <TokenType.DARROW: 'DARROW'>
FARROW = <TokenType.FARROW: 'FARROW'>
HASH = <TokenType.HASH: 'HASH'>
HASH_ARROW = <TokenType.HASH_ARROW: 'HASH_ARROW'>
DHASH_ARROW = <TokenType.DHASH_ARROW: 'DHASH_ARROW'>
LR_ARROW = <TokenType.LR_ARROW: 'LR_ARROW'>
DOLLAR = <TokenType.DOLLAR: 'DOLLAR'>
PARAMETER = <TokenType.PARAMETER: 'PARAMETER'>
SESSION_PARAMETER = <TokenType.SESSION_PARAMETER: 'SESSION_PARAMETER'>
NATIONAL = <TokenType.NATIONAL: 'NATIONAL'>
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'>
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'>
BOOLEAN = <TokenType.BOOLEAN: 'BOOLEAN'>
TINYINT = <TokenType.TINYINT: 'TINYINT'>
SMALLINT = <TokenType.SMALLINT: 'SMALLINT'>
INT = <TokenType.INT: 'INT'>
BIGINT = <TokenType.BIGINT: 'BIGINT'>
FLOAT = <TokenType.FLOAT: 'FLOAT'>
DOUBLE = <TokenType.DOUBLE: 'DOUBLE'>
DECIMAL = <TokenType.DECIMAL: 'DECIMAL'>
CHAR = <TokenType.CHAR: 'CHAR'>
NCHAR = <TokenType.NCHAR: 'NCHAR'>
VARCHAR = <TokenType.VARCHAR: 'VARCHAR'>
NVARCHAR = <TokenType.NVARCHAR: 'NVARCHAR'>
TEXT = <TokenType.TEXT: 'TEXT'>
MEDIUMTEXT = <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <TokenType.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <TokenType.LONGBLOB: 'LONGBLOB'>
BINARY = <TokenType.BINARY: 'BINARY'>
VARBINARY = <TokenType.VARBINARY: 'VARBINARY'>
JSON = <TokenType.JSON: 'JSON'>
JSONB = <TokenType.JSONB: 'JSONB'>
TIME = <TokenType.TIME: 'TIME'>
TIMESTAMP = <TokenType.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
DATETIME = <TokenType.DATETIME: 'DATETIME'>
DATE = <TokenType.DATE: 'DATE'>
UUID = <TokenType.UUID: 'UUID'>
GEOGRAPHY = <TokenType.GEOGRAPHY: 'GEOGRAPHY'>
NULLABLE = <TokenType.NULLABLE: 'NULLABLE'>
GEOMETRY = <TokenType.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <TokenType.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <TokenType.HSTORE: 'HSTORE'>
SUPER = <TokenType.SUPER: 'SUPER'>
SERIAL = <TokenType.SERIAL: 'SERIAL'>
SMALLSERIAL = <TokenType.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <TokenType.BIGSERIAL: 'BIGSERIAL'>
XML = <TokenType.XML: 'XML'>
UNIQUEIDENTIFIER = <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
MONEY = <TokenType.MONEY: 'MONEY'>
SMALLMONEY = <TokenType.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <TokenType.ROWVERSION: 'ROWVERSION'>
IMAGE = <TokenType.IMAGE: 'IMAGE'>
VARIANT = <TokenType.VARIANT: 'VARIANT'>
OBJECT = <TokenType.OBJECT: 'OBJECT'>
INET = <TokenType.INET: 'INET'>
ALIAS = <TokenType.ALIAS: 'ALIAS'>
ALTER = <TokenType.ALTER: 'ALTER'>
ALWAYS = <TokenType.ALWAYS: 'ALWAYS'>
ALL = <TokenType.ALL: 'ALL'>
ANTI = <TokenType.ANTI: 'ANTI'>
ANY = <TokenType.ANY: 'ANY'>
APPLY = <TokenType.APPLY: 'APPLY'>
ARRAY = <TokenType.ARRAY: 'ARRAY'>
ASC = <TokenType.ASC: 'ASC'>
ASOF = <TokenType.ASOF: 'ASOF'>
AT_TIME_ZONE = <TokenType.AT_TIME_ZONE: 'AT_TIME_ZONE'>
AUTO_INCREMENT = <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>
BEGIN = <TokenType.BEGIN: 'BEGIN'>
BETWEEN = <TokenType.BETWEEN: 'BETWEEN'>
BOTH = <TokenType.BOTH: 'BOTH'>
BUCKET = <TokenType.BUCKET: 'BUCKET'>
BY_DEFAULT = <TokenType.BY_DEFAULT: 'BY_DEFAULT'>
CACHE = <TokenType.CACHE: 'CACHE'>
CASCADE = <TokenType.CASCADE: 'CASCADE'>
CASE = <TokenType.CASE: 'CASE'>
CHARACTER_SET = <TokenType.CHARACTER_SET: 'CHARACTER_SET'>
CLUSTER_BY = <TokenType.CLUSTER_BY: 'CLUSTER_BY'>
COLLATE = <TokenType.COLLATE: 'COLLATE'>
COMMAND = <TokenType.COMMAND: 'COMMAND'>
COMMENT = <TokenType.COMMENT: 'COMMENT'>
COMMIT = <TokenType.COMMIT: 'COMMIT'>
COMPOUND = <TokenType.COMPOUND: 'COMPOUND'>
CONSTRAINT = <TokenType.CONSTRAINT: 'CONSTRAINT'>
CREATE = <TokenType.CREATE: 'CREATE'>
CROSS = <TokenType.CROSS: 'CROSS'>
CUBE = <TokenType.CUBE: 'CUBE'>
CURRENT_DATE = <TokenType.CURRENT_DATE: 'CURRENT_DATE'>
CURRENT_DATETIME = <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>
CURRENT_ROW = <TokenType.CURRENT_ROW: 'CURRENT_ROW'>
CURRENT_TIME = <TokenType.CURRENT_TIME: 'CURRENT_TIME'>
CURRENT_TIMESTAMP = <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>
DEFAULT = <TokenType.DEFAULT: 'DEFAULT'>
DELETE = <TokenType.DELETE: 'DELETE'>
DESC = <TokenType.DESC: 'DESC'>
DESCRIBE = <TokenType.DESCRIBE: 'DESCRIBE'>
DISTINCT = <TokenType.DISTINCT: 'DISTINCT'>
DISTINCT_FROM = <TokenType.DISTINCT_FROM: 'DISTINCT_FROM'>
DISTRIBUTE_BY = <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>
DIV = <TokenType.DIV: 'DIV'>
DROP = <TokenType.DROP: 'DROP'>
ELSE = <TokenType.ELSE: 'ELSE'>
END = <TokenType.END: 'END'>
ESCAPE = <TokenType.ESCAPE: 'ESCAPE'>
EXCEPT = <TokenType.EXCEPT: 'EXCEPT'>
EXECUTE = <TokenType.EXECUTE: 'EXECUTE'>
EXISTS = <TokenType.EXISTS: 'EXISTS'>
FALSE = <TokenType.FALSE: 'FALSE'>
FETCH = <TokenType.FETCH: 'FETCH'>
FILTER = <TokenType.FILTER: 'FILTER'>
FINAL = <TokenType.FINAL: 'FINAL'>
FIRST = <TokenType.FIRST: 'FIRST'>
FOLLOWING = <TokenType.FOLLOWING: 'FOLLOWING'>
FOR = <TokenType.FOR: 'FOR'>
FOREIGN_KEY = <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>
FORMAT = <TokenType.FORMAT: 'FORMAT'>
FROM = <TokenType.FROM: 'FROM'>
FULL = <TokenType.FULL: 'FULL'>
FUNCTION = <TokenType.FUNCTION: 'FUNCTION'>
GLOB = <TokenType.GLOB: 'GLOB'>
GLOBAL = <TokenType.GLOBAL: 'GLOBAL'>
GROUP_BY = <TokenType.GROUP_BY: 'GROUP_BY'>
GROUPING_SETS = <TokenType.GROUPING_SETS: 'GROUPING_SETS'>
HAVING = <TokenType.HAVING: 'HAVING'>
HINT = <TokenType.HINT: 'HINT'>
IF = <TokenType.IF: 'IF'>
IGNORE_NULLS = <TokenType.IGNORE_NULLS: 'IGNORE_NULLS'>
ILIKE = <TokenType.ILIKE: 'ILIKE'>
ILIKE_ANY = <TokenType.ILIKE_ANY: 'ILIKE_ANY'>
IN = <TokenType.IN: 'IN'>
INDEX = <TokenType.INDEX: 'INDEX'>
INNER = <TokenType.INNER: 'INNER'>
INSERT = <TokenType.INSERT: 'INSERT'>
INTERSECT = <TokenType.INTERSECT: 'INTERSECT'>
INTERVAL = <TokenType.INTERVAL: 'INTERVAL'>
INTO = <TokenType.INTO: 'INTO'>
INTRODUCER = <TokenType.INTRODUCER: 'INTRODUCER'>
IRLIKE = <TokenType.IRLIKE: 'IRLIKE'>
IS = <TokenType.IS: 'IS'>
ISNULL = <TokenType.ISNULL: 'ISNULL'>
JOIN = <TokenType.JOIN: 'JOIN'>
LANGUAGE = <TokenType.LANGUAGE: 'LANGUAGE'>
LATERAL = <TokenType.LATERAL: 'LATERAL'>
LAZY = <TokenType.LAZY: 'LAZY'>
LEADING = <TokenType.LEADING: 'LEADING'>
LEFT = <TokenType.LEFT: 'LEFT'>
LIKE = <TokenType.LIKE: 'LIKE'>
LIKE_ANY = <TokenType.LIKE_ANY: 'LIKE_ANY'>
LIMIT = <TokenType.LIMIT: 'LIMIT'>
LOAD_DATA = <TokenType.LOAD_DATA: 'LOAD_DATA'>
LOCAL = <TokenType.LOCAL: 'LOCAL'>
MAP = <TokenType.MAP: 'MAP'>
MATCH_RECOGNIZE = <TokenType.MATCH_RECOGNIZE: 'MATCH_RECOGNIZE'>
MATERIALIZED = <TokenType.MATERIALIZED: 'MATERIALIZED'>
MERGE = <TokenType.MERGE: 'MERGE'>
MOD = <TokenType.MOD: 'MOD'>
NATURAL = <TokenType.NATURAL: 'NATURAL'>
NEXT = <TokenType.NEXT: 'NEXT'>
NO_ACTION = <TokenType.NO_ACTION: 'NO_ACTION'>
NOTNULL = <TokenType.NOTNULL: 'NOTNULL'>
NULL = <TokenType.NULL: 'NULL'>
NULLS_FIRST = <TokenType.NULLS_FIRST: 'NULLS_FIRST'>
NULLS_LAST = <TokenType.NULLS_LAST: 'NULLS_LAST'>
OFFSET = <TokenType.OFFSET: 'OFFSET'>
ON = <TokenType.ON: 'ON'>
ONLY = <TokenType.ONLY: 'ONLY'>
OPTIONS = <TokenType.OPTIONS: 'OPTIONS'>
ORDER_BY = <TokenType.ORDER_BY: 'ORDER_BY'>
ORDERED = <TokenType.ORDERED: 'ORDERED'>
ORDINALITY = <TokenType.ORDINALITY: 'ORDINALITY'>
OUTER = <TokenType.OUTER: 'OUTER'>
OUT_OF = <TokenType.OUT_OF: 'OUT_OF'>
OVER = <TokenType.OVER: 'OVER'>
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'>
PRECEDING = <TokenType.PRECEDING: 'PRECEDING'>
PRIMARY_KEY = <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>
PROCEDURE = <TokenType.PROCEDURE: 'PROCEDURE'>
PROPERTIES = <TokenType.PROPERTIES: 'PROPERTIES'>
PSEUDO_TYPE = <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>
QUALIFY = <TokenType.QUALIFY: 'QUALIFY'>
QUOTE = <TokenType.QUOTE: 'QUOTE'>
RANGE = <TokenType.RANGE: 'RANGE'>
RECURSIVE = <TokenType.RECURSIVE: 'RECURSIVE'>
REPLACE = <TokenType.REPLACE: 'REPLACE'>
RESPECT_NULLS = <TokenType.RESPECT_NULLS: 'RESPECT_NULLS'>
RETURNING = <TokenType.RETURNING: 'RETURNING'>
REFERENCES = <TokenType.REFERENCES: 'REFERENCES'>
RIGHT = <TokenType.RIGHT: 'RIGHT'>
RLIKE = <TokenType.RLIKE: 'RLIKE'>
ROLLBACK = <TokenType.ROLLBACK: 'ROLLBACK'>
ROLLUP = <TokenType.ROLLUP: 'ROLLUP'>
ROW = <TokenType.ROW: 'ROW'>
ROWS = <TokenType.ROWS: 'ROWS'>
SEED = <TokenType.SEED: 'SEED'>
SELECT = <TokenType.SELECT: 'SELECT'>
SEMI = <TokenType.SEMI: 'SEMI'>
SEPARATOR = <TokenType.SEPARATOR: 'SEPARATOR'>
SERDE_PROPERTIES = <TokenType.SERDE_PROPERTIES: 'SERDE_PROPERTIES'>
SET = <TokenType.SET: 'SET'>
SHOW = <TokenType.SHOW: 'SHOW'>
SIMILAR_TO = <TokenType.SIMILAR_TO: 'SIMILAR_TO'>
SOME = <TokenType.SOME: 'SOME'>
SORTKEY = <TokenType.SORTKEY: 'SORTKEY'>
SORT_BY = <TokenType.SORT_BY: 'SORT_BY'>
STRUCT = <TokenType.STRUCT: 'STRUCT'>
TABLE_SAMPLE = <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>
TEMPORARY = <TokenType.TEMPORARY: 'TEMPORARY'>
TOP = <TokenType.TOP: 'TOP'>
THEN = <TokenType.THEN: 'THEN'>
TRAILING = <TokenType.TRAILING: 'TRAILING'>
TRUE = <TokenType.TRUE: 'TRUE'>
UNBOUNDED = <TokenType.UNBOUNDED: 'UNBOUNDED'>
UNCACHE = <TokenType.UNCACHE: 'UNCACHE'>
UNION = <TokenType.UNION: 'UNION'>
UNLOGGED = <TokenType.UNLOGGED: 'UNLOGGED'>
UNNEST = <TokenType.UNNEST: 'UNNEST'>
UNPIVOT = <TokenType.UNPIVOT: 'UNPIVOT'>
UPDATE = <TokenType.UPDATE: 'UPDATE'>
USE = <TokenType.USE: 'USE'>
USING = <TokenType.USING: 'USING'>
VALUES = <TokenType.VALUES: 'VALUES'>
VIEW = <TokenType.VIEW: 'VIEW'>
VOLATILE = <TokenType.VOLATILE: 'VOLATILE'>
WHEN = <TokenType.WHEN: 'WHEN'>
WHERE = <TokenType.WHERE: 'WHERE'>
WINDOW = <TokenType.WINDOW: 'WINDOW'>
WITH = <TokenType.WITH: 'WITH'>
WITH_TIME_ZONE = <TokenType.WITH_TIME_ZONE: 'WITH_TIME_ZONE'>
WITH_LOCAL_TIME_ZONE = <TokenType.WITH_LOCAL_TIME_ZONE: 'WITH_LOCAL_TIME_ZONE'>
WITHIN_GROUP = <TokenType.WITHIN_GROUP: 'WITHIN_GROUP'>
WITHOUT_TIME_ZONE = <TokenType.WITHOUT_TIME_ZONE: 'WITHOUT_TIME_ZONE'>
UNIQUE = <TokenType.UNIQUE: 'UNIQUE'>

##### Inherited Members

enum.Enum
  name
  value

class Token: View Source

    305class Token:
    306    __slots__ = ("token_type", "text", "line", "col", "comments")
    307
    308    @classmethod
    309    def number(cls, number: int) -> Token:
    310        """Returns a NUMBER token with `number` as its text."""
    311        return cls(TokenType.NUMBER, str(number))
    312
    313    @classmethod
    314    def string(cls, string: str) -> Token:
    315        """Returns a STRING token with `string` as its text."""
    316        return cls(TokenType.STRING, string)
    317
    318    @classmethod
    319    def identifier(cls, identifier: str) -> Token:
    320        """Returns an IDENTIFIER token with `identifier` as its text."""
    321        return cls(TokenType.IDENTIFIER, identifier)
    322
    323    @classmethod
    324    def var(cls, var: str) -> Token:
    325        """Returns an VAR token with `var` as its text."""
    326        return cls(TokenType.VAR, var)
    327
    328    def __init__(
    329        self,
    330        token_type: TokenType,
    331        text: str,
    332        line: int = 1,
    333        col: int = 1,
    334        comments: t.List[str] = [],
    335    ) -> None:
    336        self.token_type = token_type
    337        self.text = text
    338        self.line = line
    339        self.col = max(col - len(text), 1)
    340        self.comments = comments
    341
    342    def __repr__(self) -> str:
    343        attributes = ", ".join(f"{k}: {getattr(self, k)}" for k in self.__slots__)
    344        return f"<Token {attributes}>"

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

    328    def __init__(
    329        self,
    330        token_type: TokenType,
    331        text: str,
    332        line: int = 1,
    333        col: int = 1,
    334        comments: t.List[str] = [],
    335    ) -> None:
    336        self.token_type = token_type
    337        self.text = text
    338        self.line = line
    339        self.col = max(col - len(text), 1)
    340        self.comments = comments

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

    308    @classmethod
    309    def number(cls, number: int) -> Token:
    310        """Returns a NUMBER token with `number` as its text."""
    311        return cls(TokenType.NUMBER, str(number))

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

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

    313    @classmethod
    314    def string(cls, string: str) -> Token:
    315        """Returns a STRING token with `string` as its text."""
    316        return cls(TokenType.STRING, string)

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

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

    318    @classmethod
    319    def identifier(cls, identifier: str) -> Token:
    320        """Returns an IDENTIFIER token with `identifier` as its text."""
    321        return cls(TokenType.IDENTIFIER, identifier)

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

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

    323    @classmethod
    324    def var(cls, var: str) -> Token:
    325        """Returns an VAR token with `var` as its text."""
    326        return cls(TokenType.VAR, var)

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

class Tokenizer: View Source

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

def reset(self) -> None: View Source

    754    def reset(self) -> None:
    755        self.sql = ""
    756        self.size = 0
    757        self.tokens: t.List[Token] = []
    758        self._start = 0
    759        self._current = 0
    760        self._line = 1
    761        self._col = 1
    762        self._comments: t.List[str] = []
    763
    764        self._char = None
    765        self._end = None
    766        self._peek = None
    767        self._prev_token_line = -1
    768        self._prev_token_comments: t.List[str] = []
    769        self._prev_token_type = None

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

    771    def tokenize(self, sql: str) -> t.List[Token]:
    772        """Returns a list of tokens corresponding to the SQL string `sql`."""
    773        self.reset()
    774        self.sql = sql
    775        self.size = len(sql)
    776        self._scan()
    777        return self.tokens

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