Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

python - Cross database join in sqlalchemy

Is there a way in SQLAlchemy to do cross-database joins. To be specific, here is my use case:

Schema

  1. db1.entity1
    1. entity1_id: Primary Key
    2. entity2_id: Foreign Key to db2.entity2.entity2_id
  2. db2.entity2
    1. entity2_id: Primary Key

Model

I'm using declarative style for models.

class Entity1(Base):
  __tablename__ = 'entity1' ## I tried combination of <db>.<table> with no success
  entity1_id = Column(Integer, primary_key=True)
  entity2_id = Column(Integer, ForeignKey('db2.entity2.entity2_id'))
  entity2 = relationship('Entity2')

class Entity2(Base):
  __tablename__ = 'entity2' ## I tried combination of <db>.<table> with no success
  entity2_id = Column(Integer, primary_key=True)

Now, as expected, my queries for Entity1 is failing with MySQL error messages saying table entity2 not found. I tried many different combination for __tablename__ with no success. So i was wondering if it is possible in SQLAlchemy.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You probably need to pass the schema parameter to sqlalchemy.schema.Table. When using declarative base for ORM mapping, you can provide this extra parameter through the __table_args__ property on your classes.

class Entity2(Base):
    __tablename__ = 'entity2' ## I tried combination of <db>.<table> with no success
    __table_args__ = {'schema': 'db2'}
    entity2_id = Column(Integer, primary_key=True) 

class Entity1(Base):
    __tablename__ = 'entity1' ## I tried combination of <db>.<table> with no success
    __table_args__ = {'schema': 'db1'}
    entity1_id = Column(Integer, primary_key=True)
    entity2_id = Column(Integer, ForeignKey(Entity2.entity2_id))
    entity2 = relationship('Entity2')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...