Improving `Connection.notifies()` in Psycopg 3.2

From: Daniele Varrazzo <daniele(dot)varrazzo(at)gmail(dot)com>
To: Psycopg <psycopg(at)postgresql(dot)org>
Subject: Improving `Connection.notifies()` in Psycopg 3.2
Date: 2023-10-24 22:16:50
Message-ID: CA+mi_8Z6pSgVOpWgretCKpop8MzEWnJ-R-A3c6KQdodYY4D0YQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

Hello,

Psycopg 3 introduced a `Connection.notifies()` generator, yielding
async notifications as they are received:

for n in conn.notifies():
do_something_with(n)

However it proved harder to use than expected:

- during the loop, the connection cannot be used to run queries (and
some would be pretty useful, such as LISTEN/UNLISTEN to change
the channels to listen at);
- it is not clear how to stop the generator. If assigned to a variable
`gen`, it can be closed with `gen.close()` but it must be done from an
external task/thread if the generator is waiting and I seem to
remember that it's not possible to call close on an async generator
from an external task.

In https://github.com/psycopg/psycopg/pull/673 I propose to add
optional parameters to the function:

- `timeout`: max time to wait for notifications;
- `stop_after`: stop after receiving this number of notifications (may
return more than what requested if received in the same batch);

I think these additions should make the generator easier to use, but
I'm not completely sold on its interface.

What do you think? Comments are welcome.

Cheers

-- Daniele

Browse psycopg by date

  From Date Subject
Next Message Ams Fwd 2023-11-20 18:57:52 2-to-3 Question about adapter using AsIs
Previous Message Daniele Varrazzo 2023-09-21 09:28:28 Re: CPU usage for queries, psycopg 2 vs 3