Search code examples
pythonsqlalchemypython-3.10postgresql-13asyncpg

sqlalchemy and asyncpg – set postgres statement_timeout


When doing

engine: AsyncEngine = create_async_engine(...)

and then

async with engine.connect() as conn:
    result: Result = await conn.execute(text("""..."""))

I would like to specify a timeout. Ideally I'd be able to set statement_timeout just for this one query execution. I am also fine with sqlalchemy doing the timeout and cancelling the query execution, but I can't find a way to set either.


Solution

  • command_timeout is set only on application level. It means query will still be running in database after timeout error in your application. To set timeout on database level you should use server_settings:

    create_async_engine(
        db_url, connect_args={"server_settings": {"statement_timeout": "10000"}},
    )