sami
sami

Reputation: 551

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 the tables that is used by this query in this case : Person , Address

Upvotes: 1

Views: 913

Answers (2)

sami
sami

Reputation: 551

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)

Upvotes: 2

r-m-n
r-m-n

Reputation: 15090

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():
    if isinstance(f, Table):
        tables.add(f)
    elif isinstance(f, Alias):
        tables.add(f.element)

Upvotes: 2

Related Questions