2 * src/test/examples/testlibpq2.c
6 * Test of the asynchronous notification interface
8 * Start this program, then from psql in another window do
10 * Repeat four times to get this program to exit.
12 * Or, if you want to get fancy, try this:
13 * populate a database with the following commands
14 * (provided in src/test/examples/testlibpq2.sql):
16 * CREATE TABLE TBL1 (i int4);
18 * CREATE TABLE TBL2 (i int4);
20 * CREATE RULE r1 AS ON INSERT TO TBL1 DO
21 * (INSERT INTO TBL2 VALUES (new.i); NOTIFY TBL2);
23 * and do this four times:
25 * INSERT INTO TBL1 VALUES (10);
36 #include <sys/types.h>
40 exit_nicely(PGconn *conn)
47 main(int argc, char **argv)
56 * If the user supplies a parameter on the command line, use it as the
57 * conninfo string; otherwise default to setting dbname=postgres and using
58 * environment variables or defaults for all other connection parameters.
63 conninfo = "dbname = postgres";
65 /* Make a connection to the database */
66 conn = PQconnectdb(conninfo);
68 /* Check to see that the backend connection was successfully made */
69 if (PQstatus(conn) != CONNECTION_OK)
71 fprintf(stderr, "Connection to database failed: %s",
72 PQerrorMessage(conn));
77 * Issue LISTEN command to enable notifications from the rule's NOTIFY.
79 res = PQexec(conn, "LISTEN TBL2");
80 if (PQresultStatus(res) != PGRES_COMMAND_OK)
82 fprintf(stderr, "LISTEN command failed: %s", PQerrorMessage(conn));
88 * should PQclear PGresult whenever it is no longer needed to avoid memory
93 /* Quit after four notifies are received. */
98 * Sleep until something happens on the connection. We use select(2)
99 * to wait for input, but you could also use poll() or similar
105 sock = PQsocket(conn);
108 break; /* shouldn't happen */
110 FD_ZERO(&input_mask);
111 FD_SET(sock, &input_mask);
113 if (select(sock + 1, &input_mask, NULL, NULL, NULL) < 0)
115 fprintf(stderr, "select() failed: %s\n", strerror(errno));
119 /* Now check for input */
120 PQconsumeInput(conn);
121 while ((notify = PQnotifies(conn)) != NULL)
124 "ASYNC NOTIFY of '%s' received from backend pid %d\n",
125 notify->relname, notify->be_pid);
131 fprintf(stderr, "Done.\n");
133 /* close the connection to the database and cleanup */