0

I am trying to establish a non-blocking connection to a PostgreSQL database using the libpq library in C, and I want to be able to trigger a notification or callback function once the connection is established.

I know that PQconnectStart() can be used to initiate a non-blocking connection and that PQconnectPoll() can be used to check the status of the connection, but I'm not sure how to trigger a notification or callback function once the connection is established.

PGconn *conn;
PGconnStatusType status;

conn = PQconnectStart("dbname=mydatabase user=myusername password=mypassword");

if (conn == NULL) {
    fprintf(stderr, "Connection initialization failed\n");
    exit(1);
}

while ((status = PQconnectPoll(conn)) != CONNECTION_OK) {
    if (status == PGRES_POLLING_FAILED) {
        fprintf(stderr, "Connection failed: %s\n", PQerrorMessage(conn));
        PQfinish(conn);
        exit(1);
    }
}

// Connection is established, how do I trigger a notification or callback function?

// Do something with the connection here...

PQfinish(conn);

AmrShams07
  • 96
  • 1
  • 7

4 Answers4

0

I don't think you can do that. You'll have to call select() on the socket to poll if there is a response. You can start a thread or parallel process that polls with select(), the calls your callback.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
  • i think you are right the only possible thing is to keep select() where I can create a thread, what I have done so far I created a while loop when the connection is really needed then once the connection is established I break the loop and fire a thread – AmrShams07 Jul 12 '23 at 12:22
0

I think that you can use the Notice Receiver.

You can use PQsetNoticeReceiver to set a custom notice receiver callback function that will be called whenever a notice or warning message is received. This callback function can be used to handle and process the received messages according to your application's requirements.

Documentation Notice Processing

Marcos Silva
  • 115
  • 5
0

Well, after the connection is established, triggering a notification will make use of the PQsetNoticeReceiver function. It allows you to set a callback function that will be called whenever a warning message is received from PostgreSQL.

The trigger should be like so:

PQsetNoticeReceiver(conn, notificationHandler, NULL);

Where notificationHandler is the defined callback function.

Tito
  • 289
  • 8
0

In order to trigger a notification or callback function once the connection is established, you can use the PQsetNoticeReceiver function to set a callback function. It will be invoked when a notice is received from the database.