5

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.

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

Comments

-1

This library can parse and generate SQL https://code.google.com/p/python-sql/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.