未提供项目说明
hephaestus的Python项目详细描述
赫菲斯托斯
简介
Hephaestus是一个静态解析SQL查询并返回AST的库。在
这对于不同的目的很有用,例如:
- 统计信息,即使用的表或字段、连接的提示、过滤条件等
- 部分或完全查询比较
- 查询类型检测
SQL语法是针对Exasol的,但是可以很容易地移植它来支持其他语法。在
Hephaestus的解析器构建在Rust中,使用lalrpop板条箱来定义语法,vervolg用作SQL语法的基础。在
安装
要安装包,您需要安装nightly
版本的Rust编译器:
curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain=nightly
然后直接从Github安装包:
^{pr2}$Note: until version 0.8 of
pyo3
you need to have thepython
binary available in yourPATH
; on some systems it will fail because onlypython3
is present. In this case install the Python 2 package.
使用
解析
Hephaestus公开了一个parse()
函数,该函数给定一个SQl字符串,返回一个表示AST格式的SQl的字典:
>>>importhephaestus>>>hephaestus.parse("SELECT 1"){'_type':'SelectStatement','common':[],'expr':{'_type':'QuerySetExpression','mode':{'_type':'SelectAll'},'columns':{'_type':'ListResultColumn','values':[{'_type':'ExprResultColumn','expr':{'_type':'NumericLiteral','num':'1'},'rename':None}]},'from':[],'where_expr':None,'group_by':None},'order_by':[],'limit':None}
字典的每个节点都有一个表示节点类型的_type
键,即SelectStatement
,以及一系列特定于节点类型的键,这些键可以包含标量值,如str
,int
,None
,一个表示节点或标量值或节点列表的字典。在
For a full list of node types see
src/ast.rs
andsrc/ast_py.rs
.
遍历
解析传入的SQL表达式只是第一步,如果没有遍历树和检查节点的能力,它就没有多大用处。在
Hephaestus提供了一个类来遍历树,并为遍历过程中遇到的每个节点调用一个方法,而不是从头开始编写代码来遍历字典嵌套结构。在
只需从Visitor
类继承并实现visit_<node_type>
形式的方法,其中<node_type>
是{
此示例显示如何检查给定的SQL语句是否正在从DUAL
表进行查询:
fromtypingimportDictfromhephaestus.walkimportVisitorclassMyVisitor(Visitor):has_dual_table=Falsedefvisit_NamedTableExpression(self,attr:str,node:Dict):self.has_dual_table=node["name"]==["dual"]visitor=MyVisitor("SELECT 1 FROM dual")visitor.walk()assertvisitor.has_dual_tableisTrue
当到达NamedTableExpression
节点时,visit_NamedTableExpression
方法被调用并接收父节点的属性名attr
和节点本身。在
测试
有两组测试,一组用于Rust,另一组用于Python代码。在
Note: Unfortunately at the moment it's not possible to execute both test suites with the same
Cargo.toml
(looks like that theextension-module
feature inpyo3
interfere with the way the tests are linked with the Rust library), so it's necessary to switch to a different config before running the them.
要运行生锈测试:
make test_rust
要运行Python测试:
make test_py
贡献
如果您想为Hephaestus项目提供帮助以扩展语法,请遵循以下步骤:
- 使用
make rust
切换到纯锈Cargo.toml
- 在
src/tests
中编写一个测试来覆盖这些案例 - 扩展
src/sql.lalrpop
中的语法;请参考LALR Book - 将相对AST注释添加到
src/ast.rs
- 在某些情况下,比如定义一个新的Rust枚举器,有必要添加一个从Rust类型到Python兼容类型的显式转换;在这种情况下,将相关代码添加到
src/ast_py.rs
注意事项
- 不是所有的Exasol语法都支持,大部分函数和语句都需要实现
- 尽管
parse()
函数返回的AST现在可以随意操作,但是没有办法取回SQL字符串
- 项目
标签: