我有以下简化的数据库访问层和两个表:
class DataAccessLayer():
    def __init__(self):
        conn_string = "mysql+mysqlconnector://root:root@localhost/"
        self.engine = create_engine(conn_string)
        Base.metadata.create_all(self.engine)
        Session = sessionmaker()
        Session.configure(bind=self.engine)
        self.session = Session()
class MatchesATP(Base):
    __tablename__ = "matches_atp"
    __table_args__ = {"schema": "belgarath", "extend_existing": True}
    ID_M = Column(Integer, primary_key=True)
    ID_T_M = Column(Integer, ForeignKey("oncourt.tours_atp.ID_T"))
class TournamentsATP(Base):
    __tablename__ = "tours_atp"
    __table_args__ = {"schema": "oncourt", "extend_existing": True}
    ID_T = Column(Integer, primary_key=True)
    NAME_T = Column(String(255))
我希望能够将两个表的架构名称切换到测试数据库,如下所示:
belgarath 到 belgarath_test
oncourt 到 oncourt_test
我试过添加:
self.session.connection(execution_options={"schema_translate_map": {"belgarath": belgarath, "oncourt": oncourt}})
到底部DataAccessLayer然后用两个变量初始化类,如下所示:
def __init__(self, belgarath, oncourt):
但是,当我构建以下查询时:
dal = DataAccessLayer("belgarath_test", "oncourt_test")
query = dal.session.query(MatchesATP)
print(query)
我得到以下 SQL:
SELECT belgarath.matches_atp.`ID_M` AS `belgarath_matches_atp_ID_M`, belgarath.matches_atp.`ID_T_M` AS `belgarath_matches_atp_ID_T_M`
FROM belgarath.matches_atp
这仍然是引用belgarath表。
我也想不出一种方法来同时改变表的外键模式oncourt.tours_atp.ID_T。
我的问题是否有单独的解决方案或组合解决方案?
我只花了 18 个月就弄清楚了这一点。事实证明,我需要将其添加schema_translate_map到 an 中engine,然后使用以下命令创建会话engine:
from sqlalchemy import create_engine
engine = create_engine(conn_str, echo=False)
schema_engine = engine.execution_options(schema_translate_map={<old_schema_name>: <new_schema_name>})
NewSession = sessionmaker(bind=schema_engine)
session = NewSession()
一切准备就绪,滚滚...