Reputation: 178
I need to change PostgreSQL schema in SQLAlchemy AsyncSession
session.
For sync Session we have session.connection(execution_options={"schema_translate_map": {None: schema}})
For async I found a way to do it: MyModel.__table__.schema = "MySchema
, but it will change the model in runtime which is really bad for async code.
Is there something like schema_translate_map
for AsyncSession
?
Upvotes: 0
Views: 969
Reputation: 517
I had the same exact problem and the way I fix it is doing like this:
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})
...
Upvotes: 3