Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse SQL Queries and sub queries using sqlparser into python

Tags:

python-2.7

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.

like image 711
Bhumi Thakkar Avatar asked Oct 01 '22 08:10

Bhumi Thakkar


1 Answers

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)
like image 144
alecxe Avatar answered Oct 05 '22 05:10

alecxe