在SQLAlchemy中,当使用多个引擎(sessionmaker(binds={Base: engine})
而非sessionmaker(bind=engine)
)时,似乎CTE查询(公用表表达式)无法正确绑定。也许我做错了什么,因为我对SQLAlchemy很陌生。有没有一种(原则上的)方法可以完成这项工作?也许我可以告诉SQLAlchemy结果集使用哪个类?
以下代码直接基于Query API documentation中的示例。我添加了会话设置,并将CTE简化为仅退还零件。
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import aliased, sessionmaker
Base = declarative_base()
class Part(Base):
__tablename__ = 'part'
part = Column(String, primary_key=True)
sub_part = Column(String, primary_key=True)
quantity = Column(Integer)
engine = create_engine('sqlite:///:memory:', echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(binds={Base: engine})
session = Session()
included_parts = (session.query(Part)
.filter(Part.part == "our part")
.cte(name="included_parts", recursive=True))
incl_alias = aliased(included_parts, name="pr")
parts_alias = aliased(Part, name="p")
included_parts = included_parts.union_all(
session.query(parts_alias)
.filter(parts_alias.part == incl_alias.c.sub_part)
)
q = session.query(included_parts)
q.all() # sqlalchemy.exc.UnboundExecutionError: Could not locate a
# bind configured on SQL expression or this Session
如果将Session
更改为Session = sessionmaker(bind=engine)
,则代码将运行良好