【问题标题】:SQLAlchemy: relationship between tables using keys of different types?SQLAlchemy:使用不同类型键的表之间的关系?
【发布时间】:2011-11-18 07:33:40
【问题描述】:

我需要使用 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 表。当我尝试通过ANSWER 上的关系检索PERSON 对象时,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)?

任何想法将不胜感激!

【问题讨论】:

    标签: mysql oracle sqlalchemy relationship


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-03-24
      • 1970-01-01
      • 2012-07-28
      • 1970-01-01
      • 2018-10-31
      • 2023-03-17
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多