从SQLAlchemy存在查询中提取表名

时间:2017-07-03 17:08:49

标签: python sqlalchemy

如何从SQLAlchemy exists语句中提取表名 假设我们有以下代码

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class Person(Base):
    __tablename__ = 'person'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

engine = create_engine('mysql://...')
Session = sessionmaker(bind=engine)

conn = engine.connect()
session = Session(bind=conn)
query_exists = session.query(Person).exists()

如何从query_exists中提取表名?

1 个答案:

答案 0 :(得分:0)

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)