Skip to content

Concurrent queries on single connection #738

Open
@cosmos-97

Description

@cosmos-97
  • asyncpg version: 0.22.0
  • PostgreSQL version: 13.2
  • Do you use a PostgreSQL SaaS? If so, which? Can you reproduce
    the issue with a local PostgreSQL install?
    : local PostgreSQL install
  • Python version: 3.9
  • Platform: centos
  • Do you use pgbouncer?: No
  • Did you install asyncpg with pip?: Yes
  • If you built asyncpg locally, which version of Cython did you use?:
  • Can the issue be reproduced under both asyncio and
    uvloop?
    : uvloop
from asyncpg.exceptions import InterfaceError


class CursorIterator:
    def __init__(self, connection, prefetch, portal_name):
        if prefetch <= 0:
            raise InterfaceError("prefetch argument must be greater than zero")

        self._connection = connection
        self._prefetch = prefetch
        self._portal_name = portal_name
        self.rows = []

    def __aiter__(self):
        return self

    async def __anext__(self):
        if not self.rows:
            self.rows = await self._connection.fetch(
                f"FETCH {self._prefetch} FROM {self._portal_name}"
            )

        if self.rows:
            return self.rows.pop(0)

        raise StopAsyncIteration


class Cursor:
    def __init__(self, connection, query, *args, prefetch=None):
        self._connection = connection
        self._args = args
        self._prefetch = prefetch
        self._query = query
        self._portal_name = connection._get_unique_id("portal")

    async def __aenter__(self):
        await self._connection.execute(
            f"DECLARE {self._portal_name} NO SCROLL CURSOR WITH HOLD FOR {self._query}",
            *self._args,
        )

        prefetch = 50 if self._prefetch is None else self._prefetch
        return CursorIterator(self._connection, prefetch, self._portal_name)

    async def __aexit__(self, *args):
        await self._connection.execute(f"CLOSE {self._portal_name}")

Several queries are run concurrently and I receive the following error. What can I do to fix the problem ?

File "asyncpg/protocol/protocol.pyx", line 321, in query
  File "asyncpg/protocol/protocol.pyx", line 684, in asyncpg.protocol.protocol.BaseProtocol._check_state
asyncpg.exceptions._base.InterfaceError: cannot perform operation: another operation is in progress

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions