Using package postgresql and waiting for a notify

I’m using the postgresql package and would like to wait for a NOTIFY without repeatedly polling.

The connection class provides the methods #consume_input and #socket which could be used in a loop with Unix.select. This method is the forseen method by PostgreSQL’s libpq, which the OCaml postgresql package wraps.

The #socket method returns an integer. However, I don’t know how to wait for a file descriptor, given as an integer. OCaml has a Unix.select function, but this function works with abstract Unix.file_descr types, and I didn’t find any function to convert an integer into that type.

What can I do?

2 Likes
let file_descr_of_int (x : int) : Unix.file_descr = Obj.magic x

It’s not nice but will work,

1 Like

It’ll break on Windows where file_descr is an opaque type that maps to a HANDLE.

File descriptors are not integers goes into this with fdopen and io_uring as context. Personally I’m very sympathetic to just treating fds as ints since there are so many more serious caveats to keep in mind anyway with them, but the suggested alternative is doing the conversion in C, and you can have to do that anyway to access newer kernel APIs and constants.

That article also links to a firm refusal in Add Unix.descr_of_fd and Unix.descr_of_os by dra27 · Pull Request #1990 · ocaml/ocaml · GitHub

And IMO this should be resolved by changing #socket to return a Unix.file_descr … which was attempted, but needs an update: use Unix.file_descr for sockect by craff · Pull Request #50 · mmottl/postgresql-ocaml · GitHub

4 Likes

Thank you very much for your responses.

The necessary changes to the postgresql package seem to be small, but I don’t think I’m experienced enough yet to (soundly) fix this myself. Maybe someone else would like to help here and fix the issue.

I also opened an issue on GitHub describing the problem and referring to the information you shared here:

3 Likes