Want to parse sql join query, select sub query into python. I am using sqlparse library. But i could not parse sub query. How i can parse whole query.
e.g:
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
I could not parse for this select name from res_partner where id = 1
sub query.
Not so elegant, but works:
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
prints:
(select name from res_partner where id = 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With