2 32.23. Example Programs #
4 These examples and others can be found in the directory
5 src/test/examples in the source code distribution.
7 Example 32.1. libpq Example Program 1
10 * src/test/examples/testlibpq.c
15 * Test the C version of libpq, the PostgreSQL frontend library.
22 exit_nicely(PGconn *conn)
29 main(int argc, char **argv)
39 * If the user supplies a parameter on the command line, use it as the
40 * conninfo string; otherwise default to setting dbname=postgres and using
41 * environment variables or defaults for all other connection parameters.
46 conninfo = "dbname = postgres";
48 /* Make a connection to the database */
49 conn = PQconnectdb(conninfo);
51 /* Check to see that the backend connection was successfully made */
52 if (PQstatus(conn) != CONNECTION_OK)
54 fprintf(stderr, "%s", PQerrorMessage(conn));
58 /* Set always-secure search path, so malicious users can't take control. */
60 "SELECT pg_catalog.set_config('search_path', '', false)");
61 if (PQresultStatus(res) != PGRES_TUPLES_OK)
63 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
69 * Should PQclear PGresult whenever it is no longer needed to avoid memory
75 * Our test case here involves using a cursor, for which we must be inside
76 * a transaction block. We could do the whole thing with a single
77 * PQexec() of "select * from pg_database", but that's too trivial to make
81 /* Start a transaction block */
82 res = PQexec(conn, "BEGIN");
83 if (PQresultStatus(res) != PGRES_COMMAND_OK)
85 fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn));
92 * Fetch rows from pg_database, the system catalog of databases
94 res = PQexec(conn, "DECLARE myportal CURSOR FOR select * from pg_database");
95 if (PQresultStatus(res) != PGRES_COMMAND_OK)
97 fprintf(stderr, "DECLARE CURSOR failed: %s", PQerrorMessage(conn));
103 res = PQexec(conn, "FETCH ALL in myportal");
104 if (PQresultStatus(res) != PGRES_TUPLES_OK)
106 fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(conn));
111 /* first, print out the attribute names */
112 nFields = PQnfields(res);
113 for (i = 0; i < nFields; i++)
114 printf("%-15s", PQfname(res, i));
117 /* next, print out the rows */
118 for (i = 0; i < PQntuples(res); i++)
120 for (j = 0; j < nFields; j++)
121 printf("%-15s", PQgetvalue(res, i, j));
127 /* close the portal ... we don't bother to check for errors ... */
128 res = PQexec(conn, "CLOSE myportal");
131 /* end the transaction */
132 res = PQexec(conn, "END");
135 /* close the connection to the database and cleanup */
142 Example 32.2. libpq Example Program 2
145 * src/test/examples/testlibpq2.c
149 * Test of the asynchronous notification interface
151 * Start this program, then from psql in another window do
153 * Repeat four times to get this program to exit.
155 * Or, if you want to get fancy, try this:
156 * populate a database with the following commands
157 * (provided in src/test/examples/testlibpq2.sql):
159 * CREATE SCHEMA TESTLIBPQ2;
160 * SET search_path = TESTLIBPQ2;
161 * CREATE TABLE TBL1 (i int4);
162 * CREATE TABLE TBL2 (i int4);
163 * CREATE RULE r1 AS ON INSERT TO TBL1 DO
164 * (INSERT INTO TBL2 VALUES (new.i); NOTIFY TBL2);
166 * Start this program, then from psql do this four times:
168 * INSERT INTO TESTLIBPQ2.TBL1 VALUES (10);
178 #include <sys/select.h>
179 #include <sys/time.h>
180 #include <sys/types.h>
182 #include "libpq-fe.h"
185 exit_nicely(PGconn *conn)
192 main(int argc, char **argv)
194 const char *conninfo;
201 * If the user supplies a parameter on the command line, use it as the
202 * conninfo string; otherwise default to setting dbname=postgres and using
203 * environment variables or defaults for all other connection parameters.
208 conninfo = "dbname = postgres";
210 /* Make a connection to the database */
211 conn = PQconnectdb(conninfo);
213 /* Check to see that the backend connection was successfully made */
214 if (PQstatus(conn) != CONNECTION_OK)
216 fprintf(stderr, "%s", PQerrorMessage(conn));
220 /* Set always-secure search path, so malicious users can't take control. */
222 "SELECT pg_catalog.set_config('search_path', '', false)");
223 if (PQresultStatus(res) != PGRES_TUPLES_OK)
225 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
231 * Should PQclear PGresult whenever it is no longer needed to avoid memory
237 * Issue LISTEN command to enable notifications from the rule's NOTIFY.
239 res = PQexec(conn, "LISTEN TBL2");
240 if (PQresultStatus(res) != PGRES_COMMAND_OK)
242 fprintf(stderr, "LISTEN command failed: %s", PQerrorMessage(conn));
248 /* Quit after four notifies are received. */
250 while (nnotifies < 4)
253 * Sleep until something happens on the connection. We use select(2)
254 * to wait for input, but you could also use poll() or similar
260 sock = PQsocket(conn);
263 break; /* shouldn't happen */
265 FD_ZERO(&input_mask);
266 FD_SET(sock, &input_mask);
268 if (select(sock + 1, &input_mask, NULL, NULL, NULL) < 0)
270 fprintf(stderr, "select() failed: %s\n", strerror(errno));
274 /* Now check for input */
275 PQconsumeInput(conn);
276 while ((notify = PQnotifies(conn)) != NULL)
279 "ASYNC NOTIFY of '%s' received from backend PID %d\n",
280 notify->relname, notify->be_pid);
283 PQconsumeInput(conn);
287 fprintf(stderr, "Done.\n");
289 /* close the connection to the database and cleanup */
296 Example 32.3. libpq Example Program 3
299 * src/test/examples/testlibpq3.c
303 * Test out-of-line parameters and binary I/O.
305 * Before running this, populate a database with the following commands
306 * (provided in src/test/examples/testlibpq3.sql):
308 * CREATE SCHEMA testlibpq3;
309 * SET search_path = testlibpq3;
310 * SET standard_conforming_strings = ON;
311 * CREATE TABLE test1 (i int4, t text, b bytea);
312 * INSERT INTO test1 values (1, 'joe''s place', '\000\001\002\003\004');
313 * INSERT INTO test1 values (2, 'ho there', '\004\003\002\001\000');
315 * The expected output is:
319 * t = (11 bytes) 'joe's place'
320 * b = (5 bytes) \000\001\002\003\004
324 * t = (8 bytes) 'ho there'
325 * b = (5 bytes) \004\003\002\001\000
336 #include <sys/types.h>
337 #include "libpq-fe.h"
339 /* for ntohl/htonl */
340 #include <netinet/in.h>
341 #include <arpa/inet.h>
345 exit_nicely(PGconn *conn)
352 * This function prints a query result that is a binary-format fetch from
353 * a table defined as in the comment above. We split it out because the
354 * main() function uses it twice.
357 show_binary_results(PGresult *res)
365 /* Use PQfnumber to avoid assumptions about field order in result */
366 i_fnum = PQfnumber(res, "i");
367 t_fnum = PQfnumber(res, "t");
368 b_fnum = PQfnumber(res, "b");
370 for (i = 0; i < PQntuples(res); i++)
378 /* Get the field values (we ignore possibility they are null!) */
379 iptr = PQgetvalue(res, i, i_fnum);
380 tptr = PQgetvalue(res, i, t_fnum);
381 bptr = PQgetvalue(res, i, b_fnum);
384 * The binary representation of INT4 is in network byte order, which
385 * we'd better coerce to the local byte order.
387 ival = ntohl(*((uint32_t *) iptr));
390 * The binary representation of TEXT is, well, text, and since libpq
391 * was nice enough to append a zero byte to it, it'll work just fine
394 * The binary representation of BYTEA is a bunch of bytes, which could
395 * include embedded nulls so we have to pay attention to field length.
397 blen = PQgetlength(res, i, b_fnum);
399 printf("tuple %d: got\n", i);
400 printf(" i = (%d bytes) %d\n",
401 PQgetlength(res, i, i_fnum), ival);
402 printf(" t = (%d bytes) '%s'\n",
403 PQgetlength(res, i, t_fnum), tptr);
404 printf(" b = (%d bytes) ", blen);
405 for (j = 0; j < blen; j++)
406 printf("\\%03o", bptr[j]);
412 main(int argc, char **argv)
414 const char *conninfo;
417 const char *paramValues[1];
420 uint32_t binaryIntVal;
423 * If the user supplies a parameter on the command line, use it as the
424 * conninfo string; otherwise default to setting dbname=postgres and using
425 * environment variables or defaults for all other connection parameters.
430 conninfo = "dbname = postgres";
432 /* Make a connection to the database */
433 conn = PQconnectdb(conninfo);
435 /* Check to see that the backend connection was successfully made */
436 if (PQstatus(conn) != CONNECTION_OK)
438 fprintf(stderr, "%s", PQerrorMessage(conn));
442 /* Set always-secure search path, so malicious users can't take control. */
443 res = PQexec(conn, "SET search_path = testlibpq3");
444 if (PQresultStatus(res) != PGRES_COMMAND_OK)
446 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
453 * The point of this program is to illustrate use of PQexecParams() with
454 * out-of-line parameters, as well as binary transmission of data.
456 * This first example transmits the parameters as text, but receives the
457 * results in binary format. By using out-of-line parameters we can avoid
458 * a lot of tedious mucking about with quoting and escaping, even though
459 * the data is text. Notice how we don't have to do anything special with
460 * the quote mark in the parameter value.
463 /* Here is our out-of-line parameter value */
464 paramValues[0] = "joe's place";
466 res = PQexecParams(conn,
467 "SELECT * FROM test1 WHERE t = $1",
469 NULL, /* let the backend deduce param type */
471 NULL, /* don't need param lengths since text */
472 NULL, /* default to all text params */
473 1); /* ask for binary results */
475 if (PQresultStatus(res) != PGRES_TUPLES_OK)
477 fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
482 show_binary_results(res);
487 * In this second example we transmit an integer parameter in binary form,
488 * and again retrieve the results in binary form.
490 * Although we tell PQexecParams we are letting the backend deduce
491 * parameter type, we really force the decision by casting the parameter
492 * symbol in the query text. This is a good safety measure when sending
496 /* Convert integer value "2" to network byte order */
497 binaryIntVal = htonl((uint32_t) 2);
499 /* Set up parameter arrays for PQexecParams */
500 paramValues[0] = (char *) &binaryIntVal;
501 paramLengths[0] = sizeof(binaryIntVal);
502 paramFormats[0] = 1; /* binary */
504 res = PQexecParams(conn,
505 "SELECT * FROM test1 WHERE i = $1::int4",
507 NULL, /* let the backend deduce param type */
511 1); /* ask for binary results */
513 if (PQresultStatus(res) != PGRES_TUPLES_OK)
515 fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
520 show_binary_results(res);
524 /* close the connection to the database and cleanup */