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 SCHEMA TESTLIBPQ2;
17 * SET search_path = TESTLIBPQ2;
18 * CREATE TABLE TBL1 (i int4);
19 * 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 * Start this program, then from psql do this four times:
25 * INSERT INTO TESTLIBPQ2.TBL1 VALUES (10);
35 #include <sys/select.h>
37 #include <sys/types.h>
42 exit_nicely(PGconn
*conn
)
49 main(int argc
, char **argv
)
58 * If the user supplies a parameter on the command line, use it as the
59 * conninfo string; otherwise default to setting dbname=postgres and using
60 * environment variables or defaults for all other connection parameters.
65 conninfo
= "dbname = postgres";
67 /* Make a connection to the database */
68 conn
= PQconnectdb(conninfo
);
70 /* Check to see that the backend connection was successfully made */
71 if (PQstatus(conn
) != CONNECTION_OK
)
73 fprintf(stderr
, "%s", PQerrorMessage(conn
));
77 /* Set always-secure search path, so malicious users can't take control. */
79 "SELECT pg_catalog.set_config('search_path', '', false)");
80 if (PQresultStatus(res
) != PGRES_TUPLES_OK
)
82 fprintf(stderr
, "SET failed: %s", PQerrorMessage(conn
));
88 * Should PQclear PGresult whenever it is no longer needed to avoid memory
94 * Issue LISTEN command to enable notifications from the rule's NOTIFY.
96 res
= PQexec(conn
, "LISTEN TBL2");
97 if (PQresultStatus(res
) != PGRES_COMMAND_OK
)
99 fprintf(stderr
, "LISTEN command failed: %s", PQerrorMessage(conn
));
105 /* Quit after four notifies are received. */
107 while (nnotifies
< 4)
110 * Sleep until something happens on the connection. We use select(2)
111 * to wait for input, but you could also use poll() or similar
117 sock
= PQsocket(conn
);
120 break; /* shouldn't happen */
122 FD_ZERO(&input_mask
);
123 FD_SET(sock
, &input_mask
);
125 if (select(sock
+ 1, &input_mask
, NULL
, NULL
, NULL
) < 0)
127 fprintf(stderr
, "select() failed: %s\n", strerror(errno
));
131 /* Now check for input */
132 PQconsumeInput(conn
);
133 while ((notify
= PQnotifies(conn
)) != NULL
)
136 "ASYNC NOTIFY of '%s' received from backend PID %d\n",
137 notify
->relname
, notify
->be_pid
);
140 PQconsumeInput(conn
);
144 fprintf(stderr
, "Done.\n");
146 /* close the connection to the database and cleanup */