MagicStack / asyncpg

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

Feature Request: better support for LISTEN/NOTIFY? #1089

Open racinette opened 11 months ago

racinette commented 11 months ago

Currently, you have to execute a dummy query like SELECT 1 every time you want to get a hold of new notifications from the server. Can anything similar to aiopg be implemented in asyncpg?

https://aiopg.readthedocs.io/en/stable/examples.html#usage-of-listen-notify-commands https://www.psycopg.org/docs/connection.html#connection.poll

Victor-N-Suadicani commented 4 months ago

Is this still a problem? I just tried this small test and it seems to work fine (prints "Got notification" every second). I don't need to do any dummy queries.

import asyncpg
import asyncio

async def notify(conn):
    count = 0
    while True:
        await asyncio.sleep(1)
        await conn.execute(f"notify foo, '{count}'")
        count += 1

async def notified(conn, pid, channel, payload):
    print(f"Got notification on {channel}: {payload}")

async def main():
    conn = await asyncpg.connect("postgresql://postgres:postgres@localhost")
    await conn.add_listener("foo", notified)
    await notify(conn)

asyncio.run(main())