How Can I List All Tables Involved In Sqlalchemy Statements
How can i list all tables involved in SQLAlchemy statements ? let assume we have the following query query = session.query(Address).filter(Address.person == person) how can list t
Solution 1:
you can get all tables from locate_all_froms, something like this
from sqlalchemy import Table
from sqlalchemy.sql.selectable import Alias
tables = set()
for f in query.statement.locate_all_froms():
ifisinstance(f, Table):
tables.add(f)
elifisinstance(f, Alias):
tables.add(f.element)
Solution 2:
r-m-n answer is good , but it doesn't handle all cases , sub queries ,delete statements , exist statements etc
here is a general way to extract all tables
from sqlalchemy.sql.visitors import ClauseVisitor
from sqlalchemy import Table
def extract_tables(sql_stmt):
tables = []
visitor = ClauseVisitor()
cluase_iter = visitor.iterate(elem)
for e in cluase_iter:
if isinstance(e, Table):
tables.append(e)
if isinstance(e, (ValuesBase, UpdateBase)):
tables.append(e.table)
return set(tables)
Post a Comment for "How Can I List All Tables Involved In Sqlalchemy Statements"