MagicStack / asyncpg

A fast PostgreSQL Database Client Library for Python/asyncio.
Apache License 2.0
6.99k stars 404 forks source link

Table being used by active queries in this session #1008

Closed arnaudsjs closed 1 year ago

arnaudsjs commented 1 year ago

The following two test cases do exactly the same, but one of them uses a cursor and the other one doesn't:

async def test_cursor(postgresql_client: asyncpg.Connection):
    async with postgresql_client.transaction():
        await postgresql_client.execute("CREATE TABLE test(id INTEGER PRIMARY KEY)")
        await postgresql_client.execute("INSERT INTO test VALUES(1)")
        async for record in postgresql_client.cursor("SELECT * FROM test"):
            print(record["id"])
        await postgresql_client.execute("ALTER TABLE test ADD COLUMN test boolean")

async def test_no_cursor(postgresql_client: asyncpg.Connection):
    async with postgresql_client.transaction():
        await postgresql_client.execute("CREATE TABLE test(id INTEGER PRIMARY KEY)")
        await postgresql_client.execute("INSERT INTO test VALUES(1)")
        records = await postgresql_client.fetch("SELECT * FROM test")
        for record in records:
            print(record["id"])
        await postgresql_client.execute("ALTER TABLE test ADD COLUMN test boolean")

Observed behavior

The behavior I observe is that the test_no_cursor test case works as expected without any failure. The test_cursor test case on the other hand fails with the following error:

asyncpg.exceptions.ObjectInUseError: cannot ALTER TABLE "test" because it is being used by active queries in this session.

Expected behavior

I would expect that both tests cases succeed and behave identically. I have been following this documentation page on how to use cursors.