我花了一些时间,但我想出了如何使用 SQLAlchemy 对两种不同类型的数据库之间的关系进行建模:
Base = declarative_base()
class Survey(Base):
__tablename__ = 'SURVEY'
survey_id = Column("SURVEY_ID", Integer, primary_key=True)
term_id = Column("TERM_ID", Integer, nullable=False)
# Because the TERM table is in Oracle, but the SURVEY table is in
# MySQL, I can't rely on SQLAlchemy's ForeignKey. Thus,
# I need to specify the relationship entirely by hand, like so:
term = relationship("Term",
primaryjoin="Term.term_id==Survey.term_id",
foreign_keys=[term_id],
backref="surveys"
)
class Term(Base):
__tablename__ = 'TERM'
term_id = Column(Integer, primary_key=True)
term_name = Column(String(30))
start_date = Column(Date)
end_date = Column(Date)
mysql_engine = create_engine(MYSQL)
oracle_engine = create_engine(ORACLE)
Session = scoped_session(sessionmaker(
binds={
Term: oracle_engine,
Survey: mysql_engine
}
))
if __name__ == "__main__":
survey = Session.query(Survey).filter_by(survey_id=8).one()
print survey.term
print survey.term.surveys
我必须这样做,因为 TERM 表位于我只有读取权限的 Oracle 数据库中,并且我正在编写一个应用程序来记录学生对该学期进行的调查。
上面的方法可行,但是当表的数量增加时它非常脆弱,因为 Session 需要准确地指定哪些映射的类对应于哪个引擎。我真的希望能够使用不同Base
的来定义哪些表属于哪个引擎,而不是单独绑定每个表。像这样:
mysql_engine = create_engine(MYSQL)
oracle_engine = create_engine(ORACLE)
MySQLBase = declarative_base(bind=mysql_engine)
OracleBase = declarative_base(bind=oracle_engine)
class Survey(MySQLBase):
__tablename__ = 'SURVEY'
survey_id = Column("SURVEY_ID", Integer, primary_key=True)
term_id = Column("TERM_ID", Integer, nullable=False)
class Term(OracleBase):
__tablename__ = 'ads_term_v'
term_id = Column(Integer, primary_key=True)
term_name = Column(String(30))
start_date = Column(Date)
end_date = Column(Date)
Survey.term = relationship("Term",
primaryjoin="Term.term_id==Survey.term_id",
foreign_keys=[Survey.term_id],
backref="surveys"
)
Session = scoped_session(sessionmaker())
if __name__ == "__main__":
survey = Session.query(Survey).filter_by(survey_id=8).one()
print survey.term
print survey.term.surveys
不幸的是,这会在查询运行时导致以下错误:
sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|Survey|SURVEY, expression 'Term.term_id==Survey.term_id' failed to locate a name ("name 'Term' is not defined"). If this is a class name, consider adding this relationship() to the <class '__main__.Survey'> class after both dependent classes have been defined.
即使我确实在定义 Term 后将 relationship() 添加到了调查中。
有没有人有什么建议?