【发布时间】:2016-08-18 12:40:05
【问题描述】:
是否有任何库(最好在 Python 中)可以解析 SQL 查询(PostgreSQL 类型),并给我它们的结构化表示?有sqlparse,但这并不能让我轻松找出(比如)查询正在使用的表。我只需要支持SELECT 查询,但其中一些可能非常复杂。
【问题讨论】:
-
您能举例说明您的要求吗?
标签: python sql postgresql parsing
是否有任何库(最好在 Python 中)可以解析 SQL 查询(PostgreSQL 类型),并给我它们的结构化表示?有sqlparse,但这并不能让我轻松找出(比如)查询正在使用的表。我只需要支持SELECT 查询,但其中一些可能非常复杂。
【问题讨论】:
标签: python sql postgresql parsing
pyparsing 附带的select_parser.py 示例将为您提供语句的 ParseResults 数据结构。以下是嵌入式测试用例:
select * from xyzzy where z > 100
select * from xyzzy where z > 100 order by zz
select * from xyzzy
select z.* from xyzzy
select a, b from test_table where 1=1 and b='yes'
select a, b from test_table where 1=1 and b in (select bb from foo)
select z.a, b from test_table where 1=1 and b in (select bb from foo)
select z.a, b from test_table where 1=1 and b in (select bb from foo) order by b,c desc,d
select z.a, b from test_table left join test2_table where 1=1 and b in (select bb from foo)
select a, db.table.b as BBB from db.table where 1=1 and BBB='yes'
select a, db.table.b as BBB from test_table,db.table where 1=1 and BBB='yes'
select a, db.table.b as BBB from test_table,db.table where 1=1 and BBB='yes' limit 50
结果被结构化为输入语句的不同组件,命名字段可以像对象属性一样访问(result.table:'XYZZY'、result.where_expr:['z', '>', '100']等)。以下是前 3 次测试的结果:
select * from xyzzy where z > 100
['SELECT', ['*'], 'FROM', 'xyzzy', 'WHERE', ['z', '>', '100']]
- columns: ['*']
- from: ['xyzzy']
- table: ['xyzzy']
- where_expr: ['z', '>', '100']
select * from xyzzy where z > 100 order by zz
['SELECT', ['*'], 'FROM', 'xyzzy', 'WHERE', ['z', '>', '100'], 'ORDER', 'BY', [['zz']]]
- columns: ['*']
- from: ['xyzzy']
- order_by_terms: [['zz']]
[0]:
['zz']
- order_key: zz
- table: ['xyzzy']
- where_expr: ['z', '>', '100']
select * from xyzzy
['SELECT', ['*'], 'FROM', 'xyzzy']
- columns: ['*']
- from: ['xyzzy']
- table: ['xyzzy']
它是用 SQLite 的 SQL 方言编写的,但适应 Postgres 应该不会太糟糕。
【讨论】: