schema_translate_map 对于 SQLALchemy AsyncSession

schema_translate_map for SQLALchemy AsyncSession

我需要在 SQLAlchemy AsyncSession 会话中更改 PostgreSQL 模式。

对于同步会话,我们有 session.connection(execution_options={"schema_translate_map": {None: schema}})

对于异步,我找到了一种方法:MyModel.__table__.schema = "MySchema,但它会在运行时更改模型,这对异步代码来说非常糟糕。

AsyncSession 有类似 schema_translate_map 的东西吗?

我遇到了同样的问题,我的解决方法是这样的:

from asyncio import current_task
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_scoped_session
from sqlalchemy.orm import sessionmaker


async def main()
    db_connstring = "postgresql+asyncpg://scott:tiger@localhost/test"
    engine = create_async_engine(db_connstring, pool_pre_ping=True)
    session = async_scoped_session(
sessionmaker(bind=engine, expire_on_commit=False, class_=AsyncSession),
scopefunc=current_task)

    schema = "my_schema"
    connection = await session.connection()
    await connection.execution_options(schema_translate_map={None: schema})
    ...