Skip to content

Support for asynchronous cursors #646

@princess-entrapta

Description

@princess-entrapta

Since version 3 psycopg supports asynchronous cursors as part of the core lib. As I am writing a modern async server, I ran into the issue this module only supports synchronous cursors from postgres.

It's a significant problem since I need to test my codebase who heavily awaits cursors, results etc. and would of course ensure this code is correct before running it into production.

Fortunately, you might be interested to know this support can be added using very minimal effort. I leave you to determine the exact way to implement the option in your lib, but my approach was very simply to duplicate the postgresql factory in my own code and change a few lines here and there.

def async_postgresql(
    # [...] Skipping doc and params
    @pytest.fixture
    # This must return an async fixture now
    async def postgresql_factory(request: FixtureRequest) -> Iterator[connection]:
        """
        Async fixture factory for PostgreSQL.

        :param request: fixture request object
        :returns: postgresql client
        """
       # [...] Skipping body

        with DatabaseJanitor(
            pg_user, pg_host, pg_port, pg_db, proc_fixture.version, pg_password, isolation_level
        ) as janitor:
            # Line modified here
            db_connection: connection = await psycopg.AsyncConnection.connect(
                dbname=pg_db,
                user=pg_user,
                password=pg_password,
                host=pg_host,
                port=pg_port,
                options=pg_options,
            )
            for load_element in pg_load:
                janitor.load(load_element)
            yield db_connection
            # And here
            await db_connection.close()

    return postgresql_factory

Hope this helps. Available for any question.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions