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);
35 exit_nicely(PGconn
*conn
)
42 main(int argc
, char **argv
)
51 * If the user supplies a parameter on the command line, use it as the
52 * conninfo string; otherwise default to setting dbname=postgres and using
53 * environment variables or defaults for all other connection parameters.
58 conninfo
= "dbname = postgres";
60 /* Make a connection to the database */
61 conn
= PQconnectdb(conninfo
);
63 /* Check to see that the backend connection was successfully made */
64 if (PQstatus(conn
) != CONNECTION_OK
)
66 fprintf(stderr
, "Connection to database failed: %s",
67 PQerrorMessage(conn
));
72 * Issue LISTEN command to enable notifications from the rule's NOTIFY.
74 res
= PQexec(conn
, "LISTEN TBL2");
75 if (PQresultStatus(res
) != PGRES_COMMAND_OK
)
77 fprintf(stderr
, "LISTEN command failed: %s", PQerrorMessage(conn
));
83 * should PQclear PGresult whenever it is no longer needed to avoid memory
88 /* Quit after four notifies are received. */
93 * Sleep until something happens on the connection. We use select(2)
94 * to wait for input, but you could also use poll() or similar
100 sock
= PQsocket(conn
);
103 break; /* shouldn't happen */
105 FD_ZERO(&input_mask
);
106 FD_SET (sock
, &input_mask
);
108 if (select(sock
+ 1, &input_mask
, NULL
, NULL
, NULL
) < 0)
110 fprintf(stderr
, "select() failed: %s\n", strerror(errno
));
114 /* Now check for input */
115 PQconsumeInput(conn
);
116 while ((notify
= PQnotifies(conn
)) != NULL
)
119 "ASYNC NOTIFY of '%s' received from backend pid %d\n",
120 notify
->relname
, notify
->be_pid
);
126 fprintf(stderr
, "Done.\n");
128 /* close the connection to the database and cleanup */