"""Base class for all other classes in this module.
It represents a single token and has two instance attributes:
``value`` is the unchanged value of the token and ``ttype`` is
the type of the token.
def __init__(self, ttype, value):
value = str(value)
self.value = value
self.ttype = ttype
self.parent = None
self.is_group = False
self.is_keyword = ttype in T.Keyword
self.is_whitespace = self.ttype in T.Whitespace
self.normalized = value.upper() if self.is_keyword else value
sqlparse.sql.Token: 这是最基本的Token类,表示SQL语句中的一个原子部分,如一个单词或者符号。它包含以下属性:
- value: 该Token的实际文本内容,比如一个关键字像SELECT或一个标识符如表名。
- token_type: 表示Token类型的枚举值,比如Keyword、Identifier、Punctuation等。
- position 或 start_pos: 表示Token在原始SQL文本中的起始位置信息,有助于追踪Token的来源。
相关Token子类和概念 - sqlparse.sql.Identifier: 专门表示SQL中的标识符,如表名、列名等。这类Token可能会有额外的属性来表示是否为 quoted identifier(被引号包围的标识符)。
- sqlparse.sql.Keyword: 表示SQL关键字,如SELECT, FROM, WHERE等。
- sqlparse.sql.Punctuation: 表示SQL中的标点符号,如逗号,、分号;等。
- sqlparse.sql.Comment: 用于表示SQL中的注释内容,可以是行内注释(-- …)或块注释(/* … */)。
- sqlparse.sql.Comparison: 包含比较操作符(如=, !=, IN, BETWEEN等)以及它们两边的操作数,用于构建更复杂的表达式分析。
- sqlparse.sql.Statement: 表示整个SQL语句,通常是由多个Token和其他Statement对象组成的树状结构,便于递归遍历整个SQL语句的结构。
这里就需要引入sql解析的过程
sql -> 语法分析器(Lexer) -> Token流 -> 语法分析器(Parse) -> 抽象语法树(AST) -> 树结构(Tree Parse)
每个解析结果都会附带一个tokens 的属性,它是一个生成器,用于迭代解析后的Token序列, 包含了一些类型信息, 其中的类型信息有: