SQLAlchemy:使用不同类型的键的表之间的关系?

时间:2011-09-15 23:40:46

标签: mysql oracle sqlalchemy relationship

我需要使用SQLAlchemy 0.7关联两个表;一个在MySQL数据库中,另一个在Oracle数据库中。

我已经成功地将这样的表关联起来,其中键的类型相同:

Base = declarative_base()

class Survey(Base):
    __tablename__ = 'SURVEY'

    survey_id = Column(Integer, primary_key=True)
    term_id = Column(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
    }
))

但是,我遇到了一个问题,其中一个Oracle表的主键(PERSON.person_id)是VARCHAR2(30),以及MySQL表上的相关键(ANSWER.person_id )是INT类型。我不能改变Oracle表,我宁愿避免改变MySQL表。当我尝试通过PERSON上的关系检索ANSWER对象时,Oracle会抛出:

ORA-01722: invalid number

似乎是因为它正在尝试类似的查询:

SELECT * from PERSON where person_id = 12345;

而不是

SELECT * from PERSON where person_id = '12345';

所以,我正在寻找的是一种告诉SQLAlchemy的方法,ANSWER.person_id应该在对Oracle表执行的查询中使用它之前将其转换为字符串。我试过使用SQLAlchemy的func构造,但是:

Answer.person = relationship(Person,
    primaryjoin=Person.person_id == func.TO_CHAR(Answer.person_id),
    foreign_keys=[Answer.person_id]
)

导致SQLAlchemy引发此错误:

sqlalchemy.exc.ArgumentError: Could not determine relationship direction for primaryjoin condition 'PERSON.person_id = TO_CHAR(ANSWER.person_id)', on relationship Answer.person, using manual 'foreign_keys' setting. Do the columns in 'foreign_keys' represent all, and only, the 'foreign' columns in this join condition? Does the mapped Table already have adequate ForeignKey and/or ForeignKeyConstraint objects established (in which case 'foreign_keys' is usually unnecessary)?

任何想法都将不胜感激!

1 个答案:

答案 0 :(得分:1)

我在sqlalchemy Google Group上提出了同样的问题,得到了其中一位作者的回复,并提供了有效的解决方案。如果您对这种关系感兴趣,请查看他添加到sqlachemy wiki的新页面:

http://www.sqlalchemy.org/trac/wiki/UsageRecipes/RelationshipOnCast