python-2.7 - 如何使用sqlparser将SQL查询和子查询解析为 python

我正在使用sqlparse库,但是我无法解析子查询,如何解析整个查询。

例如


query ="select id,fname,lname,address from res_users as r left join res_partner as p on p.id=r.partner_id where name = (select name from res_partner where id = 1)"

query_tokens = sqlparse.parse(query)[0].tokens

我无法解析这个select name from res_partner where id = 1子查询。

时间:

不太优雅,但有效:


import sqlparse
from sqlparse.sql import Where, Comparison, Parenthesis

query ="""
select
 id,fname,lname,address
from
 res_users as r
 left join
 res_partner as p
 on
 p.id=r.partner_id
where
 name = (select name from res_partner where id = 1)"""

query_tokens = sqlparse.parse(query)[0]
where = next(token for token in query_tokens.tokens if isinstance(token, Where))
condition = next(token for token in where.tokens if isinstance(token, Comparison))
subquery = next(token for token in condition.tokens if isinstance(token, Parenthesis))
print subquery

打印:


(select name from res_partner where id = 1)

这个库可以解析和生成SQL https://code.google.com/p/python-sql/

...