The code to unlink dropped relations in FinishPreparedTransaction() was
[PostgreSQL.git] / doc / src / sgml / libpq.sgml
blob86affb0100aea59b29a8db8212360e5b2e20b1cf
1 <!-- $PostgreSQL$ -->
3 <chapter id="libpq">
4 <title><application>libpq</application> - C Library</title>
6 <indexterm zone="libpq">
7 <primary>libpq</primary>
8 </indexterm>
10 <indexterm zone="libpq">
11 <primary>C</primary>
12 </indexterm>
14 <para>
15 <application>libpq</application> is the <acronym>C</acronym>
16 application programmer's interface to <productname>PostgreSQL</>.
17 <application>libpq</> is a set of library functions that allow
18 client programs to pass queries to the <productname>PostgreSQL</>
19 backend server and to receive the results of these queries.
20 </para>
22 <para>
23 <application>libpq</> is also the underlying engine for several
24 other <productname>PostgreSQL</> application interfaces, including
25 those written for C++, Perl, Python, Tcl and <application>ECPG</>.
26 So some aspects of <application>libpq</>'s behavior will be
27 important to you if you use one of those packages. In particular,
28 <xref linkend="libpq-envars">,
29 <xref linkend="libpq-pgpass"> and
30 <xref linkend="libpq-ssl">
31 describe behavior that is visible to the user of any application
32 that uses <application>libpq</>.
33 </para>
35 <para>
36 Some short programs are included at the end of this chapter (<xref linkend="libpq-example">) to show how
37 to write programs that use <application>libpq</application>. There are also several
38 complete examples of <application>libpq</application> applications in the
39 directory <filename>src/test/examples</filename> in the source code distribution.
40 </para>
42 <para>
43 Client programs that use <application>libpq</application> must
44 include the header file
45 <filename>libpq-fe.h</filename><indexterm><primary>libpq-fe.h</></>
46 and must link with the <application>libpq</application> library.
47 </para>
49 <sect1 id="libpq-connect">
50 <title>Database Connection Control Functions</title>
52 <para>
53 The following functions deal with making a connection to a
54 <productname>PostgreSQL</productname> backend server. An
55 application program can have several backend connections open at
56 one time. (One reason to do that is to access more than one
57 database.) Each connection is represented by a
58 <structname>PGconn</><indexterm><primary>PGconn</></> object, which
59 is obtained from the function <function>PQconnectdb</> or
60 <function>PQsetdbLogin</>. Note that these functions will always
61 return a non-null object pointer, unless perhaps there is too
62 little memory even to allocate the <structname>PGconn</> object.
63 The <function>PQstatus</> function should be called to check
64 whether a connection was successfully made before queries are sent
65 via the connection object.
67 <warning>
68 <para>
69 On Unix, forking a process with open libpq connections can lead to
70 unpredictable results because the parent and child processes share
71 the same sockets and operating system resources. For this reason,
72 such usage is not recommended, though doing an <function>exec</> from
73 the child process to load a new executable is safe.
74 </para>
75 </warning>
77 <note>
78 <para>
79 On Windows, there is a way to improve performance if a single
80 database connection is repeatedly started and shutdown. Internally,
81 libpq calls WSAStartup() and WSACleanup() for connection startup
82 and shutdown, respectively. WSAStartup() increments an internal
83 Windows library reference count which is decremented by WSACleanup().
84 When the reference count is just one, calling WSACleanup() frees
85 all resources and all DLLs are unloaded. This is an expensive
86 operation. To avoid this, an application can manually call
87 WSAStartup() so resources will not be freed when the last database
88 connection is closed.
89 </para>
90 </note>
92 <variablelist>
93 <varlistentry>
94 <term><function>PQconnectdb</function><indexterm><primary>PQconnectdb</></></term>
95 <listitem>
96 <para>
97 Makes a new connection to the database server.
99 <synopsis>
100 PGconn *PQconnectdb(const char *conninfo);
101 </synopsis>
102 </para>
104 <para>
105 This function opens a new database connection using the parameters taken
106 from the string <literal>conninfo</literal>. Unlike <function>PQsetdbLogin</> below,
107 the parameter set can be extended without changing the function signature,
108 so use of this function (or its nonblocking analogues <function>PQconnectStart</>
109 and <function>PQconnectPoll</function>) is preferred for new application programming.
110 </para>
112 <para>
113 The passed string
114 can be empty to use all default parameters, or it can contain one or more
115 parameter settings separated by whitespace.
116 Each parameter setting is in the form <literal>keyword = value</literal>.
117 Spaces around the equal sign are optional.
118 To write an empty value or a value containing
119 spaces, surround it with single quotes, e.g.,
120 <literal>keyword = 'a value'</literal>.
121 Single quotes and backslashes within the value must be escaped with a
122 backslash, i.e., <literal>\'</literal> and <literal>\\</literal>.
123 </para>
125 <para>
126 The currently recognized parameter key words are:
128 <variablelist>
129 <varlistentry id="libpq-connect-host" xreflabel="host">
130 <term><literal>host</literal></term>
131 <listitem>
132 <para>
133 Name of host to connect to.<indexterm><primary>host name</></>
134 If this begins with a slash, it specifies Unix-domain
135 communication rather than TCP/IP communication; the value is the
136 name of the directory in which the socket file is stored. The
137 default behavior when <literal>host</literal> is not specified
138 is to connect to a Unix-domain
139 socket<indexterm><primary>Unix domain socket</></> in
140 <filename>/tmp</filename> (or whatever socket directory was specified
141 when <productname>PostgreSQL</> was built). On machines without
142 Unix-domain sockets, the default is to connect to <literal>localhost</>.
143 </para>
144 </listitem>
145 </varlistentry>
147 <varlistentry id="libpq-connect-hostaddr" xreflabel="hostaddr">
148 <term><literal>hostaddr</literal></term>
149 <listitem>
150 <para>
151 Numeric IP address of host to connect to. This should be in the
152 standard IPv4 address format, e.g., <literal>172.28.40.9</>. If
153 your machine supports IPv6, you can also use those addresses.
154 TCP/IP communication is
155 always used when a nonempty string is specified for this parameter.
156 </para>
158 <para>
159 Using <literal>hostaddr</> instead of <literal>host</> allows the
160 application to avoid a host name look-up, which might be important in
161 applications with time constraints. However, Kerberos and GSSAPI authentication
162 requires the host name. The following therefore applies: If
163 <literal>host</> is specified without <literal>hostaddr</>, a host name
164 lookup occurs. If <literal>hostaddr</> is specified without
165 <literal>host</>, the value for <literal>hostaddr</> gives the remote
166 address. When Kerberos is used, a reverse name query occurs to obtain
167 the host name for Kerberos. If both
168 <literal>host</> and <literal>hostaddr</> are specified, the value for
169 <literal>hostaddr</> gives the remote address; the value for
170 <literal>host</> is ignored, unless Kerberos is used, in which case that
171 value is used for Kerberos authentication. (Note that authentication is
172 likely to fail if <application>libpq</application> is passed a host name
173 that is not the name of the machine at <literal>hostaddr</>.) Also,
174 <literal>host</> rather than <literal>hostaddr</> is used to identify
175 the connection in <filename>~/.pgpass</> (see
176 <xref linkend="libpq-pgpass">).
177 </para>
179 <para>
180 Without either a host name or host address,
181 <application>libpq</application> will connect using a
182 local Unix-domain socket; or on machines without Unix-domain
183 sockets, it will attempt to connect to <literal>localhost</>.
184 </para>
185 </listitem>
186 </varlistentry>
188 <varlistentry id="libpq-connect-port" xreflabel="port">
189 <term><literal>port</literal></term>
190 <listitem>
191 <para>
192 Port number to connect to at the server host, or socket file
193 name extension for Unix-domain
194 connections.<indexterm><primary>port</></>
195 </para>
196 </listitem>
197 </varlistentry>
199 <varlistentry id="libpq-connect-dbname" xreflabel="dbname">
200 <term><literal>dbname</literal></term>
201 <listitem>
202 <para>
203 The database name. Defaults to be the same as the user name.
204 </para>
205 </listitem>
206 </varlistentry>
208 <varlistentry id="libpq-connect-user" xreflabel="user">
209 <term><literal>user</literal></term>
210 <listitem>
211 <para>
212 <productname>PostgreSQL</productname> user name to connect as.
213 Defaults to be the same as the operating system name of the user
214 running the application.
215 </para>
216 </listitem>
217 </varlistentry>
219 <varlistentry id="libpq-connect-password" xreflabel="password">
220 <term><literal>password</literal></term>
221 <listitem>
222 <para>
223 Password to be used if the server demands password authentication.
224 </para>
225 </listitem>
226 </varlistentry>
228 <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout">
229 <term><literal>connect_timeout</literal></term>
230 <listitem>
231 <para>
232 Maximum wait for connection, in seconds (write as a decimal integer
233 string). Zero or not specified means wait indefinitely. It is not
234 recommended to use a timeout of less than 2 seconds.
235 </para>
236 </listitem>
237 </varlistentry>
239 <varlistentry id="libpq-connect-options" xreflabel="options">
240 <term><literal>options</literal></term>
241 <listitem>
242 <para>
243 Adds command-line options to send to the server at run-time.
244 For example, setting this to <literal>-c geqo=off</> sets the
245 session's value of the <varname>geqo</> parameter to
246 <literal>off</>. For a detailed discussion of the available
247 options, consult <xref linkend="runtime-config">.
248 </para>
249 </listitem>
250 </varlistentry>
252 <varlistentry id="libpq-connect-tty" xreflabel="tty">
253 <term><literal>tty</literal></term>
254 <listitem>
255 <para>
256 Ignored (formerly, this specified where to send server debug output).
257 </para>
258 </listitem>
259 </varlistentry>
261 <varlistentry id="libpq-connect-sslmode" xreflabel="sslmode">
262 <term><literal>sslmode</literal></term>
263 <listitem>
264 <para>
265 This option determines whether or with what priority a
266 <acronym>SSL</> TCP/IP connection will be negotiated with the
267 server. There are six modes:
268 </para>
270 <table id="libpq-connect-sslmode-options">
271 <title><literal>sslmode</literal> options</title>
272 <tgroup cols="2">
273 <thead>
274 <row>
275 <entry>Option</entry>
276 <entry>Description</entry>
277 </row>
278 </thead>
280 <tbody>
282 <row>
283 <entry><literal>disable</></entry>
284 <entry>only try a non-<acronym>SSL</> connection</entry>
285 </row>
287 <row>
288 <entry><literal>allow</></entry>
289 <entry>first try a non-<acronym>SSL</>
290 connection; if that fails, try an <acronym>SSL</>
291 connection</entry>
292 </row>
294 <row>
295 <entry><literal>prefer</> (default)</entry>
296 <entry>first try an <acronym>SSL</> connection; if
297 that fails, try a non-<acronym>SSL</>
298 connection</entry>
299 </row>
301 <row>
302 <entry><literal>require</></entry>
303 <entry>only try an <acronym>SSL</> connection</entry>
304 </row>
306 <row>
307 <entry><literal>verify-ca</></entry>
308 <entry>only try an <acronym>SSL</> connection, and verify that
309 the server certificate is issued by a trusted <acronym>CA</>.
310 </entry>
311 </row>
313 <row>
314 <entry><literal>verify-full</></entry>
315 <entry>only try an <acronym>SSL</> connection, verify that
316 the server certificate is issued by a trusted <acronym>CA</> and
317 that the server hostname matches that in the certificate.</entry>
318 </row>
320 </tbody>
321 </tgroup>
322 </table>
324 <para>
325 See <xref linkend="libpq-ssl"> for a detailed description of how
326 these options work.
327 </para>
329 <para>
330 <literal>sslmode</> is ignored for Unix domain socket
331 communication.
332 If <productname>PostgreSQL</> is compiled without SSL support,
333 using option <literal>require</> will cause an error, while
334 options <literal>allow</> and <literal>prefer</> will be
335 accepted but <application>libpq</> will not actually attempt
336 an <acronym>SSL</>
337 connection.<indexterm><primary>SSL</><secondary
338 sortas="libpq">with libpq</></indexterm>
339 </para>
340 </listitem>
341 </varlistentry>
343 <varlistentry id="libpq-connect-requiressl" xreflabel="requiressl">
344 <term><literal>requiressl</literal></term>
345 <listitem>
346 <para>
347 This option is deprecated in favor of the <literal>sslmode</>
348 setting.
349 </para>
351 <para>
352 If set to 1, an <acronym>SSL</acronym> connection to the server
353 is required (this is equivalent to <literal>sslmode</>
354 <literal>require</>). <application>libpq</> will then refuse
355 to connect if the server does not accept an
356 <acronym>SSL</acronym> connection. If set to 0 (default),
357 <application>libpq</> will negotiate the connection type with
358 the server (equivalent to <literal>sslmode</>
359 <literal>prefer</>). This option is only available if
360 <productname>PostgreSQL</> is compiled with SSL support.
361 </para>
362 </listitem>
363 </varlistentry>
365 <varlistentry id="libpq-connect-sslcert" xreflabel="sslcert">
366 <term><literal>sslcert</literal></term>
367 <listitem>
368 <para>
369 This parameter specifies the file name of the client SSL
370 certificate.
371 </para>
372 </listitem>
373 </varlistentry>
375 <varlistentry id="libpq-connect-sslkey" xreflabel="sslkey">
376 <term><literal>sslkey</literal></term>
377 <listitem>
378 <para>
379 This parameter specifies the location for the secret key
380 used for the client certificate. It can either specify a filename
381 that will be used instead of the default
382 <filename>~/.postgresql/postgresql.key</>, or can specify an external
383 engine (engines are <productname>OpenSSL</> loadable modules). The
384 external engine specification should consist of a colon-separated
385 engine name and an engine-specific key identifier.
386 </para>
387 </listitem>
388 </varlistentry>
390 <varlistentry id="libpq-connect-sslrootcert" xreflabel="sslrootcert">
391 <term><literal>sslrootcert</literal></term>
392 <listitem>
393 <para>
394 This parameter specifies the file name of the root SSL certificate.
395 </para>
396 </listitem>
397 </varlistentry>
399 <varlistentry id="libpq-connect-sslcrl" xreflabel="sslcrl">
400 <term><literal>sslcrl</literal></term>
401 <listitem>
402 <para>
403 This parameter specifies the file name of the SSL certificate
404 revocation list (CRL).
405 </para>
406 </listitem>
407 </varlistentry>
409 <varlistentry id="libpq-connect-krbsrvname" xreflabel="krbsrvname">
410 <term><literal>krbsrvname</literal></term>
411 <listitem>
412 <para>
413 Kerberos service name to use when authenticating with Kerberos 5
414 or GSSAPI.
415 This must match the service name specified in the server
416 configuration for Kerberos authentication to succeed. (See also
417 <xref linkend="kerberos-auth"> and <xref linkend="gssapi-auth">.)
418 </para>
419 </listitem>
420 </varlistentry>
422 <varlistentry id="libpq-connect-gsslib" xreflabel="gsslib">
423 <term><literal>gsslib</literal></term>
424 <listitem>
425 <para>
426 GSS library to use for GSSAPI authentication. Only used on Windows.
427 Set to <literal>gssapi</literal> to force libpq to use the GSSAPI
428 library for authentication instead of the default SSPI.
429 </para>
430 </listitem>
431 </varlistentry>
433 <varlistentry id="libpq-connect-service" xreflabel="service">
434 <term><literal>service</literal></term>
435 <listitem>
436 <para>
437 Service name to use for additional parameters. It specifies a service
438 name in <filename>pg_service.conf</filename> that holds additional connection parameters.
439 This allows applications to specify only a service name so connection parameters
440 can be centrally maintained. See <xref linkend="libpq-pgservice">.
441 </para>
442 </listitem>
443 </varlistentry>
444 </variablelist>
446 If any parameter is unspecified, then the corresponding
447 environment variable (see <xref linkend="libpq-envars">)
448 is checked. If the environment variable is not set either,
449 then the indicated built-in defaults are used.
450 </para>
451 </listitem>
452 </varlistentry>
454 <varlistentry>
455 <term><function>PQsetdbLogin</function><indexterm><primary>PQsetdbLogin</></></term>
456 <listitem>
457 <para>
458 Makes a new connection to the database server.
459 <synopsis>
460 PGconn *PQsetdbLogin(const char *pghost,
461 const char *pgport,
462 const char *pgoptions,
463 const char *pgtty,
464 const char *dbName,
465 const char *login,
466 const char *pwd);
467 </synopsis>
468 </para>
470 <para>
471 This is the predecessor of <function>PQconnectdb</function> with a fixed
472 set of parameters. It has the same functionality except that the
473 missing parameters will always take on default values. Write <symbol>NULL</symbol> or an
474 empty string for any one of the fixed parameters that is to be defaulted.
475 </para>
477 <para>
478 If the <parameter>dbName</parameter> contains an <symbol>=</symbol> sign, it
479 is taken as a <parameter>conninfo</parameter> string in exactly the same way as
480 if it had been passed to <function>PQconnectdb</function>, and the remaining
481 parameters are then applied as above.
482 </para>
483 </listitem>
484 </varlistentry>
486 <varlistentry>
487 <term><function>PQsetdb</function><indexterm><primary>PQsetdb</></></term>
488 <listitem>
489 <para>
490 Makes a new connection to the database server.
491 <synopsis>
492 PGconn *PQsetdb(char *pghost,
493 char *pgport,
494 char *pgoptions,
495 char *pgtty,
496 char *dbName);
497 </synopsis>
498 </para>
500 <para>
501 This is a macro that calls <function>PQsetdbLogin</function> with null pointers
502 for the <parameter>login</> and <parameter>pwd</> parameters. It is provided
503 for backward compatibility with very old programs.
504 </para>
505 </listitem>
506 </varlistentry>
508 <varlistentry>
509 <term><function>PQconnectStart</function><indexterm><primary>PQconnectStart</></></term>
510 <term><function>PQconnectPoll</function><indexterm><primary>PQconnectPoll</></></term>
511 <listitem>
512 <para>
513 <indexterm><primary>nonblocking connection</primary></indexterm>
514 Make a connection to the database server in a nonblocking manner.
516 <synopsis>
517 PGconn *PQconnectStart(const char *conninfo);
518 </synopsis>
520 <synopsis>
521 PostgresPollingStatusType PQconnectPoll(PGconn *conn);
522 </synopsis>
523 </para>
525 <para>
526 These two functions are used to open a connection to a database server such
527 that your application's thread of execution is not blocked on remote I/O
528 whilst doing so.
529 The point of this approach is that the waits for I/O to complete can occur
530 in the application's main loop, rather than down inside
531 <function>PQconnectdb</>, and so the application can manage this
532 operation in parallel with other activities.
533 </para>
535 <para>
536 The database connection is made using the parameters taken from the string
537 <literal>conninfo</literal>, passed to <function>PQconnectStart</function>. This string is in
538 the same format as described above for <function>PQconnectdb</function>.
539 </para>
540 <para>
541 Neither <function>PQconnectStart</function> nor <function>PQconnectPoll</function> will block, so long as a number of
542 restrictions are met:
543 <itemizedlist>
544 <listitem>
545 <para>
546 The <literal>hostaddr</> and <literal>host</> parameters are used appropriately to ensure that
547 name and reverse name queries are not made. See the documentation of
548 these parameters under <function>PQconnectdb</function> above for details.
549 </para>
550 </listitem>
552 <listitem>
553 <para>
554 If you call <function>PQtrace</function>, ensure that the stream object
555 into which you trace will not block.
556 </para>
557 </listitem>
559 <listitem>
560 <para>
561 You ensure that the socket is in the appropriate state
562 before calling <function>PQconnectPoll</function>, as described below.
563 </para>
564 </listitem>
565 </itemizedlist>
566 </para>
568 <para>
569 To begin a nonblocking connection request, call <literal>conn = PQconnectStart("<replaceable>connection_info_string</>")</literal>.
570 If <varname>conn</varname> is null, then <application>libpq</> has been unable to allocate a new <structname>PGconn</>
571 structure. Otherwise, a valid <structname>PGconn</> pointer is returned (though not yet
572 representing a valid connection to the database). On return from
573 <function>PQconnectStart</function>, call <literal>status = PQstatus(conn)</literal>. If <varname>status</varname> equals
574 <symbol>CONNECTION_BAD</symbol>, <function>PQconnectStart</function> has failed.
575 </para>
577 <para>
578 If <function>PQconnectStart</> succeeds, the next stage is to poll
579 <application>libpq</> so that it can proceed with the connection sequence.
580 Use <function>PQsocket(conn)</function> to obtain the descriptor of the
581 socket underlying the database connection.
582 Loop thus: If <function>PQconnectPoll(conn)</function> last returned
583 <symbol>PGRES_POLLING_READING</symbol>, wait until the socket is ready to
584 read (as indicated by <function>select()</>, <function>poll()</>, or
585 similar system function).
586 Then call <function>PQconnectPoll(conn)</function> again.
587 Conversely, if <function>PQconnectPoll(conn)</function> last returned
588 <symbol>PGRES_POLLING_WRITING</symbol>, wait until the socket is ready
589 to write, then call <function>PQconnectPoll(conn)</function> again.
590 If you have yet to call
591 <function>PQconnectPoll</function>, i.e., just after the call to
592 <function>PQconnectStart</function>, behave as if it last returned
593 <symbol>PGRES_POLLING_WRITING</symbol>. Continue this loop until
594 <function>PQconnectPoll(conn)</function> returns
595 <symbol>PGRES_POLLING_FAILED</symbol>, indicating the connection procedure
596 has failed, or <symbol>PGRES_POLLING_OK</symbol>, indicating the connection
597 has been successfully made.
598 </para>
600 <para>
601 At any time during connection, the status of the connection can be
602 checked by calling <function>PQstatus</>. If this gives <symbol>CONNECTION_BAD</>, then the
603 connection procedure has failed; if it gives <function>CONNECTION_OK</>, then the
604 connection is ready. Both of these states are equally detectable
605 from the return value of <function>PQconnectPoll</>, described above. Other states might also occur
606 during (and only during) an asynchronous connection procedure. These
607 indicate the current stage of the connection procedure and might be useful
608 to provide feedback to the user for example. These statuses are:
610 <variablelist>
611 <varlistentry>
612 <term><symbol>CONNECTION_STARTED</symbol></term>
613 <listitem>
614 <para>
615 Waiting for connection to be made.
616 </para>
617 </listitem>
618 </varlistentry>
620 <varlistentry>
621 <term><symbol>CONNECTION_MADE</symbol></term>
622 <listitem>
623 <para>
624 Connection OK; waiting to send.
625 </para>
626 </listitem>
627 </varlistentry>
629 <varlistentry>
630 <term><symbol>CONNECTION_AWAITING_RESPONSE</symbol></term>
631 <listitem>
632 <para>
633 Waiting for a response from the server.
634 </para>
635 </listitem>
636 </varlistentry>
638 <varlistentry>
639 <term><symbol>CONNECTION_AUTH_OK</symbol></term>
640 <listitem>
641 <para>
642 Received authentication; waiting for backend start-up to finish.
643 </para>
644 </listitem>
645 </varlistentry>
647 <varlistentry>
648 <term><symbol>CONNECTION_SSL_STARTUP</symbol></term>
649 <listitem>
650 <para>
651 Negotiating SSL encryption.
652 </para>
653 </listitem>
654 </varlistentry>
656 <varlistentry>
657 <term><symbol>CONNECTION_SETENV</symbol></term>
658 <listitem>
659 <para>
660 Negotiating environment-driven parameter settings.
661 </para>
662 </listitem>
663 </varlistentry>
664 </variablelist>
666 Note that, although these constants will remain (in order to maintain
667 compatibility), an application should never rely upon these occurring in a
668 particular order, or at all, or on the status always being one of these
669 documented values. An application might do something like this:
670 <programlisting>
671 switch(PQstatus(conn))
673 case CONNECTION_STARTED:
674 feedback = "Connecting...";
675 break;
677 case CONNECTION_MADE:
678 feedback = "Connected to server...";
679 break;
683 default:
684 feedback = "Connecting...";
686 </programlisting>
687 </para>
689 <para>
690 The <literal>connect_timeout</literal> connection parameter is ignored
691 when using <function>PQconnectPoll</function>; it is the application's
692 responsibility to decide whether an excessive amount of time has elapsed.
693 Otherwise, <function>PQconnectStart</function> followed by a
694 <function>PQconnectPoll</function> loop is equivalent to
695 <function>PQconnectdb</function>.
696 </para>
698 <para>
699 Note that if <function>PQconnectStart</function> returns a non-null pointer, you must call
700 <function>PQfinish</function> when you are finished with it, in order to dispose of
701 the structure and any associated memory blocks. This must be done even if
702 the connection attempt fails or is abandoned.
703 </para>
704 </listitem>
705 </varlistentry>
707 <varlistentry>
708 <term><function>PQconndefaults</function><indexterm><primary>PQconndefaults</></></term>
709 <listitem>
710 <para>
711 Returns the default connection options.
712 <synopsis>
713 PQconninfoOption *PQconndefaults(void);
715 typedef struct
717 char *keyword; /* The keyword of the option */
718 char *envvar; /* Fallback environment variable name */
719 char *compiled; /* Fallback compiled in default value */
720 char *val; /* Option's current value, or NULL */
721 char *label; /* Label for field in connect dialog */
722 char *dispchar; /* Indicates how to display this field
723 in a connect dialog. Values are:
724 "" Display entered value as is
725 "*" Password field - hide value
726 "D" Debug option - don't show by default */
727 int dispsize; /* Field size in characters for dialog */
728 } PQconninfoOption;
729 </synopsis>
730 </para>
732 <para>
733 Returns a connection options array. This can be used to determine
734 all possible <function>PQconnectdb</function> options and their
735 current default values. The return value points to an array of
736 <structname>PQconninfoOption</structname> structures, which ends
737 with an entry having a null <structfield>keyword</> pointer. The
738 null pointer is returned if memory could not be allocated. Note that
739 the current default values (<structfield>val</structfield> fields)
740 will depend on environment variables and other context. Callers
741 must treat the connection options data as read-only.
742 </para>
744 <para>
745 After processing the options array, free it by passing it to
746 <function>PQconninfoFree</function>. If this is not done, a small amount of memory
747 is leaked for each call to <function>PQconndefaults</function>.
748 </para>
750 </listitem>
751 </varlistentry>
753 <varlistentry>
754 <term><function>PQconninfoParse</function><indexterm><primary>PQconninfoParse</></></term>
755 <listitem>
756 <para>
757 Returns parsed connection options from the provided connection string.
759 <synopsis>
760 PQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg);
761 </synopsis>
762 </para>
764 <para>
765 Parses a connection string and returns the resulting options as an
766 array; or returns NULL if there is a problem with the connection
767 string. This can be used to determine
768 the <function>PQconnectdb</function> options in the provided
769 connection string. The return value points to an array of
770 <structname>PQconninfoOption</structname> structures, which ends
771 with an entry having a null <structfield>keyword</> pointer.
772 </para>
774 <para>
775 Note that only options explicitly specified in the string will have
776 values set in the result array; no defaults are inserted.
777 </para>
779 <para>
780 If <literal>errmsg</> is not NULL, then <literal>*errmsg</> is set
781 to NULL on success, else to a malloc'd error string explaining
782 the problem. (It is also possible for <literal>*errmsg</> to be
783 set to NULL even when NULL is returned; this indicates an out-of-memory
784 situation.)
785 </para>
787 <para>
788 After processing the options array, free it by passing it to
789 <function>PQconninfoFree</function>. If this is not done, some memory
790 is leaked for each call to <function>PQconninfoParse</function>.
791 Conversely, if an error occurs and <literal>errmsg</> is not NULL,
792 be sure to free the error string using <function>PQfreemem</>.
793 </para>
795 </listitem>
796 </varlistentry>
798 <varlistentry>
799 <term><function>PQfinish</function><indexterm><primary>PQfinish</></></term>
800 <listitem>
801 <para>
802 Closes the connection to the server. Also frees
803 memory used by the <structname>PGconn</structname> object.
804 <synopsis>
805 void PQfinish(PGconn *conn);
806 </synopsis>
807 </para>
809 <para>
810 Note that even if the server connection attempt fails (as
811 indicated by <function>PQstatus</function>), the application should call <function>PQfinish</function>
812 to free the memory used by the <structname>PGconn</structname> object.
813 The <structname>PGconn</> pointer must not be used again after
814 <function>PQfinish</function> has been called.
815 </para>
816 </listitem>
817 </varlistentry>
819 <varlistentry>
820 <term><function>PQreset</function><indexterm><primary>PQreset</></></term>
821 <listitem>
822 <para>
823 Resets the communication channel to the server.
824 <synopsis>
825 void PQreset(PGconn *conn);
826 </synopsis>
827 </para>
829 <para>
830 This function will close the connection
831 to the server and attempt to reestablish a new
832 connection to the same server, using all the same
833 parameters previously used. This might be useful for
834 error recovery if a working connection is lost.
835 </para>
836 </listitem>
837 </varlistentry>
839 <varlistentry>
840 <term><function>PQresetStart</function><indexterm><primary>PQresetStart</></></term>
841 <term><function>PQresetPoll</function><indexterm><primary>PQresetPoll</></></term>
842 <listitem>
843 <para>
844 Reset the communication channel to the server, in a nonblocking manner.
846 <synopsis>
847 int PQresetStart(PGconn *conn);
848 </synopsis>
849 <synopsis>
850 PostgresPollingStatusType PQresetPoll(PGconn *conn);
851 </synopsis>
852 </para>
854 <para>
855 These functions will close the connection to the server and attempt to
856 reestablish a new connection to the same server, using all the same
857 parameters previously used. This can be useful for error recovery if a
858 working connection is lost. They differ from <function>PQreset</function> (above) in that they
859 act in a nonblocking manner. These functions suffer from the same
860 restrictions as <function>PQconnectStart</> and <function>PQconnectPoll</>.
861 </para>
863 <para>
864 To initiate a connection reset, call
865 <function>PQresetStart</function>. If it returns 0, the reset has
866 failed. If it returns 1, poll the reset using
867 <function>PQresetPoll</function> in exactly the same way as you
868 would create the connection using <function>PQconnectPoll</function>.
869 </para>
870 </listitem>
871 </varlistentry>
873 </variablelist>
874 </para>
875 </sect1>
877 <sect1 id="libpq-status">
878 <title>Connection Status Functions</title>
880 <para>
881 These functions can be used to interrogate the status
882 of an existing database connection object.
883 </para>
885 <tip>
886 <para>
887 <indexterm><primary>libpq-fe.h</></>
888 <indexterm><primary>libpq-int.h</></>
889 <application>libpq</application> application programmers should be careful to
890 maintain the <structname>PGconn</structname> abstraction. Use the accessor
891 functions described below to get at the contents of <structname>PGconn</structname>.
892 Reference to internal <structname>PGconn</structname> fields using
893 <filename>libpq-int.h</> is not recommended because they are subject to change
894 in the future.
895 </para>
896 </tip>
898 <para>
899 The following functions return parameter values established at connection.
900 These values are fixed for the life of the <structname>PGconn</> object.
902 <variablelist>
903 <varlistentry>
904 <term>
905 <function>PQdb</function>
906 <indexterm>
907 <primary>PQdb</primary>
908 </indexterm>
909 </term>
911 <listitem>
912 <para>
913 Returns the database name of the connection.
914 <synopsis>
915 char *PQdb(const PGconn *conn);
916 </synopsis>
917 </para>
918 </listitem>
919 </varlistentry>
921 <varlistentry>
922 <term>
923 <function>PQuser</function>
924 <indexterm>
925 <primary>PQuser</primary>
926 </indexterm>
927 </term>
929 <listitem>
930 <para>
931 Returns the user name of the connection.
932 <synopsis>
933 char *PQuser(const PGconn *conn);
934 </synopsis>
935 </para>
936 </listitem>
937 </varlistentry>
939 <varlistentry>
940 <term>
941 <function>PQpass</function>
942 <indexterm>
943 <primary>PQpass</primary>
944 </indexterm>
945 </term>
947 <listitem>
948 <para>
949 Returns the password of the connection.
950 <synopsis>
951 char *PQpass(const PGconn *conn);
952 </synopsis>
953 </para>
954 </listitem>
955 </varlistentry>
957 <varlistentry>
958 <term>
959 <function>PQhost</function>
960 <indexterm>
961 <primary>PQhost</primary>
962 </indexterm>
963 </term>
965 <listitem>
966 <para>
967 Returns the server host name of the connection.
968 <synopsis>
969 char *PQhost(const PGconn *conn);
970 </synopsis>
971 </para>
972 </listitem>
973 </varlistentry>
975 <varlistentry>
976 <term>
977 <function>PQport</function>
978 <indexterm>
979 <primary>PQport</primary>
980 </indexterm>
981 </term>
983 <listitem>
984 <para>
985 Returns the port of the connection.
987 <synopsis>
988 char *PQport(const PGconn *conn);
989 </synopsis>
990 </para>
991 </listitem>
992 </varlistentry>
994 <varlistentry>
995 <term>
996 <function>PQtty</function>
997 <indexterm>
998 <primary>PQtty</primary>
999 </indexterm>
1000 </term>
1002 <listitem>
1003 <para>
1004 Returns the debug <acronym>TTY</acronym> of the connection.
1005 (This is obsolete, since the server no longer pays attention
1006 to the <acronym>TTY</acronym> setting, but the function remains
1007 for backwards compatibility.)
1009 <synopsis>
1010 char *PQtty(const PGconn *conn);
1011 </synopsis>
1012 </para>
1013 </listitem>
1014 </varlistentry>
1016 <varlistentry>
1017 <term>
1018 <function>PQoptions</function>
1019 <indexterm>
1020 <primary>PQoptions</primary>
1021 </indexterm>
1022 </term>
1024 <listitem>
1025 <para>
1026 Returns the command-line options passed in the connection request.
1027 <synopsis>
1028 char *PQoptions(const PGconn *conn);
1029 </synopsis>
1030 </para>
1031 </listitem>
1032 </varlistentry>
1033 </variablelist>
1034 </para>
1036 <para>
1037 The following functions return status data that can change as operations
1038 are executed on the <structname>PGconn</> object.
1040 <variablelist>
1041 <varlistentry>
1042 <term>
1043 <function>PQstatus</function>
1044 <indexterm>
1045 <primary>PQstatus</primary>
1046 </indexterm>
1047 </term>
1049 <listitem>
1050 <para>
1051 Returns the status of the connection.
1052 <synopsis>
1053 ConnStatusType PQstatus(const PGconn *conn);
1054 </synopsis>
1055 </para>
1057 <para>
1058 The status can be one of a number of values. However, only two of
1059 these are seen outside of an asynchronous connection procedure:
1060 <literal>CONNECTION_OK</literal> and
1061 <literal>CONNECTION_BAD</literal>. A good connection to the database
1062 has the status <literal>CONNECTION_OK</literal>. A failed
1063 connection attempt is signaled by status
1064 <literal>CONNECTION_BAD</literal>. Ordinarily, an OK status will
1065 remain so until <function>PQfinish</function>, but a communications
1066 failure might result in the status changing to
1067 <literal>CONNECTION_BAD</literal> prematurely. In that case the
1068 application could try to recover by calling
1069 <function>PQreset</function>.
1070 </para>
1072 <para>
1073 See the entry for <function>PQconnectStart</> and <function>PQconnectPoll</> with regards
1074 to other status codes
1075 that might be seen.
1076 </para>
1077 </listitem>
1078 </varlistentry>
1080 <varlistentry>
1081 <term>
1082 <function>PQtransactionStatus</function>
1083 <indexterm>
1084 <primary>PQtransactionStatus</primary>
1085 </indexterm>
1086 </term>
1088 <listitem>
1089 <para>
1090 Returns the current in-transaction status of the server.
1092 <synopsis>
1093 PGTransactionStatusType PQtransactionStatus(const PGconn *conn);
1094 </synopsis>
1096 The status can be <literal>PQTRANS_IDLE</literal> (currently idle),
1097 <literal>PQTRANS_ACTIVE</literal> (a command is in progress),
1098 <literal>PQTRANS_INTRANS</literal> (idle, in a valid transaction block),
1099 or <literal>PQTRANS_INERROR</literal> (idle, in a failed transaction block).
1100 <literal>PQTRANS_UNKNOWN</literal> is reported if the connection is bad.
1101 <literal>PQTRANS_ACTIVE</literal> is reported only when a query
1102 has been sent to the server and not yet completed.
1103 </para>
1105 <caution>
1106 <para>
1107 <function>PQtransactionStatus</> will give incorrect results when using
1108 a <productname>PostgreSQL</> 7.3 server that has the parameter <literal>autocommit</>
1109 set to off. The server-side autocommit feature has been
1110 deprecated and does not exist in later server versions.
1111 </para>
1112 </caution>
1113 </listitem>
1114 </varlistentry>
1116 <varlistentry>
1117 <term>
1118 <function>PQparameterStatus</function>
1119 <indexterm>
1120 <primary>PQparameterStatus</primary>
1121 </indexterm>
1122 </term>
1124 <listitem>
1125 <para>
1126 Looks up a current parameter setting of the server.
1128 <synopsis>
1129 const char *PQparameterStatus(const PGconn *conn, const char *paramName);
1130 </synopsis>
1132 Certain parameter values are reported by the server automatically at
1133 connection startup or whenever their values change.
1134 <function>PQparameterStatus</> can be used to interrogate these settings.
1135 It returns the current value of a parameter if known, or <symbol>NULL</symbol>
1136 if the parameter is not known.
1137 </para>
1139 <para>
1140 Parameters reported as of the current release include
1141 <literal>server_version</>,
1142 <literal>server_encoding</>,
1143 <literal>client_encoding</>,
1144 <literal>is_superuser</>,
1145 <literal>session_authorization</>,
1146 <literal>DateStyle</>,
1147 <literal>IntervalStyle</>,
1148 <literal>TimeZone</>,
1149 <literal>integer_datetimes</>, and
1150 <literal>standard_conforming_strings</>.
1151 (<literal>server_encoding</>, <literal>TimeZone</>, and
1152 <literal>integer_datetimes</> were not reported by releases before 8.0;
1153 <literal>standard_conforming_strings</> was not reported by releases
1154 before 8.1; <literal>IntervalStyle</> was not reported by releases
1155 before 8.4.)
1156 Note that
1157 <literal>server_version</>,
1158 <literal>server_encoding</> and
1159 <literal>integer_datetimes</>
1160 cannot change after startup.
1161 </para>
1163 <para>
1164 Pre-3.0-protocol servers do not report parameter settings, but
1165 <application>libpq</> includes logic to obtain values for
1166 <literal>server_version</> and <literal>client_encoding</> anyway.
1167 Applications are encouraged to use <function>PQparameterStatus</>
1168 rather than <foreignphrase>ad hoc</> code to determine these values.
1169 (Beware however that on a pre-3.0 connection, changing
1170 <literal>client_encoding</> via <command>SET</> after connection
1171 startup will not be reflected by <function>PQparameterStatus</>.)
1172 For <literal>server_version</>, see also
1173 <function>PQserverVersion</>, which returns the information in a
1174 numeric form that is much easier to compare against.
1175 </para>
1177 <para>
1178 If no value for <literal>standard_conforming_strings</> is reported,
1179 applications can assume it is <literal>off</>, that is, backslashes
1180 are treated as escapes in string literals. Also, the presence of
1181 this parameter can be taken as an indication that the escape string
1182 syntax (<literal>E'...'</>) is accepted.
1183 </para>
1185 <para>
1186 Although the returned pointer is declared <literal>const</>, it in fact
1187 points to mutable storage associated with the <literal>PGconn</> structure.
1188 It is unwise to assume the pointer will remain valid across queries.
1189 </para>
1190 </listitem>
1191 </varlistentry>
1193 <varlistentry>
1194 <term>
1195 <function>PQprotocolVersion</function>
1196 <indexterm>
1197 <primary>PQprotocolVersion</primary>
1198 </indexterm>
1199 </term>
1201 <listitem>
1202 <para>
1203 Interrogates the frontend/backend protocol being used.
1204 <synopsis>
1205 int PQprotocolVersion(const PGconn *conn);
1206 </synopsis>
1207 Applications might wish to use this to determine whether certain
1208 features are supported. Currently, the possible values are 2 (2.0
1209 protocol), 3 (3.0 protocol), or zero (connection bad). This will
1210 not change after connection startup is complete, but it could
1211 theoretically change during a connection reset. The 3.0 protocol
1212 will normally be used when communicating with
1213 <productname>PostgreSQL</> 7.4 or later servers; pre-7.4 servers
1214 support only protocol 2.0. (Protocol 1.0 is obsolete and not
1215 supported by <application>libpq</application>.)
1216 </para>
1217 </listitem>
1218 </varlistentry>
1220 <varlistentry>
1221 <term>
1222 <function>PQserverVersion</function>
1223 <indexterm>
1224 <primary>PQserverVersion</primary>
1225 </indexterm>
1226 </term>
1228 <listitem>
1229 <para>
1230 Returns an integer representing the backend version.
1231 <synopsis>
1232 int PQserverVersion(const PGconn *conn);
1233 </synopsis>
1234 Applications might use this to determine the version of the database
1235 server they are connected to. The number is formed by converting
1236 the major, minor, and revision numbers into two-decimal-digit
1237 numbers and appending them together. For example, version 8.1.5
1238 will be returned as 80105, and version 8.2 will be returned as
1239 80200 (leading zeroes are not shown). Zero is returned if the
1240 connection is bad.
1241 </para>
1242 </listitem>
1243 </varlistentry>
1245 <varlistentry>
1246 <term>
1247 <function>PQerrorMessage</function>
1248 <indexterm>
1249 <primary>PQerrorMessage</primary>
1250 </indexterm>
1251 </term>
1253 <listitem>
1254 <para>
1255 <indexterm><primary>error message</></> Returns the error message
1256 most recently generated by an operation on the connection.
1258 <synopsis>
1259 char *PQerrorMessage(const PGconn *conn);
1260 </synopsis>
1262 </para>
1264 <para>
1265 Nearly all <application>libpq</> functions will set a message for
1266 <function>PQerrorMessage</function> if they fail. Note that by
1267 <application>libpq</application> convention, a nonempty
1268 <function>PQerrorMessage</function> result can be multiple lines,
1269 and will include a trailing newline. The caller should not free
1270 the result directly. It will be freed when the associated
1271 <structname>PGconn</> handle is passed to
1272 <function>PQfinish</function>. The result string should not be
1273 expected to remain the same across operations on the
1274 <literal>PGconn</> structure.
1275 </para>
1276 </listitem>
1277 </varlistentry>
1279 <varlistentry>
1280 <term><function>PQsocket</function><indexterm><primary>PQsocket</></></term>
1281 <listitem>
1282 <para>
1283 Obtains the file descriptor number of the connection socket to
1284 the server. A valid descriptor will be greater than or equal
1285 to 0; a result of -1 indicates that no server connection is
1286 currently open. (This will not change during normal operation,
1287 but could change during connection setup or reset.)
1289 <synopsis>
1290 int PQsocket(const PGconn *conn);
1291 </synopsis>
1293 </para>
1294 </listitem>
1295 </varlistentry>
1297 <varlistentry>
1298 <term><function>PQbackendPID</function><indexterm><primary>PQbackendPID</></></term>
1299 <listitem>
1300 <para>
1301 Returns the process <acronym>ID</acronym>
1302 (PID)<indexterm><primary>PID</><secondary>determining PID of
1303 server process</><tertiary>in libpq</></> of the backend server
1304 process handling this connection.
1306 <synopsis>
1307 int PQbackendPID(const PGconn *conn);
1308 </synopsis>
1309 </para>
1311 <para>
1312 The backend <acronym>PID</acronym> is useful for debugging
1313 purposes and for comparison to <command>NOTIFY</command>
1314 messages (which include the <acronym>PID</acronym> of the
1315 notifying backend process). Note that the
1316 <acronym>PID</acronym> belongs to a process executing on the
1317 database server host, not the local host!
1318 </para>
1319 </listitem>
1320 </varlistentry>
1322 <varlistentry>
1323 <term><function>PQconnectionNeedsPassword</function><indexterm><primary>PQconnectionNeedsPassword</></></term>
1324 <listitem>
1325 <para>
1326 Returns true (1) if the connection authentication method
1327 required a password, but none was available.
1328 Returns false (0) if not.
1330 <synopsis>
1331 int PQconnectionNeedsPassword(const PGconn *conn);
1332 </synopsis>
1333 </para>
1335 <para>
1336 This function can be applied after a failed connection attempt
1337 to decide whether to prompt the user for a password.
1338 </para>
1339 </listitem>
1340 </varlistentry>
1342 <varlistentry>
1343 <term><function>PQconnectionUsedPassword</function><indexterm><primary>PQconnectionUsedPassword</></></term>
1344 <listitem>
1345 <para>
1346 Returns true (1) if the connection authentication method
1347 used a password. Returns false (0) if not.
1349 <synopsis>
1350 int PQconnectionUsedPassword(const PGconn *conn);
1351 </synopsis>
1352 </para>
1354 <para>
1355 This function can be applied after either a failed or successful
1356 connection attempt to detect whether the server demanded a password.
1357 </para>
1358 </listitem>
1359 </varlistentry>
1361 <varlistentry>
1362 <term><function>PQgetssl</function><indexterm><primary>PQgetssl</></></term>
1363 <listitem>
1364 <para>
1365 <indexterm><primary>SSL</><secondary sortas="libpq">in libpq</secondary></indexterm>
1366 Returns the SSL structure used in the connection, or null
1367 if SSL is not in use.
1369 <synopsis>
1370 SSL *PQgetssl(const PGconn *conn);
1371 </synopsis>
1372 </para>
1374 <para>
1375 This structure can be used to verify encryption levels, check server
1376 certificates, and more. Refer to the <productname>OpenSSL</>
1377 documentation for information about this structure.
1378 </para>
1380 <para>
1381 You must define <symbol>USE_SSL</symbol> in order to get the
1382 correct prototype for this function. Doing this will also
1383 automatically include <filename>ssl.h</filename> from <productname>OpenSSL</productname>.
1384 </para>
1385 </listitem>
1386 </varlistentry>
1388 </variablelist>
1389 </para>
1391 </sect1>
1393 <sect1 id="libpq-exec">
1394 <title>Command Execution Functions</title>
1396 <para>
1397 Once a connection to a database server has been successfully
1398 established, the functions described here are used to perform
1399 SQL queries and commands.
1400 </para>
1402 <sect2 id="libpq-exec-main">
1403 <title>Main Functions</title>
1405 <para>
1406 <variablelist>
1407 <varlistentry>
1408 <term>
1409 <function>PQexec</function>
1410 <indexterm>
1411 <primary>PQexec</primary>
1412 </indexterm>
1413 </term>
1415 <listitem>
1416 <para>
1417 Submits a command to the server and waits for the result.
1419 <synopsis>
1420 PGresult *PQexec(PGconn *conn, const char *command);
1421 </synopsis>
1422 </para>
1424 <para>
1425 Returns a <structname>PGresult</structname> pointer or possibly a null
1426 pointer. A non-null pointer will generally be returned except in
1427 out-of-memory conditions or serious errors such as inability to send
1428 the command to the server. If a null pointer is returned, it should
1429 be treated like a <symbol>PGRES_FATAL_ERROR</symbol> result. Use
1430 <function>PQerrorMessage</function> to get more information about such
1431 errors.
1432 </para>
1433 </listitem>
1434 </varlistentry>
1435 </variablelist>
1437 It is allowed to include multiple SQL commands (separated by semicolons)
1438 in the command string. Multiple queries sent in a single
1439 <function>PQexec</> call are processed in a single transaction, unless
1440 there are explicit <command>BEGIN</command>/<command>COMMIT</command>
1441 commands included in the query string to divide it into multiple
1442 transactions. Note however that the returned
1443 <structname>PGresult</structname> structure describes only the result
1444 of the last command executed from the string. Should one of the
1445 commands fail, processing of the string stops with it and the returned
1446 <structname>PGresult</structname> describes the error condition.
1447 </para>
1449 <para>
1450 <variablelist>
1451 <varlistentry>
1452 <term>
1453 <function>PQexecParams</function>
1454 <indexterm>
1455 <primary>PQexecParams</primary>
1456 </indexterm>
1457 </term>
1459 <listitem>
1460 <para>
1461 Submits a command to the server and waits for the result,
1462 with the ability to pass parameters separately from the SQL
1463 command text.
1465 <synopsis>
1466 PGresult *PQexecParams(PGconn *conn,
1467 const char *command,
1468 int nParams,
1469 const Oid *paramTypes,
1470 const char * const *paramValues,
1471 const int *paramLengths,
1472 const int *paramFormats,
1473 int resultFormat);
1474 </synopsis>
1475 </para>
1477 <para>
1478 <function>PQexecParams</> is like <function>PQexec</>, but offers additional
1479 functionality: parameter values can be specified separately from the command
1480 string proper, and query results can be requested in either text or binary
1481 format. <function>PQexecParams</> is supported only in protocol 3.0 and later
1482 connections; it will fail when using protocol 2.0.
1483 </para>
1485 <para>
1486 The function arguments are:
1488 <variablelist>
1489 <varlistentry>
1490 <term><parameter>conn</parameter></term>
1492 <listitem>
1493 <para>
1494 The connection object to send the command through.
1495 </para>
1496 </listitem>
1497 </varlistentry>
1499 <varlistentry>
1500 <term><parameter>command</parameter></term>
1501 <listitem>
1502 <para>
1503 The SQL command string to be executed. If parameters are used,
1504 they are referred to in the command string as <literal>$1</>,
1505 <literal>$2</>, etc.
1506 </para>
1507 </listitem>
1508 </varlistentry>
1510 <varlistentry>
1511 <term><parameter>nParams</parameter></term>
1512 <listitem>
1513 <para>
1514 The number of parameters supplied; it is the length of the arrays
1515 <parameter>paramTypes[]</>, <parameter>paramValues[]</>,
1516 <parameter>paramLengths[]</>, and <parameter>paramFormats[]</>. (The
1517 array pointers can be <symbol>NULL</symbol> when <parameter>nParams</>
1518 is zero.)
1519 </para>
1520 </listitem>
1521 </varlistentry>
1523 <varlistentry>
1524 <term><parameter>paramTypes[]</parameter></term>
1525 <listitem>
1526 <para>
1527 Specifies, by OID, the data types to be assigned to the
1528 parameter symbols. If <parameter>paramTypes</> is
1529 <symbol>NULL</symbol>, or any particular element in the array
1530 is zero, the server infers a data type for the parameter symbol
1531 in the same way it would do for an untyped literal string.
1532 </para>
1533 </listitem>
1534 </varlistentry>
1536 <varlistentry>
1537 <term><parameter>paramValues[]</parameter></term>
1538 <listitem>
1539 <para>
1540 Specifies the actual values of the parameters. A null pointer
1541 in this array means the corresponding parameter is null;
1542 otherwise the pointer points to a zero-terminated text string
1543 (for text format) or binary data in the format expected by the
1544 server (for binary format).
1545 </para>
1546 </listitem>
1547 </varlistentry>
1549 <varlistentry>
1550 <term><parameter>paramLengths[]</parameter></term>
1551 <listitem>
1552 <para>
1553 Specifies the actual data lengths of binary-format parameters.
1554 It is ignored for null parameters and text-format parameters.
1555 The array pointer can be null when there are no binary parameters.
1556 </para>
1557 </listitem>
1558 </varlistentry>
1560 <varlistentry>
1561 <term><parameter>paramFormats[]</parameter></term>
1562 <listitem>
1563 <para>
1564 Specifies whether parameters are text (put a zero in the
1565 array entry for the corresponding parameter) or binary (put
1566 a one in the array entry for the corresponding parameter).
1567 If the array pointer is null then all parameters are presumed
1568 to be text strings.
1569 </para>
1570 <para>
1571 Values passed in binary format require knowlege of
1572 the internal representation expected by the backend.
1573 For example, integers must be passed in network byte
1574 order. Passing <type>numeric</> values requires
1575 knowledge of the server storage format, as implemented
1577 <filename>src/backend/utils/adt/numeric.c::numeric_send()</> and
1578 <filename>src/backend/utils/adt/numeric.c::numeric_recv()</>.
1579 </para>
1580 </listitem>
1581 </varlistentry>
1583 <varlistentry>
1584 <term><parameter>resultFormat</parameter></term>
1585 <listitem>
1586 <para>
1587 Specify zero to obtain results in text format, or one to obtain
1588 results in binary format. (There is not currently a provision
1589 to obtain different result columns in different formats,
1590 although that is possible in the underlying protocol.)
1591 </para>
1592 </listitem>
1593 </varlistentry>
1594 </variablelist>
1595 </para>
1596 </listitem>
1597 </varlistentry>
1598 </variablelist>
1599 </para>
1601 <para>
1602 The primary advantage of <function>PQexecParams</> over
1603 <function>PQexec</> is that parameter values can be separated from the
1604 command string, thus avoiding the need for tedious and error-prone
1605 quoting and escaping.
1606 </para>
1608 <para>
1609 Unlike <function>PQexec</>, <function>PQexecParams</> allows at most
1610 one SQL command in the given string. (There can be semicolons in it,
1611 but not more than one nonempty command.) This is a limitation of the
1612 underlying protocol, but has some usefulness as an extra defense against
1613 SQL-injection attacks.
1614 </para>
1616 <tip>
1617 <para>
1618 Specifying parameter types via OIDs is tedious, particularly if you prefer
1619 not to hard-wire particular OID values into your program. However, you can
1620 avoid doing so even in cases where the server by itself cannot determine the
1621 type of the parameter, or chooses a different type than you want. In the
1622 SQL command text, attach an explicit cast to the parameter symbol to show what
1623 data type you will send. For example:
1624 <programlisting>
1625 SELECT * FROM mytable WHERE x = $1::bigint;
1626 </programlisting>
1627 This forces parameter <literal>$1</> to be treated as <type>bigint</>, whereas
1628 by default it would be assigned the same type as <literal>x</>. Forcing the
1629 parameter type decision, either this way or by specifying a numeric type OID,
1630 is strongly recommended when sending parameter values in binary format, because
1631 binary format has less redundancy than text format and so there is less chance
1632 that the server will detect a type mismatch mistake for you.
1633 </para>
1634 </tip>
1636 <para>
1637 <variablelist>
1638 <varlistentry>
1639 <term><function>PQprepare</function>
1640 <indexterm>
1641 <primary>PQprepare</primary>
1642 </indexterm>
1643 </term>
1645 <listitem>
1646 <para>
1647 Submits a request to create a prepared statement with the
1648 given parameters, and waits for completion.
1649 <synopsis>
1650 PGresult *PQprepare(PGconn *conn,
1651 const char *stmtName,
1652 const char *query,
1653 int nParams,
1654 const Oid *paramTypes);
1655 </synopsis>
1656 </para>
1658 <para>
1659 <function>PQprepare</> creates a prepared statement for later
1660 execution with <function>PQexecPrepared</>. This feature allows
1661 commands that will be used repeatedly to be parsed and planned just
1662 once, rather than each time they are executed.
1663 <function>PQprepare</> is supported only in protocol 3.0 and later
1664 connections; it will fail when using protocol 2.0.
1665 </para>
1667 <para>
1668 The function creates a prepared statement named
1669 <parameter>stmtName</> from the <parameter>query</> string, which
1670 must contain a single SQL command. <parameter>stmtName</> can be
1671 <literal>""</> to create an unnamed statement, in which case any
1672 pre-existing unnamed statement is automatically replaced; otherwise
1673 it is an error if the statement name is already defined in the
1674 current session. If any parameters are used, they are referred
1675 to in the query as <literal>$1</>, <literal>$2</>, etc.
1676 <parameter>nParams</> is the number of parameters for which types
1677 are pre-specified in the array <parameter>paramTypes[]</>. (The
1678 array pointer can be <symbol>NULL</symbol> when
1679 <parameter>nParams</> is zero.) <parameter>paramTypes[]</>
1680 specifies, by OID, the data types to be assigned to the parameter
1681 symbols. If <parameter>paramTypes</> is <symbol>NULL</symbol>,
1682 or any particular element in the array is zero, the server assigns
1683 a data type to the parameter symbol in the same way it would do
1684 for an untyped literal string. Also, the query can use parameter
1685 symbols with numbers higher than <parameter>nParams</>; data types
1686 will be inferred for these symbols as well. (See
1687 <function>PQdescribePrepared</function> for a means to find out
1688 what data types were inferred.)
1689 </para>
1691 <para>
1692 As with <function>PQexec</>, the result is normally a
1693 <structname>PGresult</structname> object whose contents indicate
1694 server-side success or failure. A null result indicates
1695 out-of-memory or inability to send the command at all. Use
1696 <function>PQerrorMessage</function> to get more information about
1697 such errors.
1698 </para>
1699 </listitem>
1700 </varlistentry>
1701 </variablelist>
1703 Prepared statements for use with <function>PQexecPrepared</> can also
1704 be created by executing SQL <xref linkend="sql-prepare"
1705 endterm="sql-prepare-title"> statements. (But <function>PQprepare</>
1706 is more flexible since it does not require parameter types to be
1707 pre-specified.) Also, although there is no <application>libpq</>
1708 function for deleting a prepared statement, the SQL <xref
1709 linkend="sql-deallocate" endterm="sql-deallocate-title"> statement
1710 can be used for that purpose.
1711 </para>
1713 <para>
1714 <variablelist>
1715 <varlistentry>
1716 <term>
1717 <function>PQexecPrepared</function>
1718 <indexterm>
1719 <primary>PQexecPrepared</primary>
1720 </indexterm>
1721 </term>
1723 <listitem>
1724 <para>
1725 Sends a request to execute a prepared statement with given
1726 parameters, and waits for the result.
1727 <synopsis>
1728 PGresult *PQexecPrepared(PGconn *conn,
1729 const char *stmtName,
1730 int nParams,
1731 const char * const *paramValues,
1732 const int *paramLengths,
1733 const int *paramFormats,
1734 int resultFormat);
1735 </synopsis>
1736 </para>
1738 <para>
1739 <function>PQexecPrepared</> is like <function>PQexecParams</>,
1740 but the command to be executed is specified by naming a
1741 previously-prepared statement, instead of giving a query string.
1742 This feature allows commands that will be used repeatedly to be
1743 parsed and planned just once, rather than each time they are
1744 executed. The statement must have been prepared previously in
1745 the current session. <function>PQexecPrepared</> is supported
1746 only in protocol 3.0 and later connections; it will fail when
1747 using protocol 2.0.
1748 </para>
1750 <para>
1751 The parameters are identical to <function>PQexecParams</>, except that the
1752 name of a prepared statement is given instead of a query string, and the
1753 <parameter>paramTypes[]</> parameter is not present (it is not needed since
1754 the prepared statement's parameter types were determined when it was created).
1755 </para>
1756 </listitem>
1757 </varlistentry>
1759 <varlistentry>
1760 <term>
1761 <function>PQdescribePrepared</function>
1762 <indexterm>
1763 <primary>PQdescribePrepared</primary>
1764 </indexterm>
1765 </term>
1767 <listitem>
1768 <para>
1769 Submits a request to obtain information about the specified
1770 prepared statement, and waits for completion.
1771 <synopsis>
1772 PGresult *PQdescribePrepared(PGconn *conn, const char *stmtName);
1773 </synopsis>
1774 </para>
1776 <para>
1777 <function>PQdescribePrepared</> allows an application to obtain
1778 information about a previously prepared statement.
1779 <function>PQdescribePrepared</> is supported only in protocol 3.0
1780 and later connections; it will fail when using protocol 2.0.
1781 </para>
1783 <para>
1784 <parameter>stmtName</> can be <literal>""</> or NULL to reference
1785 the unnamed statement, otherwise it must be the name of an existing
1786 prepared statement. On success, a <structname>PGresult</> with
1787 status <literal>PGRES_COMMAND_OK</literal> is returned. The
1788 functions <function>PQnparams</function> and
1789 <function>PQparamtype</function> can be applied to this
1790 <structname>PGresult</> to obtain information about the parameters
1791 of the prepared statement, and the functions
1792 <function>PQnfields</function>, <function>PQfname</function>,
1793 <function>PQftype</function>, etc provide information about the
1794 result columns (if any) of the statement.
1795 </para>
1796 </listitem>
1797 </varlistentry>
1799 <varlistentry>
1800 <term>
1801 <function>PQdescribePortal</function>
1802 <indexterm>
1803 <primary>PQdescribePortal</primary>
1804 </indexterm>
1805 </term>
1807 <listitem>
1808 <para>
1809 Submits a request to obtain information about the specified
1810 portal, and waits for completion.
1811 <synopsis>
1812 PGresult *PQdescribePortal(PGconn *conn, const char *portalName);
1813 </synopsis>
1814 </para>
1816 <para>
1817 <function>PQdescribePortal</> allows an application to obtain
1818 information about a previously created portal.
1819 (<application>libpq</> does not provide any direct access to
1820 portals, but you can use this function to inspect the properties
1821 of a cursor created with a <command>DECLARE CURSOR</> SQL command.)
1822 <function>PQdescribePortal</> is supported only in protocol 3.0
1823 and later connections; it will fail when using protocol 2.0.
1824 </para>
1826 <para>
1827 <parameter>portalName</> can be <literal>""</> or NULL to reference
1828 the unnamed portal, otherwise it must be the name of an existing
1829 portal. On success, a <structname>PGresult</> with status
1830 <literal>PGRES_COMMAND_OK</literal> is returned. The functions
1831 <function>PQnfields</function>, <function>PQfname</function>,
1832 <function>PQftype</function>, etc can be applied to the
1833 <structname>PGresult</> to obtain information about the result
1834 columns (if any) of the portal.
1835 </para>
1836 </listitem>
1837 </varlistentry>
1838 </variablelist>
1839 </para>
1841 <para>
1842 The <structname>PGresult</structname><indexterm><primary>PGresult</></>
1843 structure encapsulates the result returned by the server.
1844 <application>libpq</application> application programmers should be
1845 careful to maintain the <structname>PGresult</structname> abstraction.
1846 Use the accessor functions below to get at the contents of
1847 <structname>PGresult</structname>. Avoid directly referencing the
1848 fields of the <structname>PGresult</structname> structure because they
1849 are subject to change in the future.
1851 <variablelist>
1852 <varlistentry>
1853 <term>
1854 <function>PQresultStatus</function>
1855 <indexterm>
1856 <primary>PQresultStatus</primary>
1857 </indexterm>
1858 </term>
1860 <listitem>
1861 <para>
1862 Returns the result status of the command.
1863 <synopsis>
1864 ExecStatusType PQresultStatus(const PGresult *res);
1865 </synopsis>
1866 </para>
1868 <para>
1869 <function>PQresultStatus</function> can return one of the following values:
1871 <variablelist>
1872 <varlistentry>
1873 <term><literal>PGRES_EMPTY_QUERY</literal></term>
1874 <listitem>
1875 <para>
1876 The string sent to the server was empty.
1877 </para>
1878 </listitem>
1879 </varlistentry>
1881 <varlistentry>
1882 <term><literal>PGRES_COMMAND_OK</literal></term>
1883 <listitem>
1884 <para>
1885 Successful completion of a command returning no data.
1886 </para>
1887 </listitem>
1888 </varlistentry>
1890 <varlistentry>
1891 <term><literal>PGRES_TUPLES_OK</literal></term>
1892 <listitem>
1893 <para>
1894 Successful completion of a command returning data (such as
1895 a <command>SELECT</> or <command>SHOW</>).
1896 </para>
1897 </listitem>
1898 </varlistentry>
1900 <varlistentry>
1901 <term><literal>PGRES_COPY_OUT</literal></term>
1902 <listitem>
1903 <para>
1904 Copy Out (from server) data transfer started.
1905 </para>
1906 </listitem>
1907 </varlistentry>
1909 <varlistentry>
1910 <term><literal>PGRES_COPY_IN</literal></term>
1911 <listitem>
1912 <para>
1913 Copy In (to server) data transfer started.
1914 </para>
1915 </listitem>
1916 </varlistentry>
1918 <varlistentry>
1919 <term><literal>PGRES_BAD_RESPONSE</literal></term>
1920 <listitem>
1921 <para>
1922 The server's response was not understood.
1923 </para>
1924 </listitem>
1925 </varlistentry>
1927 <varlistentry>
1928 <term><literal>PGRES_NONFATAL_ERROR</literal></term>
1929 <listitem>
1930 <para>
1931 A nonfatal error (a notice or warning) occurred.
1932 </para>
1933 </listitem>
1934 </varlistentry>
1936 <varlistentry>
1937 <term><literal>PGRES_FATAL_ERROR</literal></term>
1938 <listitem>
1939 <para>
1940 A fatal error occurred.
1941 </para>
1942 </listitem>
1943 </varlistentry>
1944 </variablelist>
1946 If the result status is <literal>PGRES_TUPLES_OK</literal>, then
1947 the functions described below can be used to retrieve the rows
1948 returned by the query. Note that a <command>SELECT</command>
1949 command that happens to retrieve zero rows still shows
1950 <literal>PGRES_TUPLES_OK</literal>.
1951 <literal>PGRES_COMMAND_OK</literal> is for commands that can never
1952 return rows (<command>INSERT</command>, <command>UPDATE</command>,
1953 etc.). A response of <literal>PGRES_EMPTY_QUERY</literal> might
1954 indicate a bug in the client software.
1955 </para>
1957 <para>
1958 A result of status <symbol>PGRES_NONFATAL_ERROR</symbol> will
1959 never be returned directly by <function>PQexec</function> or other
1960 query execution functions; results of this kind are instead passed
1961 to the notice processor (see <xref
1962 linkend="libpq-notice-processing">).
1963 </para>
1964 </listitem>
1965 </varlistentry>
1967 <varlistentry>
1968 <term>
1969 <function>PQresStatus</function>
1970 <indexterm>
1971 <primary>PQresStatus</primary>
1972 </indexterm>
1973 </term>
1975 <listitem>
1976 <para>
1977 Converts the enumerated type returned by
1978 <function>PQresultStatus</> into a string constant describing the
1979 status code. The caller should not free the result.
1981 <synopsis>
1982 char *PQresStatus(ExecStatusType status);
1983 </synopsis>
1984 </para>
1985 </listitem>
1986 </varlistentry>
1988 <varlistentry>
1989 <term>
1990 <function>PQresultErrorMessage</function>
1991 <indexterm>
1992 <primary>PQresultErrorMessage</primary>
1993 </indexterm>
1994 </term>
1996 <listitem>
1997 <para>
1998 Returns the error message associated with the command, or an empty string
1999 if there was no error.
2000 <synopsis>
2001 char *PQresultErrorMessage(const PGresult *res);
2002 </synopsis>
2003 If there was an error, the returned string will include a trailing
2004 newline. The caller should not free the result directly. It will
2005 be freed when the associated <structname>PGresult</> handle is
2006 passed to <function>PQclear</function>.
2007 </para>
2009 <para>
2010 Immediately following a <function>PQexec</function> or
2011 <function>PQgetResult</function> call,
2012 <function>PQerrorMessage</function> (on the connection) will return
2013 the same string as <function>PQresultErrorMessage</function> (on
2014 the result). However, a <structname>PGresult</structname> will
2015 retain its error message until destroyed, whereas the connection's
2016 error message will change when subsequent operations are done.
2017 Use <function>PQresultErrorMessage</function> when you want to
2018 know the status associated with a particular
2019 <structname>PGresult</structname>; use
2020 <function>PQerrorMessage</function> when you want to know the
2021 status from the latest operation on the connection.
2022 </para>
2023 </listitem>
2024 </varlistentry>
2026 <varlistentry>
2027 <term><function>PQresultErrorField</function><indexterm><primary>PQresultErrorField</></></term>
2028 <listitem>
2029 <para>
2030 Returns an individual field of an error report.
2031 <synopsis>
2032 char *PQresultErrorField(const PGresult *res, int fieldcode);
2033 </synopsis>
2034 <parameter>fieldcode</> is an error field identifier; see the symbols
2035 listed below. <symbol>NULL</symbol> is returned if the
2036 <structname>PGresult</structname> is not an error or warning result,
2037 or does not include the specified field. Field values will normally
2038 not include a trailing newline. The caller should not free the
2039 result directly. It will be freed when the
2040 associated <structname>PGresult</> handle is passed to
2041 <function>PQclear</function>.
2042 </para>
2044 <para>
2045 The following field codes are available:
2046 <variablelist>
2047 <varlistentry>
2048 <term><symbol>PG_DIAG_SEVERITY</></term>
2049 <listitem>
2050 <para>
2051 The severity; the field contents are <literal>ERROR</>,
2052 <literal>FATAL</>, or <literal>PANIC</> (in an error message),
2053 or <literal>WARNING</>, <literal>NOTICE</>, <literal>DEBUG</>,
2054 <literal>INFO</>, or <literal>LOG</> (in a notice message), or
2055 a localized translation of one of these. Always present.
2056 </para>
2057 </listitem>
2058 </varlistentry>
2060 <varlistentry>
2061 <indexterm>
2062 <primary>error codes</primary>
2063 <secondary>libpq</secondary>
2064 </indexterm>
2065 <term><symbol>PG_DIAG_SQLSTATE</></term>
2066 <listitem>
2067 <para>
2068 The SQLSTATE code for the error. The SQLSTATE code identifies
2069 the type of error that has occurred; it can be used by
2070 front-end applications to perform specific operations (such
2071 as error handling) in response to a particular database error.
2072 For a list of the possible SQLSTATE codes, see <xref
2073 linkend="errcodes-appendix">. This field is not localizable,
2074 and is always present.
2075 </para>
2076 </listitem>
2077 </varlistentry>
2079 <varlistentry>
2080 <term><symbol>PG_DIAG_MESSAGE_PRIMARY</></term>
2081 <listitem>
2082 <para>
2083 The primary human-readable error message (typically one line).
2084 Always present.
2085 </para>
2086 </listitem>
2087 </varlistentry>
2089 <varlistentry>
2090 <term><symbol>PG_DIAG_MESSAGE_DETAIL</></term>
2091 <listitem>
2092 <para>
2093 Detail: an optional secondary error message carrying more
2094 detail about the problem. Might run to multiple lines.
2095 </para>
2096 </listitem>
2097 </varlistentry>
2099 <varlistentry>
2100 <term><symbol>PG_DIAG_MESSAGE_HINT</></term>
2101 <listitem>
2102 <para>
2103 Hint: an optional suggestion what to do about the problem.
2104 This is intended to differ from detail in that it offers advice
2105 (potentially inappropriate) rather than hard facts. Might
2106 run to multiple lines.
2107 </para>
2108 </listitem>
2109 </varlistentry>
2111 <varlistentry>
2112 <term><symbol>PG_DIAG_STATEMENT_POSITION</></term>
2113 <listitem>
2114 <para>
2115 A string containing a decimal integer indicating an error cursor
2116 position as an index into the original statement string. The
2117 first character has index 1, and positions are measured in
2118 characters not bytes.
2119 </para>
2120 </listitem>
2121 </varlistentry>
2123 <varlistentry>
2124 <term><symbol>PG_DIAG_INTERNAL_POSITION</></term>
2125 <listitem>
2126 <para>
2127 This is defined the same as the
2128 <symbol>PG_DIAG_STATEMENT_POSITION</> field, but it is used
2129 when the cursor position refers to an internally generated
2130 command rather than the one submitted by the client. The
2131 <symbol>PG_DIAG_INTERNAL_QUERY</> field will always appear when
2132 this field appears.
2133 </para>
2134 </listitem>
2135 </varlistentry>
2137 <varlistentry>
2138 <term><symbol>PG_DIAG_INTERNAL_QUERY</></term>
2139 <listitem>
2140 <para>
2141 The text of a failed internally-generated command. This could
2142 be, for example, a SQL query issued by a PL/pgSQL function.
2143 </para>
2144 </listitem>
2145 </varlistentry>
2147 <varlistentry>
2148 <term><symbol>PG_DIAG_CONTEXT</></term>
2149 <listitem>
2150 <para>
2151 An indication of the context in which the error occurred.
2152 Presently this includes a call stack traceback of active
2153 procedural language functions and internally-generated queries.
2154 The trace is one entry per line, most recent first.
2155 </para>
2156 </listitem>
2157 </varlistentry>
2159 <varlistentry>
2160 <term><symbol>PG_DIAG_SOURCE_FILE</></term>
2161 <listitem>
2162 <para>
2163 The file name of the source-code location where the error was
2164 reported.
2165 </para>
2166 </listitem>
2167 </varlistentry>
2169 <varlistentry>
2170 <term><symbol>PG_DIAG_SOURCE_LINE</></term>
2171 <listitem>
2172 <para>
2173 The line number of the source-code location where the error
2174 was reported.
2175 </para>
2176 </listitem>
2177 </varlistentry>
2179 <varlistentry>
2180 <term><symbol>PG_DIAG_SOURCE_FUNCTION</></term>
2181 <listitem>
2182 <para>
2183 The name of the source-code function reporting the error.
2184 </para>
2185 </listitem>
2186 </varlistentry>
2187 </variablelist>
2188 </para>
2190 <para>
2191 The client is responsible for formatting displayed information to meet
2192 its needs; in particular it should break long lines as needed.
2193 Newline characters appearing in the error message fields should be
2194 treated as paragraph breaks, not line breaks.
2195 </para>
2197 <para>
2198 Errors generated internally by <application>libpq</application> will
2199 have severity and primary message, but typically no other fields.
2200 Errors returned by a pre-3.0-protocol server will include severity and
2201 primary message, and sometimes a detail message, but no other fields.
2202 </para>
2204 <para>
2205 Note that error fields are only available from
2206 <structname>PGresult</structname> objects, not
2207 <structname>PGconn</structname> objects; there is no
2208 <function>PQerrorField</function> function.
2209 </para>
2210 </listitem>
2211 </varlistentry>
2213 <varlistentry>
2214 <term><function>PQclear</function><indexterm><primary>PQclear</></></term>
2215 <listitem>
2216 <para>
2217 Frees the storage associated with a
2218 <structname>PGresult</structname>. Every command result should be
2219 freed via <function>PQclear</function> when it is no longer
2220 needed.
2222 <synopsis>
2223 void PQclear(PGresult *res);
2224 </synopsis>
2225 </para>
2227 <para>
2228 You can keep a <structname>PGresult</structname> object around for
2229 as long as you need it; it does not go away when you issue a new
2230 command, nor even if you close the connection. To get rid of it,
2231 you must call <function>PQclear</function>. Failure to do this
2232 will result in memory leaks in your application.
2233 </para>
2234 </listitem>
2235 </varlistentry>
2236 </variablelist>
2237 </para>
2238 </sect2>
2240 <sect2 id="libpq-exec-select-info">
2241 <title>Retrieving Query Result Information</title>
2243 <para>
2244 These functions are used to extract information from a
2245 <structname>PGresult</structname> object that represents a successful
2246 query result (that is, one that has status
2247 <literal>PGRES_TUPLES_OK</literal>). They can also be used to extract
2248 information from a successful Describe operation: a Describe's result
2249 has all the same column information that actual execution of the query
2250 would provide, but it has zero rows. For objects with other status values,
2251 these functions will act as though the result has zero rows and zero columns.
2252 </para>
2254 <variablelist>
2255 <varlistentry>
2256 <term>
2257 <function>PQntuples</function>
2258 <indexterm>
2259 <primary>PQntuples</primary>
2260 </indexterm>
2261 </term>
2263 <listitem>
2264 <para>
2265 Returns the number of rows (tuples) in the query result. Because
2266 it returns an integer result, large result sets might overflow the
2267 return value on 32-bit operating systems.
2269 <synopsis>
2270 int PQntuples(const PGresult *res);
2271 </synopsis>
2273 </para>
2274 </listitem>
2275 </varlistentry>
2277 <varlistentry>
2278 <term>
2279 <function>PQnfields</function>
2280 <indexterm>
2281 <primary>PQnfields</primary>
2282 </indexterm>
2283 </term>
2285 <listitem>
2286 <para>
2287 Returns the number of columns (fields) in each row of the query
2288 result.
2290 <synopsis>
2291 int PQnfields(const PGresult *res);
2292 </synopsis>
2293 </para>
2294 </listitem>
2295 </varlistentry>
2297 <varlistentry>
2298 <term>
2299 <function>PQfname</function>
2300 <indexterm>
2301 <primary>PQfname</primary>
2302 </indexterm>
2303 </term>
2305 <listitem>
2306 <para>
2307 Returns the column name associated with the given column number.
2308 Column numbers start at 0. The caller should not free the result
2309 directly. It will be freed when the associated
2310 <structname>PGresult</> handle is passed to
2311 <function>PQclear</function>.
2312 <synopsis>
2313 char *PQfname(const PGresult *res,
2314 int column_number);
2315 </synopsis>
2316 </para>
2318 <para>
2319 <symbol>NULL</symbol> is returned if the column number is out of range.
2320 </para>
2321 </listitem>
2322 </varlistentry>
2324 <varlistentry>
2325 <term>
2326 <function>PQfnumber</function>
2327 <indexterm>
2328 <primary>PQfnumber</primary>
2329 </indexterm>
2330 </term>
2332 <listitem>
2333 <para>
2334 Returns the column number associated with the given column name.
2335 <synopsis>
2336 int PQfnumber(const PGresult *res,
2337 const char *column_name);
2338 </synopsis>
2339 </para>
2341 <para>
2342 -1 is returned if the given name does not match any column.
2343 </para>
2345 <para>
2346 The given name is treated like an identifier in an SQL command,
2347 that is, it is downcased unless double-quoted. For example, given
2348 a query result generated from the SQL command:
2349 <programlisting>
2350 SELECT 1 AS FOO, 2 AS "BAR";
2351 </programlisting>
2352 we would have the results:
2353 <programlisting>
2354 PQfname(res, 0) <lineannotation>foo</lineannotation>
2355 PQfname(res, 1) <lineannotation>BAR</lineannotation>
2356 PQfnumber(res, "FOO") <lineannotation>0</lineannotation>
2357 PQfnumber(res, "foo") <lineannotation>0</lineannotation>
2358 PQfnumber(res, "BAR") <lineannotation>-1</lineannotation>
2359 PQfnumber(res, "\"BAR\"") <lineannotation>1</lineannotation>
2360 </programlisting>
2361 </para>
2362 </listitem>
2363 </varlistentry>
2365 <varlistentry>
2366 <term>
2367 <function>PQftable</function>
2368 <indexterm>
2369 <primary>PQftable</primary>
2370 </indexterm>
2371 </term>
2373 <listitem>
2374 <para>
2375 Returns the OID of the table from which the given column was
2376 fetched. Column numbers start at 0.
2377 <synopsis>
2378 Oid PQftable(const PGresult *res,
2379 int column_number);
2380 </synopsis>
2381 </para>
2383 <para>
2384 <literal>InvalidOid</> is returned if the column number is out of range,
2385 or if the specified column is not a simple reference to a table column,
2386 or when using pre-3.0 protocol.
2387 You can query the system table <literal>pg_class</literal> to determine
2388 exactly which table is referenced.
2389 </para>
2391 <para>
2392 The type <type>Oid</type> and the constant
2393 <literal>InvalidOid</literal> will be defined when you include
2394 the <application>libpq</application> header file. They will both
2395 be some integer type.
2396 </para>
2397 </listitem>
2398 </varlistentry>
2400 <varlistentry>
2401 <term>
2402 <function>PQftablecol</function>
2403 <indexterm>
2404 <primary>PQftablecol</primary>
2405 </indexterm>
2406 </term>
2408 <listitem>
2409 <para>
2410 Returns the column number (within its table) of the column making
2411 up the specified query result column. Query-result column numbers
2412 start at 0, but table columns have nonzero numbers.
2413 <synopsis>
2414 int PQftablecol(const PGresult *res,
2415 int column_number);
2416 </synopsis>
2417 </para>
2419 <para>
2420 Zero is returned if the column number is out of range, or if the
2421 specified column is not a simple reference to a table column, or
2422 when using pre-3.0 protocol.
2423 </para>
2424 </listitem>
2425 </varlistentry>
2427 <varlistentry>
2428 <term>
2429 <function>PQfformat</function>
2430 <indexterm>
2431 <primary>PQfformat</primary>
2432 </indexterm>
2433 </term>
2435 <listitem>
2436 <para>
2437 Returns the format code indicating the format of the given
2438 column. Column numbers start at 0.
2439 <synopsis>
2440 int PQfformat(const PGresult *res,
2441 int column_number);
2442 </synopsis>
2443 </para>
2445 <para>
2446 Format code zero indicates textual data representation, while format
2447 code one indicates binary representation. (Other codes are reserved
2448 for future definition.)
2449 </para>
2450 </listitem>
2451 </varlistentry>
2453 <varlistentry>
2454 <term>
2455 <function>PQftype</function>
2456 <indexterm>
2457 <primary>PQftype</primary>
2458 </indexterm>
2459 </term>
2461 <listitem>
2462 <para>
2463 Returns the data type associated with the given column number.
2464 The integer returned is the internal OID number of the type.
2465 Column numbers start at 0.
2466 <synopsis>
2467 Oid PQftype(const PGresult *res,
2468 int column_number);
2469 </synopsis>
2470 </para>
2472 <para>
2473 You can query the system table <literal>pg_type</literal> to
2474 obtain the names and properties of the various data types. The
2475 <acronym>OID</acronym>s of the built-in data types are defined
2476 in the file <filename>src/include/catalog/pg_type.h</filename>
2477 in the source tree.
2478 </para>
2479 </listitem>
2480 </varlistentry>
2482 <varlistentry>
2483 <term>
2484 <function>PQfmod</function>
2485 <indexterm>
2486 <primary>PQfmod</primary>
2487 </indexterm>
2488 </term>
2490 <listitem>
2491 <para>
2492 Returns the type modifier of the column associated with the
2493 given column number. Column numbers start at 0.
2494 <synopsis>
2495 int PQfmod(const PGresult *res,
2496 int column_number);
2497 </synopsis>
2498 </para>
2500 <para>
2501 The interpretation of modifier values is type-specific; they
2502 typically indicate precision or size limits. The value -1 is
2503 used to indicate <quote>no information available</>. Most data
2504 types do not use modifiers, in which case the value is always
2506 </para>
2507 </listitem>
2508 </varlistentry>
2510 <varlistentry>
2511 <term>
2512 <function>PQfsize</function>
2513 <indexterm>
2514 <primary>PQfsize</primary>
2515 </indexterm>
2516 </term>
2518 <listitem>
2519 <para>
2520 Returns the size in bytes of the column associated with the
2521 given column number. Column numbers start at 0.
2522 <synopsis>
2523 int PQfsize(const PGresult *res,
2524 int column_number);
2525 </synopsis>
2526 </para>
2528 <para>
2529 <function>PQfsize</> returns the space allocated for this column
2530 in a database row, in other words the size of the server's
2531 internal representation of the data type. (Accordingly, it is
2532 not really very useful to clients.) A negative value indicates
2533 the data type is variable-length.
2534 </para>
2535 </listitem>
2536 </varlistentry>
2538 <varlistentry>
2539 <term>
2540 <function>PQbinaryTuples</function>
2541 <indexterm>
2542 <primary>PQbinaryTuples</primary>
2543 </indexterm>
2544 </term>
2546 <listitem>
2547 <para>
2548 Returns 1 if the <structname>PGresult</> contains binary data
2549 and 0 if it contains text data.
2550 <synopsis>
2551 int PQbinaryTuples(const PGresult *res);
2552 </synopsis>
2553 </para>
2555 <para>
2556 This function is deprecated (except for its use in connection with
2557 <command>COPY</>), because it is possible for a single
2558 <structname>PGresult</> to contain text data in some columns and
2559 binary data in others. <function>PQfformat</> is preferred.
2560 <function>PQbinaryTuples</> returns 1 only if all columns of the
2561 result are binary (format 1).
2562 </para>
2563 </listitem>
2564 </varlistentry>
2566 <varlistentry>
2567 <term>
2568 <function>PQgetvalue</function>
2569 <indexterm>
2570 <primary>PQgetvalue</primary>
2571 </indexterm>
2572 </term>
2574 <listitem>
2575 <para>
2576 Returns a single field value of one row of a
2577 <structname>PGresult</structname>. Row and column numbers start
2578 at 0. The caller should not free the result directly. It will
2579 be freed when the associated <structname>PGresult</> handle is
2580 passed to <function>PQclear</function>.
2581 <synopsis>
2582 char *PQgetvalue(const PGresult *res,
2583 int row_number,
2584 int column_number);
2585 </synopsis>
2586 </para>
2588 <para>
2589 For data in text format, the value returned by
2590 <function>PQgetvalue</function> is a null-terminated character
2591 string representation of the field value. For data in binary
2592 format, the value is in the binary representation determined by
2593 the data type's <function>typsend</> and <function>typreceive</>
2594 functions. (The value is actually followed by a zero byte in
2595 this case too, but that is not ordinarily useful, since the
2596 value is likely to contain embedded nulls.)
2597 </para>
2599 <para>
2600 An empty string is returned if the field value is null. See
2601 <function>PQgetisnull</> to distinguish null values from
2602 empty-string values.
2603 </para>
2605 <para>
2606 The pointer returned by <function>PQgetvalue</function> points
2607 to storage that is part of the <structname>PGresult</structname>
2608 structure. One should not modify the data it points to, and one
2609 must explicitly copy the data into other storage if it is to be
2610 used past the lifetime of the <structname>PGresult</structname>
2611 structure itself.
2612 </para>
2613 </listitem>
2614 </varlistentry>
2616 <varlistentry>
2617 <term>
2618 <function>PQgetisnull</function>
2619 <indexterm>
2620 <primary>PQgetisnull</primary>
2621 </indexterm>
2622 <indexterm>
2623 <primary>null value</primary>
2624 <secondary sortas="libpq">in libpq</secondary>
2625 </indexterm>
2626 </term>
2628 <listitem>
2629 <para>
2630 Tests a field for a null value. Row and column numbers start
2631 at 0.
2632 <synopsis>
2633 int PQgetisnull(const PGresult *res,
2634 int row_number,
2635 int column_number);
2636 </synopsis>
2637 </para>
2639 <para>
2640 This function returns 1 if the field is null and 0 if it
2641 contains a non-null value. (Note that
2642 <function>PQgetvalue</function> will return an empty string,
2643 not a null pointer, for a null field.)
2644 </para>
2645 </listitem>
2646 </varlistentry>
2648 <varlistentry>
2649 <term>
2650 <function>PQgetlength</function>
2651 <indexterm>
2652 <primary>PQgetlength</primary>
2653 </indexterm></term>
2655 <listitem>
2656 <para>
2657 Returns the actual length of a field value in bytes. Row and
2658 column numbers start at 0.
2659 <synopsis>
2660 int PQgetlength(const PGresult *res,
2661 int row_number,
2662 int column_number);
2663 </synopsis>
2664 </para>
2666 <para>
2667 This is the actual data length for the particular data value,
2668 that is, the size of the object pointed to by
2669 <function>PQgetvalue</function>. For text data format this is
2670 the same as <function>strlen()</>. For binary format this is
2671 essential information. Note that one should <emphasis>not</>
2672 rely on <function>PQfsize</function> to obtain the actual data
2673 length.
2674 </para>
2675 </listitem>
2676 </varlistentry>
2678 <varlistentry>
2679 <term>
2680 <function>PQnparams</function>
2681 <indexterm>
2682 <primary>PQnparams</primary>
2683 </indexterm>
2684 </term>
2686 <listitem>
2687 <para>
2688 Returns the number of parameters of a prepared statement.
2689 <synopsis>
2690 int PQnparams(const PGresult *res);
2691 </synopsis>
2692 </para>
2694 <para>
2695 This function is only useful when inspecting the result of
2696 <function>PQdescribePrepared</>. For other types of queries it
2697 will return zero.
2698 </para>
2699 </listitem>
2700 </varlistentry>
2702 <varlistentry>
2703 <term>
2704 <function>PQparamtype</function>
2705 <indexterm>
2706 <primary>PQparamtype</primary>
2707 </indexterm>
2708 </term>
2710 <listitem>
2711 <para>
2712 Returns the data type of the indicated statement parameter.
2713 Parameter numbers start at 0.
2714 <synopsis>
2715 Oid PQparamtype(const PGresult *res, int param_number);
2716 </synopsis>
2717 </para>
2719 <para>
2720 This function is only useful when inspecting the result of
2721 <function>PQdescribePrepared</>. For other types of queries it
2722 will return zero.
2723 </para>
2724 </listitem>
2725 </varlistentry>
2727 <varlistentry>
2728 <term>
2729 <function>PQprint</function>
2730 <indexterm>
2731 <primary>PQprint</primary>
2732 </indexterm>
2733 </term>
2735 <listitem>
2736 <para>
2737 Prints out all the rows and, optionally, the column names to
2738 the specified output stream.
2739 <synopsis>
2740 void PQprint(FILE *fout, /* output stream */
2741 const PGresult *res,
2742 const PQprintOpt *po);
2743 typedef struct {
2744 pqbool header; /* print output field headings and row count */
2745 pqbool align; /* fill align the fields */
2746 pqbool standard; /* old brain dead format */
2747 pqbool html3; /* output HTML tables */
2748 pqbool expanded; /* expand tables */
2749 pqbool pager; /* use pager for output if needed */
2750 char *fieldSep; /* field separator */
2751 char *tableOpt; /* attributes for HTML table element */
2752 char *caption; /* HTML table caption */
2753 char **fieldName; /* null-terminated array of replacement field names */
2754 } PQprintOpt;
2755 </synopsis>
2756 </para>
2758 <para>
2759 This function was formerly used by <application>psql</application>
2760 to print query results, but this is no longer the case. Note
2761 that it assumes all the data is in text format.
2762 </para>
2763 </listitem>
2764 </varlistentry>
2765 </variablelist>
2766 </sect2>
2768 <sect2 id="libpq-exec-nonselect">
2769 <title>Retrieving Result Information for Other Commands</title>
2771 <para>
2772 These functions are used to extract information from
2773 <structname>PGresult</structname> objects that are not
2774 <command>SELECT</> results.
2775 </para>
2777 <variablelist>
2778 <varlistentry>
2779 <term>
2780 <function>PQcmdStatus</function>
2781 <indexterm>
2782 <primary>PQcmdStatus</primary>
2783 </indexterm>
2784 </term>
2786 <listitem>
2787 <para>
2788 Returns the command status tag from the SQL command that generated
2789 the <structname>PGresult</structname>.
2790 <synopsis>
2791 char *PQcmdStatus(PGresult *res);
2792 </synopsis>
2793 </para>
2795 <para>
2796 Commonly this is just the name of the command, but it might include
2797 additional data such as the number of rows processed. The caller
2798 should not free the result directly. It will be freed when the
2799 associated <structname>PGresult</> handle is passed to
2800 <function>PQclear</function>.
2801 </para>
2802 </listitem>
2803 </varlistentry>
2805 <varlistentry>
2806 <term>
2807 <function>PQcmdTuples</function>
2808 <indexterm>
2809 <primary>PQcmdTuples</primary>
2810 </indexterm>
2811 </term>
2813 <listitem>
2814 <para>
2815 Returns the number of rows affected by the SQL command.
2816 <synopsis>
2817 char *PQcmdTuples(PGresult *res);
2818 </synopsis>
2819 </para>
2821 <para>
2822 This function returns a string containing the number of rows
2823 affected by the <acronym>SQL</> statement that generated the
2824 <structname>PGresult</>. This function can only be used following
2825 the execution of an <command>INSERT</>, <command>UPDATE</>,
2826 <command>DELETE</>, <command>MOVE</>, <command>FETCH</>, or
2827 <command>COPY</> statement, or an <command>EXECUTE</> of a
2828 prepared query that contains an <command>INSERT</>,
2829 <command>UPDATE</>, or <command>DELETE</> statement. If the
2830 command that generated the <structname>PGresult</> was anything
2831 else, <function>PQcmdTuples</> returns an empty string. The caller
2832 should not free the return value directly. It will be freed when
2833 the associated <structname>PGresult</> handle is passed to
2834 <function>PQclear</function>.
2835 </para>
2836 </listitem>
2837 </varlistentry>
2839 <varlistentry>
2840 <term>
2841 <function>PQoidValue</function>
2842 <indexterm>
2843 <primary>PQoidValue</primary>
2844 </indexterm>
2845 </term>
2847 <listitem>
2848 <para>
2849 Returns the OID<indexterm><primary>OID</><secondary>in libpq</></>
2850 of the inserted row, if the <acronym>SQL</> command was an
2851 <command>INSERT</> that inserted exactly one row into a table that
2852 has OIDs, or a <command>EXECUTE</> of a prepared query containing
2853 a suitable <command>INSERT</> statement. Otherwise, this function
2854 returns <literal>InvalidOid</literal>. This function will also
2855 return <literal>InvalidOid</literal> if the table affected by the
2856 <command>INSERT</> statement does not contain OIDs.
2857 <synopsis>
2858 Oid PQoidValue(const PGresult *res);
2859 </synopsis>
2860 </para>
2861 </listitem>
2862 </varlistentry>
2864 <varlistentry>
2865 <term>
2866 <function>PQoidStatus</function>
2867 <indexterm>
2868 <primary>PQoidStatus</primary>
2869 </indexterm>
2870 </term>
2872 <listitem>
2873 <para>
2874 Returns a string with the OID of the inserted row, if the
2875 <acronym>SQL</acronym> command was an <command>INSERT</command>
2876 that inserted exactly one row, or a <command>EXECUTE</command> of
2877 a prepared statement consisting of a suitable
2878 <command>INSERT</command>. (The string will be <literal>0</> if
2879 the <command>INSERT</command> did not insert exactly one row, or
2880 if the target table does not have OIDs.) If the command was not
2881 an <command>INSERT</command>, returns an empty string.
2882 <synopsis>
2883 char *PQoidStatus(const PGresult *res);
2884 </synopsis>
2885 </para>
2887 <para>
2888 This function is deprecated in favor of
2889 <function>PQoidValue</function>. It is not thread-safe.
2890 </para>
2891 </listitem>
2892 </varlistentry>
2893 </variablelist>
2895 </sect2>
2897 <sect2 id="libpq-exec-escape-string">
2898 <title>Escaping Strings for Inclusion in SQL Commands</title>
2900 <indexterm zone="libpq-exec-escape-string">
2901 <primary>PQescapeStringConn</primary>
2902 </indexterm>
2903 <indexterm zone="libpq-exec-escape-string">
2904 <primary>PQescapeString</primary>
2905 </indexterm>
2906 <indexterm zone="libpq-exec-escape-string">
2907 <primary>escaping strings</primary>
2908 <secondary>in libpq</secondary>
2909 </indexterm>
2911 <para>
2912 <function>PQescapeStringConn</function> escapes a string for use within an SQL
2913 command. This is useful when inserting data values as literal constants
2914 in SQL commands. Certain characters (such as quotes and backslashes) must
2915 be escaped to prevent them from being interpreted specially by the SQL parser.
2916 <function>PQescapeStringConn</> performs this operation.
2917 </para>
2919 <tip>
2920 <para>
2921 It is especially important to do proper escaping when handling strings that
2922 were received from an untrustworthy source. Otherwise there is a security
2923 risk: you are vulnerable to <quote>SQL injection</> attacks wherein unwanted
2924 SQL commands are fed to your database.
2925 </para>
2926 </tip>
2928 <para>
2929 Note that it is not necessary nor correct to do escaping when a data
2930 value is passed as a separate parameter in <function>PQexecParams</> or
2931 its sibling routines.
2933 <synopsis>
2934 size_t PQescapeStringConn (PGconn *conn,
2935 char *to, const char *from, size_t length,
2936 int *error);
2937 </synopsis>
2938 </para>
2940 <para>
2941 <function>PQescapeStringConn</> writes an escaped version of the
2942 <parameter>from</> string to the <parameter>to</> buffer, escaping
2943 special characters so that they cannot cause any harm, and adding a
2944 terminating zero byte. The single quotes that must surround
2945 <productname>PostgreSQL</> string literals are not included in the
2946 result string; they should be provided in the SQL command that the
2947 result is inserted into. The parameter <parameter>from</> points to
2948 the first character of the string that is to be escaped, and the
2949 <parameter>length</> parameter gives the number of bytes in this
2950 string. A terminating zero byte is not required, and should not be
2951 counted in <parameter>length</>. (If a terminating zero byte is found
2952 before <parameter>length</> bytes are processed,
2953 <function>PQescapeStringConn</> stops at the zero; the behavior is
2954 thus rather like <function>strncpy</>.) <parameter>to</> shall point
2955 to a buffer that is able to hold at least one more byte than twice
2956 the value of <parameter>length</>, otherwise the behavior is undefined.
2957 Behavior is likewise undefined if the <parameter>to</> and
2958 <parameter>from</> strings overlap.
2959 </para>
2961 <para>
2962 If the <parameter>error</> parameter is not NULL, then
2963 <literal>*error</> is set to zero on success, nonzero on error.
2964 Presently the only possible error conditions involve invalid multibyte
2965 encoding in the source string. The output string is still generated
2966 on error, but it can be expected that the server will reject it as
2967 malformed. On error, a suitable message is stored in the
2968 <parameter>conn</> object, whether or not <parameter>error</> is NULL.
2969 </para>
2971 <para>
2972 <function>PQescapeStringConn</> returns the number of bytes written
2973 to <parameter>to</>, not including the terminating zero byte.
2974 </para>
2976 <para>
2977 <synopsis>
2978 size_t PQescapeString (char *to, const char *from, size_t length);
2979 </synopsis>
2980 </para>
2982 <para>
2983 <function>PQescapeString</> is an older, deprecated version of
2984 <function>PQescapeStringConn</>; the difference is that it does
2985 not take <parameter>conn</> or <parameter>error</> parameters.
2986 Because of this, it cannot adjust its behavior depending on the
2987 connection properties (such as character encoding) and therefore
2988 <emphasis>it might give the wrong results</>. Also, it has no way
2989 to report error conditions.
2990 </para>
2992 <para>
2993 <function>PQescapeString</> can be used safely in single-threaded
2994 client programs that work with only one <productname>PostgreSQL</>
2995 connection at a time (in this case it can find out what it needs to
2996 know <quote>behind the scenes</>). In other contexts it is a security
2997 hazard and should be avoided in favor of
2998 <function>PQescapeStringConn</>.
2999 </para>
3000 </sect2>
3003 <sect2 id="libpq-exec-escape-bytea">
3004 <title>Escaping Binary Strings for Inclusion in SQL Commands</title>
3006 <indexterm zone="libpq-exec-escape-bytea">
3007 <primary>bytea</primary>
3008 <secondary sortas="libpq">in libpq</secondary>
3009 </indexterm>
3011 <variablelist>
3012 <varlistentry>
3013 <term>
3014 <function>PQescapeByteaConn</function>
3015 <indexterm>
3016 <primary>PQescapeByteaConn</primary>
3017 </indexterm>
3018 </term>
3020 <listitem>
3021 <para>
3022 Escapes binary data for use within an SQL command with the type
3023 <type>bytea</type>. As with <function>PQescapeStringConn</function>,
3024 this is only used when inserting data directly into an SQL command string.
3025 <synopsis>
3026 unsigned char *PQescapeByteaConn(PGconn *conn,
3027 const unsigned char *from,
3028 size_t from_length,
3029 size_t *to_length);
3030 </synopsis>
3031 </para>
3033 <para>
3034 Certain byte values <emphasis>must</emphasis> be escaped (but all
3035 byte values <emphasis>can</emphasis> be escaped) when used as part
3036 of a <type>bytea</type> literal in an <acronym>SQL</acronym>
3037 statement. In general, to escape a byte, it is converted into the
3038 three digit octal number equal to the octet value, and preceded by
3039 usually two backslashes. The single quote (<literal>'</>) and backslash
3040 (<literal>\</>) characters have special alternative escape
3041 sequences. See <xref linkend="datatype-binary"> for more
3042 information. <function>PQescapeByteaConn</function> performs this
3043 operation, escaping only the minimally required bytes.
3044 </para>
3046 <para>
3047 The <parameter>from</parameter> parameter points to the first
3048 byte of the string that is to be escaped, and the
3049 <parameter>from_length</parameter> parameter gives the number of
3050 bytes in this binary string. (A terminating zero byte is
3051 neither necessary nor counted.) The <parameter>to_length</parameter>
3052 parameter points to a variable that will hold the resultant
3053 escaped string length. This result string length includes the terminating
3054 zero byte of the result.
3055 </para>
3057 <para>
3058 <function>PQescapeByteaConn</> returns an escaped version of the
3059 <parameter>from</parameter> parameter binary string in memory
3060 allocated with <function>malloc()</>. This memory must be freed using
3061 <function>PQfreemem()</> when the result is no longer needed. The
3062 return string has all special characters replaced so that they can
3063 be properly processed by the <productname>PostgreSQL</productname>
3064 string literal parser, and the <type>bytea</type> input function. A
3065 terminating zero byte is also added. The single quotes that must
3066 surround <productname>PostgreSQL</productname> string literals are
3067 not part of the result string.
3068 </para>
3070 <para>
3071 On error, a NULL pointer is returned, and a suitable error message
3072 is stored in the <parameter>conn</> object. Currently, the only
3073 possible error is insufficient memory for the result string.
3074 </para>
3075 </listitem>
3076 </varlistentry>
3078 <varlistentry>
3079 <term>
3080 <function>PQescapeBytea</function>
3081 <indexterm>
3082 <primary>PQescapeBytea</primary>
3083 </indexterm>
3084 </term>
3086 <listitem>
3087 <para>
3088 <function>PQescapeBytea</> is an older, deprecated version of
3089 <function>PQescapeByteaConn</>.
3090 <synopsis>
3091 unsigned char *PQescapeBytea(const unsigned char *from,
3092 size_t from_length,
3093 size_t *to_length);
3094 </synopsis>
3095 </para>
3097 <para>
3098 The only difference from <function>PQescapeByteaConn</> is that
3099 <function>PQescapeBytea</> does not take a <structname>PGconn</>
3100 parameter. Because of this, it cannot adjust its behavior
3101 depending on the connection properties (in particular, whether
3102 standard-conforming strings are enabled) and therefore
3103 <emphasis>it might give the wrong results</>. Also, it has no
3104 way to return an error message on failure.
3105 </para>
3107 <para>
3108 <function>PQescapeBytea</> can be used safely in single-threaded
3109 client programs that work with only one <productname>PostgreSQL</>
3110 connection at a time (in this case it can find out what it needs
3111 to know <quote>behind the scenes</>). In other contexts it is
3112 a security hazard and should be avoided in favor of
3113 <function>PQescapeByteaConn</>.
3114 </para>
3115 </listitem>
3116 </varlistentry>
3118 <varlistentry>
3119 <term>
3120 <function>PQunescapeBytea</function>
3121 <indexterm>
3122 <primary>PQunescapeBytea</primary>
3123 </indexterm>
3124 </term>
3126 <listitem>
3127 <para>
3128 Converts a string representation of binary data into binary data
3129 &mdash; the reverse of <function>PQescapeBytea</function>. This
3130 is needed when retrieving <type>bytea</type> data in text format,
3131 but not when retrieving it in binary format.
3133 <synopsis>
3134 unsigned char *PQunescapeBytea(const unsigned char *from, size_t *to_length);
3135 </synopsis>
3136 </para>
3138 <para>
3139 The <parameter>from</parameter> parameter points to a string
3140 such as might be returned by <function>PQgetvalue</function> when applied
3141 to a <type>bytea</type> column. <function>PQunescapeBytea</function>
3142 converts this string representation into its binary representation.
3143 It returns a pointer to a buffer allocated with
3144 <function>malloc()</function>, or null on error, and puts the size of
3145 the buffer in <parameter>to_length</parameter>. The result must be
3146 freed using <function>PQfreemem</> when it is no longer needed.
3147 </para>
3149 <para>
3150 This conversion is not exactly the inverse of
3151 <function>PQescapeBytea</function>, because the string is not expected
3152 to be <quote>escaped</> when received from <function>PQgetvalue</function>.
3153 In particular this means there is no need for string quoting considerations,
3154 and so no need for a <structname>PGconn</> parameter.
3155 </para>
3156 </listitem>
3157 </varlistentry>
3158 </variablelist>
3160 </sect2>
3162 </sect1>
3164 <sect1 id="libpq-async">
3165 <title>Asynchronous Command Processing</title>
3167 <indexterm zone="libpq-async">
3168 <primary>nonblocking connection</primary>
3169 </indexterm>
3171 <para>
3172 The <function>PQexec</function> function is adequate for submitting
3173 commands in normal, synchronous applications. It has a couple of
3174 deficiencies, however, that can be of importance to some users:
3176 <itemizedlist>
3177 <listitem>
3178 <para>
3179 <function>PQexec</function> waits for the command to be completed.
3180 The application might have other work to do (such as maintaining a
3181 user interface), in which case it won't want to block waiting for
3182 the response.
3183 </para>
3184 </listitem>
3186 <listitem>
3187 <para>
3188 Since the execution of the client application is suspended while it
3189 waits for the result, it is hard for the application to decide that
3190 it would like to try to cancel the ongoing command. (It can be done
3191 from a signal handler, but not otherwise.)
3192 </para>
3193 </listitem>
3195 <listitem>
3196 <para>
3197 <function>PQexec</function> can return only one
3198 <structname>PGresult</structname> structure. If the submitted command
3199 string contains multiple <acronym>SQL</acronym> commands, all but
3200 the last <structname>PGresult</structname> are discarded by
3201 <function>PQexec</function>.
3202 </para>
3203 </listitem>
3204 </itemizedlist>
3205 </para>
3207 <para>
3208 Applications that do not like these limitations can instead use the
3209 underlying functions that <function>PQexec</function> is built from:
3210 <function>PQsendQuery</function> and <function>PQgetResult</function>.
3211 There are also
3212 <function>PQsendQueryParams</function>,
3213 <function>PQsendPrepare</function>,
3214 <function>PQsendQueryPrepared</function>,
3215 <function>PQsendDescribePrepared</function>, and
3216 <function>PQsendDescribePortal</function>,
3217 which can be used with <function>PQgetResult</function> to duplicate
3218 the functionality of
3219 <function>PQexecParams</function>,
3220 <function>PQprepare</function>,
3221 <function>PQexecPrepared</function>,
3222 <function>PQdescribePrepared</function>, and
3223 <function>PQdescribePortal</function>
3224 respectively.
3226 <variablelist>
3227 <varlistentry>
3228 <term>
3229 <function>PQsendQuery</function>
3230 <indexterm>
3231 <primary>PQsendQuery</primary>
3232 </indexterm>
3233 </term>
3235 <listitem>
3236 <para>
3237 Submits a command to the server without waiting for the result(s).
3238 1 is returned if the command was successfully dispatched and 0 if
3239 not (in which case, use <function>PQerrorMessage</> to get more
3240 information about the failure).
3241 <synopsis>
3242 int PQsendQuery(PGconn *conn, const char *command);
3243 </synopsis>
3245 After successfully calling <function>PQsendQuery</function>, call
3246 <function>PQgetResult</function> one or more times to obtain the
3247 results. <function>PQsendQuery</function> cannot be called again
3248 (on the same connection) until <function>PQgetResult</function>
3249 has returned a null pointer, indicating that the command is done.
3250 </para>
3251 </listitem>
3252 </varlistentry>
3254 <varlistentry>
3255 <term>
3256 <function>PQsendQueryParams</function>
3257 <indexterm>
3258 <primary>PQsendQueryParams</primary>
3259 </indexterm>
3260 </term>
3262 <listitem>
3263 <para>
3264 Submits a command and separate parameters to the server without
3265 waiting for the result(s).
3266 <synopsis>
3267 int PQsendQueryParams(PGconn *conn,
3268 const char *command,
3269 int nParams,
3270 const Oid *paramTypes,
3271 const char * const *paramValues,
3272 const int *paramLengths,
3273 const int *paramFormats,
3274 int resultFormat);
3275 </synopsis>
3277 This is equivalent to <function>PQsendQuery</function> except that
3278 query parameters can be specified separately from the query string.
3279 The function's parameters are handled identically to
3280 <function>PQexecParams</function>. Like
3281 <function>PQexecParams</function>, it will not work on 2.0-protocol
3282 connections, and it allows only one command in the query string.
3283 </para>
3284 </listitem>
3285 </varlistentry>
3287 <varlistentry>
3288 <term>
3289 <function>PQsendPrepare</>
3290 <indexterm>
3291 <primary>PQsendPrepare</primary>
3292 </indexterm>
3293 </term>
3295 <listitem>
3296 <para>
3297 Sends a request to create a prepared statement with the given
3298 parameters, without waiting for completion.
3299 <synopsis>
3300 int PQsendPrepare(PGconn *conn,
3301 const char *stmtName,
3302 const char *query,
3303 int nParams,
3304 const Oid *paramTypes);
3305 </synopsis>
3307 This is an asynchronous version of <function>PQprepare</>: it
3308 returns 1 if it was able to dispatch the request, and 0 if not.
3309 After a successful call, call <function>PQgetResult</function> to
3310 determine whether the server successfully created the prepared
3311 statement. The function's parameters are handled identically to
3312 <function>PQprepare</function>. Like
3313 <function>PQprepare</function>, it will not work on 2.0-protocol
3314 connections.
3315 </para>
3316 </listitem>
3317 </varlistentry>
3319 <varlistentry>
3320 <term>
3321 <function>PQsendQueryPrepared</function>
3322 <indexterm>
3323 <primary>PQsendQueryPrepared</primary>
3324 </indexterm>
3325 </term>
3327 <listitem>
3328 <para>
3329 Sends a request to execute a prepared statement with given
3330 parameters, without waiting for the result(s).
3331 <synopsis>
3332 int PQsendQueryPrepared(PGconn *conn,
3333 const char *stmtName,
3334 int nParams,
3335 const char * const *paramValues,
3336 const int *paramLengths,
3337 const int *paramFormats,
3338 int resultFormat);
3339 </synopsis>
3341 This is similar to <function>PQsendQueryParams</function>, but
3342 the command to be executed is specified by naming a
3343 previously-prepared statement, instead of giving a query string.
3344 The function's parameters are handled identically to
3345 <function>PQexecPrepared</function>. Like
3346 <function>PQexecPrepared</function>, it will not work on
3347 2.0-protocol connections.
3348 </para>
3349 </listitem>
3350 </varlistentry>
3352 <varlistentry>
3353 <term>
3354 <function>PQsendDescribePrepared</>
3355 <indexterm>
3356 <primary>PQsendDescribePrepared</primary>
3357 </indexterm>
3358 </term>
3360 <listitem>
3361 <para>
3362 Submits a request to obtain information about the specified
3363 prepared statement, without waiting for completion.
3364 <synopsis>
3365 int PQsendDescribePrepared(PGconn *conn, const char *stmtName);
3366 </synopsis>
3368 This is an asynchronous version of <function>PQdescribePrepared</>:
3369 it returns 1 if it was able to dispatch the request, and 0 if not.
3370 After a successful call, call <function>PQgetResult</function> to
3371 obtain the results. The function's parameters are handled
3372 identically to <function>PQdescribePrepared</function>. Like
3373 <function>PQdescribePrepared</function>, it will not work on
3374 2.0-protocol connections.
3375 </para>
3376 </listitem>
3377 </varlistentry>
3379 <varlistentry>
3380 <term>
3381 <function>PQsendDescribePortal</>
3382 <indexterm>
3383 <primary>PQsendDescribePortal</primary>
3384 </indexterm>
3385 </term>
3387 <listitem>
3388 <para>
3389 Submits a request to obtain information about the specified
3390 portal, without waiting for completion.
3391 <synopsis>
3392 int PQsendDescribePortal(PGconn *conn, const char *portalName);
3393 </synopsis>
3395 This is an asynchronous version of <function>PQdescribePortal</>:
3396 it returns 1 if it was able to dispatch the request, and 0 if not.
3397 After a successful call, call <function>PQgetResult</function> to
3398 obtain the results. The function's parameters are handled
3399 identically to <function>PQdescribePortal</function>. Like
3400 <function>PQdescribePortal</function>, it will not work on
3401 2.0-protocol connections.
3402 </para>
3403 </listitem>
3404 </varlistentry>
3406 <varlistentry>
3407 <term>
3408 <function>PQgetResult</function>
3409 <indexterm>
3410 <primary>PQgetResult</primary>
3411 </indexterm>
3412 </term>
3414 <listitem>
3415 <para>
3416 Waits for the next result from a prior
3417 <function>PQsendQuery</function>,
3418 <function>PQsendQueryParams</function>,
3419 <function>PQsendPrepare</function>, or
3420 <function>PQsendQueryPrepared</function> call, and returns it.
3421 A null pointer is returned when the command is complete and there
3422 will be no more results.
3423 <synopsis>
3424 PGresult *PQgetResult(PGconn *conn);
3425 </synopsis>
3426 </para>
3428 <para>
3429 <function>PQgetResult</function> must be called repeatedly until
3430 it returns a null pointer, indicating that the command is done.
3431 (If called when no command is active,
3432 <function>PQgetResult</function> will just return a null pointer
3433 at once.) Each non-null result from
3434 <function>PQgetResult</function> should be processed using the
3435 same <structname>PGresult</> accessor functions previously
3436 described. Don't forget to free each result object with
3437 <function>PQclear</function> when done with it. Note that
3438 <function>PQgetResult</function> will block only if a command is
3439 active and the necessary response data has not yet been read by
3440 <function>PQconsumeInput</function>.
3441 </para>
3442 </listitem>
3443 </varlistentry>
3444 </variablelist>
3445 </para>
3447 <para>
3448 Using <function>PQsendQuery</function> and
3449 <function>PQgetResult</function> solves one of
3450 <function>PQexec</function>'s problems: If a command string contains
3451 multiple <acronym>SQL</acronym> commands, the results of those commands
3452 can be obtained individually. (This allows a simple form of overlapped
3453 processing, by the way: the client can be handling the results of one
3454 command while the server is still working on later queries in the same
3455 command string.) However, calling <function>PQgetResult</function>
3456 will still cause the client to block until the server completes the
3457 next <acronym>SQL</acronym> command. This can be avoided by proper
3458 use of two more functions:
3460 <variablelist>
3461 <varlistentry>
3462 <term>
3463 <function>PQconsumeInput</function>
3464 <indexterm>
3465 <primary>PQconsumeInput</primary>
3466 </indexterm>
3467 </term>
3469 <listitem>
3470 <para>
3471 If input is available from the server, consume it.
3472 <synopsis>
3473 int PQconsumeInput(PGconn *conn);
3474 </synopsis>
3475 </para>
3477 <para>
3478 <function>PQconsumeInput</function> normally returns 1 indicating
3479 <quote>no error</quote>, but returns 0 if there was some kind of
3480 trouble (in which case <function>PQerrorMessage</function> can be
3481 consulted). Note that the result does not say whether any input
3482 data was actually collected. After calling
3483 <function>PQconsumeInput</function>, the application can check
3484 <function>PQisBusy</function> and/or
3485 <function>PQnotifies</function> to see if their state has changed.
3486 </para>
3488 <para>
3489 <function>PQconsumeInput</function> can be called even if the
3490 application is not prepared to deal with a result or notification
3491 just yet. The function will read available data and save it in
3492 a buffer, thereby causing a <function>select()</function>
3493 read-ready indication to go away. The application can thus use
3494 <function>PQconsumeInput</function> to clear the
3495 <function>select()</function> condition immediately, and then
3496 examine the results at leisure.
3497 </para>
3498 </listitem>
3499 </varlistentry>
3501 <varlistentry>
3502 <term>
3503 <function>PQisBusy</function>
3504 <indexterm>
3505 <primary>PQisBusy</primary>
3506 </indexterm>
3507 </term>
3509 <listitem>
3510 <para>
3511 Returns 1 if a command is busy, that is,
3512 <function>PQgetResult</function> would block waiting for input.
3513 A 0 return indicates that <function>PQgetResult</function> can be
3514 called with assurance of not blocking.
3515 <synopsis>
3516 int PQisBusy(PGconn *conn);
3517 </synopsis>
3518 </para>
3520 <para>
3521 <function>PQisBusy</function> will not itself attempt to read data
3522 from the server; therefore <function>PQconsumeInput</function>
3523 must be invoked first, or the busy state will never end.
3524 </para>
3525 </listitem>
3526 </varlistentry>
3527 </variablelist>
3528 </para>
3530 <para>
3531 A typical application using these functions will have a main loop that
3532 uses <function>select()</function> or <function>poll()</> to wait for
3533 all the conditions that it must respond to. One of the conditions
3534 will be input available from the server, which in terms of
3535 <function>select()</function> means readable data on the file
3536 descriptor identified by <function>PQsocket</function>. When the main
3537 loop detects input ready, it should call
3538 <function>PQconsumeInput</function> to read the input. It can then
3539 call <function>PQisBusy</function>, followed by
3540 <function>PQgetResult</function> if <function>PQisBusy</function>
3541 returns false (0). It can also call <function>PQnotifies</function>
3542 to detect <command>NOTIFY</> messages (see <xref
3543 linkend="libpq-notify">).
3544 </para>
3546 <para>
3547 A client that uses
3548 <function>PQsendQuery</function>/<function>PQgetResult</function>
3549 can also attempt to cancel a command that is still being processed
3550 by the server; see <xref linkend="libpq-cancel">. But regardless of
3551 the return value of <function>PQcancel</function>, the application
3552 must continue with the normal result-reading sequence using
3553 <function>PQgetResult</function>. A successful cancellation will
3554 simply cause the command to terminate sooner than it would have
3555 otherwise.
3556 </para>
3558 <para>
3559 By using the functions described above, it is possible to avoid
3560 blocking while waiting for input from the database server. However,
3561 it is still possible that the application will block waiting to send
3562 output to the server. This is relatively uncommon but can happen if
3563 very long SQL commands or data values are sent. (It is much more
3564 probable if the application sends data via <command>COPY IN</command>,
3565 however.) To prevent this possibility and achieve completely
3566 nonblocking database operation, the following additional functions
3567 can be used.
3569 <variablelist>
3570 <varlistentry>
3571 <term>
3572 <function>PQsetnonblocking</function>
3573 <indexterm>
3574 <primary>PQsetnonblocking</primary>
3575 </indexterm>
3576 </term>
3578 <listitem>
3579 <para>
3580 Sets the nonblocking status of the connection.
3581 <synopsis>
3582 int PQsetnonblocking(PGconn *conn, int arg);
3583 </synopsis>
3584 </para>
3586 <para>
3587 Sets the state of the connection to nonblocking if
3588 <parameter>arg</parameter> is 1, or blocking if
3589 <parameter>arg</parameter> is 0. Returns 0 if OK, -1 if error.
3590 </para>
3592 <para>
3593 In the nonblocking state, calls to
3594 <function>PQsendQuery</function>, <function>PQputline</function>,
3595 <function>PQputnbytes</function>, and
3596 <function>PQendcopy</function> will not block but instead return
3597 an error if they need to be called again.
3598 </para>
3600 <para>
3601 Note that <function>PQexec</function> does not honor nonblocking
3602 mode; if it is called, it will act in blocking fashion anyway.
3603 </para>
3604 </listitem>
3605 </varlistentry>
3607 <varlistentry>
3608 <term>
3609 <function>PQisnonblocking</function>
3610 <indexterm>
3611 <primary>PQisnonblocking</primary>
3612 </indexterm>
3613 </term>
3615 <listitem>
3616 <para>
3617 Returns the blocking status of the database connection.
3618 <synopsis>
3619 int PQisnonblocking(const PGconn *conn);
3620 </synopsis>
3621 </para>
3623 <para>
3624 Returns 1 if the connection is set to nonblocking mode and 0 if
3625 blocking.
3626 </para>
3627 </listitem>
3628 </varlistentry>
3630 <varlistentry>
3631 <term>
3632 <function>PQflush</function>
3633 <indexterm>
3634 <primary>PQflush</primary>
3635 </indexterm>
3636 </term>
3638 <listitem>
3639 <para>
3640 Attempts to flush any queued output data to the server. Returns
3641 0 if successful (or if the send queue is empty), -1 if it failed
3642 for some reason, or 1 if it was unable to send all the data in
3643 the send queue yet (this case can only occur if the connection
3644 is nonblocking).
3645 <synopsis>
3646 int PQflush(PGconn *conn);
3647 </synopsis>
3648 </para>
3649 </listitem>
3650 </varlistentry>
3651 </variablelist>
3652 </para>
3654 <para>
3655 After sending any command or data on a nonblocking connection, call
3656 <function>PQflush</function>. If it returns 1, wait for the socket
3657 to be write-ready and call it again; repeat until it returns 0. Once
3658 <function>PQflush</function> returns 0, wait for the socket to be
3659 read-ready and then read the response as described above.
3660 </para>
3662 </sect1>
3664 <sect1 id="libpq-cancel">
3665 <title>Cancelling Queries in Progress</title>
3667 <indexterm zone="libpq-cancel">
3668 <primary>canceling</primary>
3669 <secondary>SQL command</secondary>
3670 </indexterm>
3672 <para>
3673 A client application can request cancellation of a command that is
3674 still being processed by the server, using the functions described in
3675 this section.
3677 <variablelist>
3678 <varlistentry>
3679 <term>
3680 <function>PQgetCancel</function>
3681 <indexterm>
3682 <primary>PQgetCancel</primary>
3683 </indexterm>
3684 </term>
3686 <listitem>
3687 <para>
3688 Creates a data structure containing the information needed to cancel
3689 a command issued through a particular database connection.
3690 <synopsis>
3691 PGcancel *PQgetCancel(PGconn *conn);
3692 </synopsis>
3693 </para>
3695 <para>
3696 <function>PQgetCancel</function> creates a
3697 <structname>PGcancel</><indexterm><primary>PGcancel</></> object
3698 given a <structname>PGconn</> connection object. It will return
3699 NULL if the given <parameter>conn</> is NULL or an invalid
3700 connection. The <structname>PGcancel</> object is an opaque
3701 structure that is not meant to be accessed directly by the
3702 application; it can only be passed to <function>PQcancel</function>
3703 or <function>PQfreeCancel</function>.
3704 </para>
3705 </listitem>
3706 </varlistentry>
3708 <varlistentry>
3709 <term>
3710 <function>PQfreeCancel</function>
3711 <indexterm>
3712 <primary>PQfreeCancel</primary>
3713 </indexterm>
3714 </term>
3716 <listitem>
3717 <para>
3718 Frees a data structure created by <function>PQgetCancel</function>.
3719 <synopsis>
3720 void PQfreeCancel(PGcancel *cancel);
3721 </synopsis>
3722 </para>
3724 <para>
3725 <function>PQfreeCancel</function> frees a data object previously created
3726 by <function>PQgetCancel</function>.
3727 </para>
3728 </listitem>
3729 </varlistentry>
3731 <varlistentry>
3732 <term>
3733 <function>PQcancel</function>
3734 <indexterm>
3735 <primary>PQcancel</primary>
3736 </indexterm>
3737 </term>
3739 <listitem>
3740 <para>
3741 Requests that the server abandon processing of the current command.
3742 <synopsis>
3743 int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize);
3744 </synopsis>
3745 </para>
3747 <para>
3748 The return value is 1 if the cancel request was successfully
3749 dispatched and 0 if not. If not, <parameter>errbuf</> is filled
3750 with an error message explaining why not. <parameter>errbuf</>
3751 must be a char array of size <parameter>errbufsize</> (the
3752 recommended size is 256 bytes).
3753 </para>
3755 <para>
3756 Successful dispatch is no guarantee that the request will have
3757 any effect, however. If the cancellation is effective, the current
3758 command will terminate early and return an error result. If the
3759 cancellation fails (say, because the server was already done
3760 processing the command), then there will be no visible result at
3761 all.
3762 </para>
3764 <para>
3765 <function>PQcancel</function> can safely be invoked from a signal
3766 handler, if the <parameter>errbuf</> is a local variable in the
3767 signal handler. The <structname>PGcancel</> object is read-only
3768 as far as <function>PQcancel</function> is concerned, so it can
3769 also be invoked from a thread that is separate from the one
3770 manipulating the <structname>PGconn</> object.
3771 </para>
3772 </listitem>
3773 </varlistentry>
3774 </variablelist>
3776 <variablelist>
3777 <varlistentry>
3778 <term>
3779 <function>PQrequestCancel</function>
3780 <indexterm>
3781 <primary>PQrequestCancel</primary>
3782 </indexterm>
3783 </term>
3785 <listitem>
3786 <para>
3787 Requests that the server abandon processing of the current
3788 command.
3789 <synopsis>
3790 int PQrequestCancel(PGconn *conn);
3791 </synopsis>
3792 </para>
3794 <para>
3795 <function>PQrequestCancel</function> is a deprecated variant of
3796 <function>PQcancel</function>. It operates directly on the
3797 <structname>PGconn</> object, and in case of failure stores the
3798 error message in the <structname>PGconn</> object (whence it can
3799 be retrieved by <function>PQerrorMessage</function>). Although
3800 the functionality is the same, this approach creates hazards for
3801 multiple-thread programs and signal handlers, since it is possible
3802 that overwriting the <structname>PGconn</>'s error message will
3803 mess up the operation currently in progress on the connection.
3804 </para>
3805 </listitem>
3806 </varlistentry>
3807 </variablelist>
3808 </para>
3810 </sect1>
3812 <sect1 id="libpq-fastpath">
3813 <title>The Fast-Path Interface</title>
3815 <indexterm zone="libpq-fastpath">
3816 <primary>fast path</primary>
3817 </indexterm>
3819 <para>
3820 <productname>PostgreSQL</productname> provides a fast-path interface
3821 to send simple function calls to the server.
3822 </para>
3824 <tip>
3825 <para>
3826 This interface is somewhat obsolete, as one can achieve similar
3827 performance and greater functionality by setting up a prepared
3828 statement to define the function call. Then, executing the statement
3829 with binary transmission of parameters and results substitutes for a
3830 fast-path function call.
3831 </para>
3832 </tip>
3834 <para>
3835 The function <function>PQfn</function><indexterm><primary>PQfn</></>
3836 requests execution of a server function via the fast-path interface:
3837 <synopsis>
3838 PGresult *PQfn(PGconn *conn,
3839 int fnid,
3840 int *result_buf,
3841 int *result_len,
3842 int result_is_int,
3843 const PQArgBlock *args,
3844 int nargs);
3846 typedef struct {
3847 int len;
3848 int isint;
3849 union {
3850 int *ptr;
3851 int integer;
3852 } u;
3853 } PQArgBlock;
3854 </synopsis>
3855 </para>
3857 <para>
3858 The <parameter>fnid</> argument is the OID of the function to be
3859 executed. <parameter>args</> and <parameter>nargs</> define the
3860 parameters to be passed to the function; they must match the declared
3861 function argument list. When the <parameter>isint</> field of a
3862 parameter structure is true, the <parameter>u.integer</> value is sent
3863 to the server as an integer of the indicated length (this must be 1,
3864 2, or 4 bytes); proper byte-swapping occurs. When <parameter>isint</>
3865 is false, the indicated number of bytes at <parameter>*u.ptr</> are
3866 sent with no processing; the data must be in the format expected by
3867 the server for binary transmission of the function's argument data
3868 type. <parameter>result_buf</parameter> is the buffer in which to
3869 place the return value. The caller must have allocated sufficient
3870 space to store the return value. (There is no check!) The actual result
3871 length will be returned in the integer pointed to by
3872 <parameter>result_len</parameter>. If a 1, 2, or 4-byte integer result
3873 is expected, set <parameter>result_is_int</parameter> to 1, otherwise
3874 set it to 0. Setting <parameter>result_is_int</parameter> to 1 causes
3875 <application>libpq</> to byte-swap the value if necessary, so that it
3876 is delivered as a proper <type>int</type> value for the client machine.
3877 When <parameter>result_is_int</> is 0, the binary-format byte string
3878 sent by the server is returned unmodified.
3879 </para>
3881 <para>
3882 <function>PQfn</function> always returns a valid
3883 <structname>PGresult</structname> pointer. The result status should be
3884 checked before the result is used. The caller is responsible for
3885 freeing the <structname>PGresult</structname> with
3886 <function>PQclear</function> when it is no longer needed.
3887 </para>
3889 <para>
3890 Note that it is not possible to handle null arguments, null results,
3891 nor set-valued results when using this interface.
3892 </para>
3894 </sect1>
3896 <sect1 id="libpq-notify">
3897 <title>Asynchronous Notification</title>
3899 <indexterm zone="libpq-notify">
3900 <primary>NOTIFY</primary>
3901 <secondary>in libpq</secondary>
3902 </indexterm>
3904 <para>
3905 <productname>PostgreSQL</productname> offers asynchronous notification
3906 via the <command>LISTEN</command> and <command>NOTIFY</command>
3907 commands. A client session registers its interest in a particular
3908 notification condition with the <command>LISTEN</command> command (and
3909 can stop listening with the <command>UNLISTEN</command> command). All
3910 sessions listening on a particular condition will be notified
3911 asynchronously when a <command>NOTIFY</command> command with that
3912 condition name is executed by any session. No additional information
3913 is passed from the notifier to the listener. Thus, typically, any
3914 actual data that needs to be communicated is transferred through a
3915 database table. Commonly, the condition name is the same as the
3916 associated table, but it is not necessary for there to be any associated
3917 table.
3918 </para>
3920 <para>
3921 <application>libpq</application> applications submit
3922 <command>LISTEN</command> and <command>UNLISTEN</command> commands as
3923 ordinary SQL commands. The arrival of <command>NOTIFY</command>
3924 messages can subsequently be detected by calling
3925 <function>PQnotifies</function>.<indexterm><primary>PQnotifies</></>
3926 </para>
3928 <para>
3929 The function <function>PQnotifies</function>
3930 returns the next notification from a list of unhandled
3931 notification messages received from the server. It returns a null pointer if
3932 there are no pending notifications. Once a notification is
3933 returned from <function>PQnotifies</>, it is considered handled and will be
3934 removed from the list of notifications.
3935 <synopsis>
3936 PGnotify *PQnotifies(PGconn *conn);
3938 typedef struct pgNotify {
3939 char *relname; /* notification condition name */
3940 int be_pid; /* process ID of notifying server process */
3941 char *extra; /* notification parameter */
3942 } PGnotify;
3943 </synopsis>
3944 After processing a <structname>PGnotify</structname> object returned
3945 by <function>PQnotifies</function>, be sure to free it with
3946 <function>PQfreemem</function>. It is sufficient to free the
3947 <structname>PGnotify</structname> pointer; the
3948 <structfield>relname</structfield> and <structfield>extra</structfield>
3949 fields do not represent separate allocations. (At present, the
3950 <structfield>extra</structfield> field is unused and will always point
3951 to an empty string.)
3952 </para>
3954 <para>
3955 <xref linkend="libpq-example-2"> gives a sample program that illustrates
3956 the use of asynchronous notification.
3957 </para>
3959 <para>
3960 <function>PQnotifies</function> does not actually read data from the
3961 server; it just returns messages previously absorbed by another
3962 <application>libpq</application> function. In prior releases of
3963 <application>libpq</application>, the only way to ensure timely receipt
3964 of <command>NOTIFY</> messages was to constantly submit commands, even
3965 empty ones, and then check <function>PQnotifies</function> after each
3966 <function>PQexec</function>. While this still works, it is deprecated
3967 as a waste of processing power.
3968 </para>
3970 <para>
3971 A better way to check for <command>NOTIFY</> messages when you have no
3972 useful commands to execute is to call
3973 <function>PQconsumeInput</function>, then check
3974 <function>PQnotifies</function>. You can use
3975 <function>select()</function> to wait for data to arrive from the
3976 server, thereby using no <acronym>CPU</acronym> power unless there is
3977 something to do. (See <function>PQsocket</function> to obtain the file
3978 descriptor number to use with <function>select()</function>.) Note that
3979 this will work OK whether you submit commands with
3980 <function>PQsendQuery</function>/<function>PQgetResult</function> or
3981 simply use <function>PQexec</function>. You should, however, remember
3982 to check <function>PQnotifies</function> after each
3983 <function>PQgetResult</function> or <function>PQexec</function>, to
3984 see if any notifications came in during the processing of the command.
3985 </para>
3987 </sect1>
3989 <sect1 id="libpq-copy">
3990 <title>Functions Associated with the <command>COPY</command> Command</title>
3992 <indexterm zone="libpq-copy">
3993 <primary>COPY</primary>
3994 <secondary>with libpq</secondary>
3995 </indexterm>
3997 <para>
3998 The <command>COPY</command> command in
3999 <productname>PostgreSQL</productname> has options to read from or write
4000 to the network connection used by <application>libpq</application>.
4001 The functions described in this section allow applications to take
4002 advantage of this capability by supplying or consuming copied data.
4003 </para>
4005 <para>
4006 The overall process is that the application first issues the SQL
4007 <command>COPY</command> command via <function>PQexec</function> or one
4008 of the equivalent functions. The response to this (if there is no
4009 error in the command) will be a <structname>PGresult</> object bearing
4010 a status code of <literal>PGRES_COPY_OUT</literal> or
4011 <literal>PGRES_COPY_IN</literal> (depending on the specified copy
4012 direction). The application should then use the functions of this
4013 section to receive or transmit data rows. When the data transfer is
4014 complete, another <structname>PGresult</> object is returned to indicate
4015 success or failure of the transfer. Its status will be
4016 <literal>PGRES_COMMAND_OK</literal> for success or
4017 <literal>PGRES_FATAL_ERROR</literal> if some problem was encountered.
4018 At this point further SQL commands can be issued via
4019 <function>PQexec</function>. (It is not possible to execute other SQL
4020 commands using the same connection while the <command>COPY</command>
4021 operation is in progress.)
4022 </para>
4024 <para>
4025 If a <command>COPY</command> command is issued via
4026 <function>PQexec</function> in a string that could contain additional
4027 commands, the application must continue fetching results via
4028 <function>PQgetResult</> after completing the <command>COPY</command>
4029 sequence. Only when <function>PQgetResult</> returns
4030 <symbol>NULL</symbol> is it certain that the <function>PQexec</function>
4031 command string is done and it is safe to issue more commands.
4032 </para>
4034 <para>
4035 The functions of this section should be executed only after obtaining
4036 a result status of <literal>PGRES_COPY_OUT</literal> or
4037 <literal>PGRES_COPY_IN</literal> from <function>PQexec</function> or
4038 <function>PQgetResult</function>.
4039 </para>
4041 <para>
4042 A <structname>PGresult</> object bearing one of these status values
4043 carries some additional data about the <command>COPY</command> operation
4044 that is starting. This additional data is available using functions
4045 that are also used in connection with query results:
4047 <variablelist>
4048 <varlistentry>
4049 <term>
4050 <function>PQnfields</function>
4051 <indexterm>
4052 <primary>PQnfields</primary>
4053 <secondary>with COPY</secondary>
4054 </indexterm>
4055 </term>
4057 <listitem>
4058 <para>
4059 Returns the number of columns (fields) to be copied.
4060 </para>
4061 </listitem>
4062 </varlistentry>
4064 <varlistentry>
4065 <term>
4066 <function>PQbinaryTuples</function>
4067 <indexterm>
4068 <primary>PQbinaryTuples</primary>
4069 <secondary>with COPY</secondary>
4070 </indexterm>
4071 </term>
4073 <listitem>
4074 <para>
4075 0 indicates the overall copy format is textual (rows separated by
4076 newlines, columns separated by separator characters, etc). 1
4077 indicates the overall copy format is binary. See <xref
4078 linkend="sql-copy" endterm="sql-copy-title"> for more information.
4079 </para>
4080 </listitem>
4081 </varlistentry>
4083 <varlistentry>
4084 <term>
4085 <function>PQfformat</function>
4086 <indexterm>
4087 <primary>PQfformat</primary>
4088 <secondary>with COPY</secondary>
4089 </indexterm>
4090 </term>
4092 <listitem>
4093 <para>
4094 Returns the format code (0 for text, 1 for binary) associated with
4095 each column of the copy operation. The per-column format codes
4096 will always be zero when the overall copy format is textual, but
4097 the binary format can support both text and binary columns.
4098 (However, as of the current implementation of <command>COPY</>,
4099 only binary columns appear in a binary copy; so the per-column
4100 formats always match the overall format at present.)
4101 </para>
4102 </listitem>
4103 </varlistentry>
4104 </variablelist>
4105 </para>
4107 <note>
4108 <para>
4109 These additional data values are only available when using protocol
4110 3.0. When using protocol 2.0, all these functions will return 0.
4111 </para>
4112 </note>
4114 <sect2 id="libpq-copy-send">
4115 <title>Functions for Sending <command>COPY</command> Data</title>
4117 <para>
4118 These functions are used to send data during <literal>COPY FROM
4119 STDIN</>. They will fail if called when the connection is not in
4120 <literal>COPY_IN</> state.
4121 </para>
4123 <variablelist>
4124 <varlistentry>
4125 <term>
4126 <function>PQputCopyData</function>
4127 <indexterm>
4128 <primary>PQputCopyData</primary>
4129 </indexterm>
4130 </term>
4132 <listitem>
4133 <para>
4134 Sends data to the server during <literal>COPY_IN</> state.
4135 <synopsis>
4136 int PQputCopyData(PGconn *conn,
4137 const char *buffer,
4138 int nbytes);
4139 </synopsis>
4140 </para>
4142 <para>
4143 Transmits the <command>COPY</command> data in the specified
4144 <parameter>buffer</>, of length <parameter>nbytes</>, to the server.
4145 The result is 1 if the data was sent, zero if it was not sent
4146 because the attempt would block (this case is only possible if the
4147 connection is in nonblocking mode), or -1 if an error occurred.
4148 (Use <function>PQerrorMessage</function> to retrieve details if
4149 the return value is -1. If the value is zero, wait for write-ready
4150 and try again.)
4151 </para>
4153 <para>
4154 The application can divide the <command>COPY</command> data stream
4155 into buffer loads of any convenient size. Buffer-load boundaries
4156 have no semantic significance when sending. The contents of the
4157 data stream must match the data format expected by the
4158 <command>COPY</> command; see <xref linkend="sql-copy"
4159 endterm="sql-copy-title"> for details.
4160 </para>
4161 </listitem>
4162 </varlistentry>
4164 <varlistentry>
4165 <term>
4166 <function>PQputCopyEnd</function>
4167 <indexterm>
4168 <primary>PQputCopyEnd</primary>
4169 </indexterm>
4170 </term>
4172 <listitem>
4173 <para>
4174 Sends end-of-data indication to the server during <literal>COPY_IN</> state.
4175 <synopsis>
4176 int PQputCopyEnd(PGconn *conn,
4177 const char *errormsg);
4178 </synopsis>
4179 </para>
4181 <para>
4182 Ends the <literal>COPY_IN</> operation successfully if
4183 <parameter>errormsg</> is <symbol>NULL</symbol>. If
4184 <parameter>errormsg</> is not <symbol>NULL</symbol> then the
4185 <command>COPY</> is forced to fail, with the string pointed to by
4186 <parameter>errormsg</> used as the error message. (One should not
4187 assume that this exact error message will come back from the server,
4188 however, as the server might have already failed the
4189 <command>COPY</> for its own reasons. Also note that the option
4190 to force failure does not work when using pre-3.0-protocol
4191 connections.)
4192 </para>
4194 <para>
4195 The result is 1 if the termination data was sent, zero if it was
4196 not sent because the attempt would block (this case is only possible
4197 if the connection is in nonblocking mode), or -1 if an error
4198 occurred. (Use <function>PQerrorMessage</function> to retrieve
4199 details if the return value is -1. If the value is zero, wait for
4200 write-ready and try again.)
4201 </para>
4203 <para>
4204 After successfully calling <function>PQputCopyEnd</>, call
4205 <function>PQgetResult</> to obtain the final result status of the
4206 <command>COPY</> command. One can wait for this result to be
4207 available in the usual way. Then return to normal operation.
4208 </para>
4209 </listitem>
4210 </varlistentry>
4211 </variablelist>
4213 </sect2>
4215 <sect2 id="libpq-copy-receive">
4216 <title>Functions for Receiving <command>COPY</command> Data</title>
4218 <para>
4219 These functions are used to receive data during <literal>COPY TO
4220 STDOUT</>. They will fail if called when the connection is not in
4221 <literal>COPY_OUT</> state.
4222 </para>
4224 <variablelist>
4225 <varlistentry>
4226 <term>
4227 <function>PQgetCopyData</function>
4228 <indexterm>
4229 <primary>PQgetCopyData</primary>
4230 </indexterm>
4231 </term>
4233 <listitem>
4234 <para>
4235 Receives data from the server during <literal>COPY_OUT</> state.
4236 <synopsis>
4237 int PQgetCopyData(PGconn *conn,
4238 char **buffer,
4239 int async);
4240 </synopsis>
4241 </para>
4243 <para>
4244 Attempts to obtain another row of data from the server during a
4245 <command>COPY</command>. Data is always returned one data row at
4246 a time; if only a partial row is available, it is not returned.
4247 Successful return of a data row involves allocating a chunk of
4248 memory to hold the data. The <parameter>buffer</> parameter must
4249 be non-<symbol>NULL</symbol>. <parameter>*buffer</> is set to
4250 point to the allocated memory, or to <symbol>NULL</symbol> in cases
4251 where no buffer is returned. A non-<symbol>NULL</symbol> result
4252 buffer must be freed using <function>PQfreemem</> when no longer
4253 needed.
4254 </para>
4256 <para>
4257 When a row is successfully returned, the return value is the number
4258 of data bytes in the row (this will always be greater than zero).
4259 The returned string is always null-terminated, though this is
4260 probably only useful for textual <command>COPY</command>. A result
4261 of zero indicates that the <command>COPY</command> is still in
4262 progress, but no row is yet available (this is only possible when
4263 <parameter>async</> is true). A result of -1 indicates that the
4264 <command>COPY</command> is done. A result of -2 indicates that an
4265 error occurred (consult <function>PQerrorMessage</> for the reason).
4266 </para>
4268 <para>
4269 When <parameter>async</> is true (not zero),
4270 <function>PQgetCopyData</> will not block waiting for input; it
4271 will return zero if the <command>COPY</command> is still in progress
4272 but no complete row is available. (In this case wait for read-ready
4273 and then call <function>PQconsumeInput</> before calling
4274 <function>PQgetCopyData</> again.) When <parameter>async</> is
4275 false (zero), <function>PQgetCopyData</> will block until data is
4276 available or the operation completes.
4277 </para>
4279 <para>
4280 After <function>PQgetCopyData</> returns -1, call
4281 <function>PQgetResult</> to obtain the final result status of the
4282 <command>COPY</> command. One can wait for this result to be
4283 available in the usual way. Then return to normal operation.
4284 </para>
4285 </listitem>
4286 </varlistentry>
4287 </variablelist>
4289 </sect2>
4291 <sect2 id="libpq-copy-deprecated">
4292 <title>Obsolete Functions for <command>COPY</command></title>
4294 <para>
4295 These functions represent older methods of handling <command>COPY</>.
4296 Although they still work, they are deprecated due to poor error handling,
4297 inconvenient methods of detecting end-of-data, and lack of support for binary
4298 or nonblocking transfers.
4299 </para>
4301 <variablelist>
4302 <varlistentry>
4303 <term>
4304 <function>PQgetline</function>
4305 <indexterm>
4306 <primary>PQgetline</primary>
4307 </indexterm>
4308 </term>
4310 <listitem>
4311 <para>
4312 Reads a newline-terminated line of characters (transmitted
4313 by the server) into a buffer string of size <parameter>length</>.
4314 <synopsis>
4315 int PQgetline(PGconn *conn,
4316 char *buffer,
4317 int length);
4318 </synopsis>
4319 </para>
4321 <para>
4322 This function copies up to <parameter>length</>-1 characters into
4323 the buffer and converts the terminating newline into a zero byte.
4324 <function>PQgetline</function> returns <symbol>EOF</symbol> at the
4325 end of input, 0 if the entire line has been read, and 1 if the
4326 buffer is full but the terminating newline has not yet been read.
4327 </para>
4328 <para>
4329 Note that the application must check to see if a new line consists
4330 of the two characters <literal>\.</literal>, which indicates
4331 that the server has finished sending the results of the
4332 <command>COPY</command> command. If the application might receive
4333 lines that are more than <parameter>length</>-1 characters long,
4334 care is needed to be sure it recognizes the <literal>\.</literal>
4335 line correctly (and does not, for example, mistake the end of a
4336 long data line for a terminator line).
4337 </para>
4338 </listitem>
4339 </varlistentry>
4341 <varlistentry>
4342 <term>
4343 <function>PQgetlineAsync</function>
4344 <indexterm>
4345 <primary>PQgetlineAsync</primary>
4346 </indexterm>
4347 </term>
4349 <listitem>
4350 <para>
4351 Reads a row of <command>COPY</command> data (transmitted by the
4352 server) into a buffer without blocking.
4353 <synopsis>
4354 int PQgetlineAsync(PGconn *conn,
4355 char *buffer,
4356 int bufsize);
4357 </synopsis>
4358 </para>
4360 <para>
4361 This function is similar to <function>PQgetline</function>, but it can be used
4362 by applications
4363 that must read <command>COPY</command> data asynchronously, that is, without blocking.
4364 Having issued the <command>COPY</command> command and gotten a <literal>PGRES_COPY_OUT</literal>
4365 response, the
4366 application should call <function>PQconsumeInput</function> and
4367 <function>PQgetlineAsync</function> until the
4368 end-of-data signal is detected.
4369 </para>
4370 <para>
4371 Unlike <function>PQgetline</function>, this function takes
4372 responsibility for detecting end-of-data.
4373 </para>
4375 <para>
4376 On each call, <function>PQgetlineAsync</function> will return data if a
4377 complete data row is available in <application>libpq</>'s input buffer.
4378 Otherwise, no data is returned until the rest of the row arrives.
4379 The function returns -1 if the end-of-copy-data marker has been recognized,
4380 or 0 if no data is available, or a positive number giving the number of
4381 bytes of data returned. If -1 is returned, the caller must next call
4382 <function>PQendcopy</function>, and then return to normal processing.
4383 </para>
4385 <para>
4386 The data returned will not extend beyond a data-row boundary. If possible
4387 a whole row will be returned at one time. But if the buffer offered by
4388 the caller is too small to hold a row sent by the server, then a partial
4389 data row will be returned. With textual data this can be detected by testing
4390 whether the last returned byte is <literal>\n</literal> or not. (In a binary
4391 <command>COPY</>, actual parsing of the <command>COPY</> data format will be needed to make the
4392 equivalent determination.)
4393 The returned string is not null-terminated. (If you want to add a
4394 terminating null, be sure to pass a <parameter>bufsize</parameter> one smaller
4395 than the room actually available.)
4396 </para>
4397 </listitem>
4398 </varlistentry>
4400 <varlistentry>
4401 <term>
4402 <function>PQputline</function>
4403 <indexterm>
4404 <primary>PQputline</primary>
4405 </indexterm>
4406 </term>
4408 <listitem>
4409 <para>
4410 Sends a null-terminated string to the server. Returns 0 if
4411 OK and <symbol>EOF</symbol> if unable to send the string.
4412 <synopsis>
4413 int PQputline(PGconn *conn,
4414 const char *string);
4415 </synopsis>
4416 </para>
4418 <para>
4419 The <command>COPY</command> data stream sent by a series of calls
4420 to <function>PQputline</function> has the same format as that
4421 returned by <function>PQgetlineAsync</function>, except that
4422 applications are not obliged to send exactly one data row per
4423 <function>PQputline</function> call; it is okay to send a partial
4424 line or multiple lines per call.
4425 </para>
4427 <note>
4428 <para>
4429 Before <productname>PostgreSQL</productname> protocol 3.0, it was necessary
4430 for the application to explicitly send the two characters
4431 <literal>\.</literal> as a final line to indicate to the server that it had
4432 finished sending <command>COPY</> data. While this still works, it is deprecated and the
4433 special meaning of <literal>\.</literal> can be expected to be removed in a
4434 future release. It is sufficient to call <function>PQendcopy</function> after
4435 having sent the actual data.
4436 </para>
4437 </note>
4438 </listitem>
4439 </varlistentry>
4441 <varlistentry>
4442 <term>
4443 <function>PQputnbytes</function>
4444 <indexterm>
4445 <primary>PQputnbytes</primary>
4446 </indexterm>
4447 </term>
4449 <listitem>
4450 <para>
4451 Sends a non-null-terminated string to the server. Returns
4452 0 if OK and <symbol>EOF</symbol> if unable to send the string.
4453 <synopsis>
4454 int PQputnbytes(PGconn *conn,
4455 const char *buffer,
4456 int nbytes);
4457 </synopsis>
4458 </para>
4460 <para>
4461 This is exactly like <function>PQputline</function>, except that the data
4462 buffer need not be null-terminated since the number of bytes to send is
4463 specified directly. Use this procedure when sending binary data.
4464 </para>
4465 </listitem>
4466 </varlistentry>
4468 <varlistentry>
4469 <term>
4470 <function>PQendcopy</function>
4471 <indexterm>
4472 <primary>PQendcopy</primary>
4473 </indexterm>
4474 </term>
4476 <listitem>
4477 <para>
4478 Synchronizes with the server.
4479 <synopsis>
4480 int PQendcopy(PGconn *conn);
4481 </synopsis>
4482 This function waits until the server has finished the copying.
4483 It should either be issued when the last string has been sent
4484 to the server using <function>PQputline</function> or when the
4485 last string has been received from the server using
4486 <function>PGgetline</function>. It must be issued or the server
4487 will get <quote>out of sync</quote> with the client. Upon return
4488 from this function, the server is ready to receive the next SQL
4489 command. The return value is 0 on successful completion,
4490 nonzero otherwise. (Use <function>PQerrorMessage</function> to
4491 retrieve details if the return value is nonzero.)
4492 </para>
4494 <para>
4495 When using <function>PQgetResult</function>, the application should
4496 respond to a <literal>PGRES_COPY_OUT</literal> result by executing
4497 <function>PQgetline</function> repeatedly, followed by
4498 <function>PQendcopy</function> after the terminator line is seen.
4499 It should then return to the <function>PQgetResult</function> loop
4500 until <function>PQgetResult</function> returns a null pointer.
4501 Similarly a <literal>PGRES_COPY_IN</literal> result is processed
4502 by a series of <function>PQputline</function> calls followed by
4503 <function>PQendcopy</function>, then return to the
4504 <function>PQgetResult</function> loop. This arrangement will
4505 ensure that a <command>COPY</command> command embedded in a series
4506 of <acronym>SQL</acronym> commands will be executed correctly.
4507 </para>
4509 <para>
4510 Older applications are likely to submit a <command>COPY</command>
4511 via <function>PQexec</function> and assume that the transaction
4512 is done after <function>PQendcopy</function>. This will work
4513 correctly only if the <command>COPY</command> is the only
4514 <acronym>SQL</acronym> command in the command string.
4515 </para>
4516 </listitem>
4517 </varlistentry>
4518 </variablelist>
4520 </sect2>
4522 </sect1>
4524 <sect1 id="libpq-control">
4525 <title>Control Functions</title>
4527 <para>
4528 These functions control miscellaneous details of <application>libpq</>'s
4529 behavior.
4530 </para>
4532 <variablelist>
4533 <varlistentry>
4534 <term>
4535 <function>PQclientEncoding</function>
4536 <indexterm>
4537 <primary>PQclientEncoding</primary>
4538 </indexterm>
4539 </term>
4541 <listitem>
4542 <para>
4543 Returns the client encoding.
4544 <synopsis>
4545 int PQclientEncoding(const PGconn *<replaceable>conn</replaceable>);
4546 </synopsis>
4548 Note that it returns the encoding ID, not a symbolic string
4549 such as <literal>EUC_JP</literal>. To convert an encoding ID to an encoding name, you
4550 can use:
4552 <synopsis>
4553 char *pg_encoding_to_char(int <replaceable>encoding_id</replaceable>);
4554 </synopsis>
4555 </para>
4556 </listitem>
4557 </varlistentry>
4559 <varlistentry>
4560 <term>
4561 <function>PQsetClientEncoding</function>
4562 <indexterm>
4563 <primary>PQsetClientEncoding</primary>
4564 </indexterm>
4565 </term>
4567 <listitem>
4568 <para>
4569 Sets the client encoding.
4570 <synopsis>
4571 int PQsetClientEncoding(PGconn *<replaceable>conn</replaceable>, const char *<replaceable>encoding</replaceable>);
4572 </synopsis>
4574 <replaceable>conn</replaceable> is a connection to the server,
4575 and <replaceable>encoding</replaceable> is the encoding you want to
4576 use. If the function successfully sets the encoding, it returns 0,
4577 otherwise -1. The current encoding for this connection can be
4578 determined by using <function>PQclientEncoding</>.
4579 </para>
4580 </listitem>
4581 </varlistentry>
4583 <varlistentry>
4584 <term>
4585 <function>PQsetErrorVerbosity</function>
4586 <indexterm>
4587 <primary>PQsetErrorVerbosity</primary>
4588 </indexterm>
4589 </term>
4591 <listitem>
4592 <para>
4593 Determines the verbosity of messages returned by
4594 <function>PQerrorMessage</> and <function>PQresultErrorMessage</>.
4595 <synopsis>
4596 typedef enum {
4597 PQERRORS_TERSE,
4598 PQERRORS_DEFAULT,
4599 PQERRORS_VERBOSE
4600 } PGVerbosity;
4602 PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity);
4603 </synopsis>
4605 <function>PQsetErrorVerbosity</> sets the verbosity mode, returning
4606 the connection's previous setting. In <firstterm>TERSE</> mode,
4607 returned messages include severity, primary text, and position only;
4608 this will normally fit on a single line. The default mode produces
4609 messages that include the above plus any detail, hint, or context
4610 fields (these might span multiple lines). The <firstterm>VERBOSE</>
4611 mode includes all available fields. Changing the verbosity does not
4612 affect the messages available from already-existing
4613 <structname>PGresult</> objects, only subsequently-created ones.
4614 </para>
4615 </listitem>
4616 </varlistentry>
4618 <varlistentry>
4619 <term>
4620 <function>PQtrace</function>
4621 <indexterm>
4622 <primary>PQtrace</primary>
4623 </indexterm>
4624 </term>
4626 <listitem>
4627 <para>
4628 Enables tracing of the client/server communication to a debugging file stream.
4629 <synopsis>
4630 void PQtrace(PGconn *conn, FILE *stream);
4631 </synopsis>
4632 </para>
4634 <note>
4635 <para>
4636 On Windows, if the <application>libpq</> library and an application are
4637 compiled with different flags, this function call will crash the
4638 application because the internal representation of the <literal>FILE</>
4639 pointers differ. Specifically, multithreaded/single-threaded,
4640 release/debug, and static/dynamic flags should be the same for the
4641 library and all applications using that library.
4642 </para>
4643 </note>
4645 </listitem>
4646 </varlistentry>
4648 <varlistentry>
4649 <term>
4650 <function>PQuntrace</function>
4651 <indexterm>
4652 <primary>PQuntrace</primary>
4653 </indexterm>
4654 </term>
4656 <listitem>
4657 <para>
4658 Disables tracing started by <function>PQtrace</function>.
4659 <synopsis>
4660 void PQuntrace(PGconn *conn);
4661 </synopsis>
4662 </para>
4663 </listitem>
4664 </varlistentry>
4665 </variablelist>
4667 </sect1>
4669 <sect1 id="libpq-misc">
4670 <title>Miscellaneous Functions</title>
4672 <para>
4673 As always, there are some functions that just don't fit anywhere.
4674 </para>
4676 <variablelist>
4677 <varlistentry>
4678 <term>
4679 <function>PQfreemem</function>
4680 <indexterm>
4681 <primary>PQfreemem</primary>
4682 </indexterm>
4683 </term>
4685 <listitem>
4686 <para>
4687 Frees memory allocated by <application>libpq</>.
4688 <synopsis>
4689 void PQfreemem(void *ptr);
4690 </synopsis>
4691 </para>
4693 <para>
4694 Frees memory allocated by <application>libpq</>, particularly
4695 <function>PQescapeByteaConn</function>,
4696 <function>PQescapeBytea</function>,
4697 <function>PQunescapeBytea</function>,
4698 and <function>PQnotifies</function>.
4699 It is particularly important that this function, rather than
4700 <function>free()</>, be used on Microsoft Windows. This is because
4701 allocating memory in a DLL and releasing it in the application works
4702 only if multithreaded/single-threaded, release/debug, and static/dynamic
4703 flags are the same for the DLL and the application. On non-Microsoft
4704 Windows platforms, this function is the same as the standard library
4705 function <function>free()</>.
4706 </para>
4707 </listitem>
4708 </varlistentry>
4710 <varlistentry>
4711 <term>
4712 <function>PQconninfoFree</function>
4713 <indexterm>
4714 <primary>PQconninfoFree</primary>
4715 </indexterm>
4716 </term>
4718 <listitem>
4719 <para>
4720 Frees the data structures allocated by
4721 <function>PQconndefaults</> or <function>PQconninfoParse</>.
4722 <synopsis>
4723 void PQconninfoFree(PQconninfoOption *connOptions);
4724 </synopsis>
4725 </para>
4727 <para>
4728 A simple <function>PQfreemem</function> will not do for this, since
4729 the array contains references to subsidiary strings.
4730 </para>
4731 </listitem>
4732 </varlistentry>
4734 <varlistentry>
4735 <term>
4736 <function>PQencryptPassword</function>
4737 <indexterm>
4738 <primary>PQencryptPassword</primary>
4739 </indexterm>
4740 </term>
4742 <listitem>
4743 <para>
4744 Prepares the encrypted form of a <productname>PostgreSQL</> password.
4745 <synopsis>
4746 char * PQencryptPassword(const char *passwd, const char *user);
4747 </synopsis>
4748 This function is intended to be used by client applications that
4749 wish to send commands like <literal>ALTER USER joe PASSWORD
4750 'pwd'</>. It is good practice not to send the original cleartext
4751 password in such a command, because it might be exposed in command
4752 logs, activity displays, and so on. Instead, use this function to
4753 convert the password to encrypted form before it is sent. The
4754 arguments are the cleartext password, and the SQL name of the user
4755 it is for. The return value is a string allocated by
4756 <function>malloc</function>, or <symbol>NULL</symbol> if out of
4757 memory. The caller can assume the string doesn't contain any
4758 special characters that would require escaping. Use
4759 <function>PQfreemem</> to free the result when done with it.
4760 </para>
4761 </listitem>
4762 </varlistentry>
4764 <varlistentry>
4765 <term>
4766 <function>PQmakeEmptyPGresult</function>
4767 <indexterm>
4768 <primary>PQmakeEmptyPGresult</primary>
4769 </indexterm>
4770 </term>
4772 <listitem>
4773 <para>
4774 Constructs an empty <structname>PGresult</structname> object with the given status.
4775 <synopsis>
4776 PGresult *PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status);
4777 </synopsis>
4778 </para>
4780 <para>
4781 This is <application>libpq</>'s internal function to allocate and
4782 initialize an empty <structname>PGresult</structname> object. This
4783 function returns NULL if memory could not be allocated. It is
4784 exported because some applications find it useful to generate result
4785 objects (particularly objects with error status) themselves. If
4786 <parameter>conn</parameter> is not null and <parameter>status</>
4787 indicates an error, the current error message of the specified
4788 connection is copied into the <structname>PGresult</structname>.
4789 Also, if <parameter>conn</parameter> is not null, any event procedures
4790 registered in the connection are copied into the
4791 <structname>PGresult</structname>. (They do not get
4792 <literal>PGEVT_RESULTCREATE</> calls, but see
4793 <function>PQfireResultCreateEvents</function>.)
4794 Note that <function>PQclear</function> should eventually be called
4795 on the object, just as with a <structname>PGresult</structname>
4796 returned by <application>libpq</application> itself.
4797 </para>
4798 </listitem>
4799 </varlistentry>
4801 <varlistentry>
4802 <term>
4803 <function>PQfireResultCreateEvents</function>
4804 <indexterm>
4805 <primary>PQfireResultCreateEvents</primary>
4806 </indexterm>
4807 </term>
4808 <listitem>
4809 <para>
4810 Fires a <literal>PGEVT_RESULTCREATE</literal> event (see <xref
4811 linkend="libpq-events">) for each event procedure registered in the
4812 <structname>PGresult</structname> object. Returns non-zero for success,
4813 zero if any event procedure fails.
4815 <synopsis>
4816 int PQfireResultCreateEvents(PGconn *conn, PGresult *res);
4817 </synopsis>
4818 </para>
4820 <para>
4821 The <literal>conn</> argument is passed through to event procedures
4822 but not used directly. It can be <literal>NULL</> if the event
4823 procedures won't use it.
4824 </para>
4826 <para>
4827 Event procedures that have already received a
4828 <literal>PGEVT_RESULTCREATE</> or <literal>PGEVT_RESULTCOPY</> event
4829 for this object are not fired again.
4830 </para>
4832 <para>
4833 The main reason that this function is separate from
4834 <function>PQmakeEmptyPGResult</function> is that it is often appropriate
4835 to create a <structname>PGresult</structname> and fill it with data
4836 before invoking the event procedures.
4837 </para>
4838 </listitem>
4839 </varlistentry>
4841 <varlistentry>
4842 <term>
4843 <function>PQcopyResult</function>
4844 <indexterm>
4845 <primary>PQcopyResult</primary>
4846 </indexterm>
4847 </term>
4849 <listitem>
4850 <para>
4851 Makes a copy of a <structname>PGresult</structname> object. The copy is
4852 not linked to the source result in any way and
4853 <function>PQclear</function> must be called when the copy is no longer
4854 needed. If the function fails, NULL is returned.
4856 <synopsis>
4857 PGresult *PQcopyResult(const PGresult *src, int flags);
4858 </synopsis>
4859 </para>
4861 <para>
4862 This is not intended to make an exact copy. The returned result is
4863 always put into <literal>PGRES_TUPLES_OK</literal> status, and does not
4864 copy any error message in the source. (It does copy the command status
4865 string, however.) The <parameter>flags</parameter> argument determines
4866 what else is copied. It is a bitwise OR of several flags.
4867 <literal>PG_COPYRES_ATTRS</literal> specifies copying the source
4868 result's attributes (column definitions).
4869 <literal>PG_COPYRES_TUPLES</literal> specifies copying the source
4870 result's tuples. (This implies copying the attributes, too.)
4871 <literal>PG_COPYRES_NOTICEHOOKS</literal> specifies
4872 copying the source result's notify hooks.
4873 <literal>PG_COPYRES_EVENTS</literal> specifies copying the source
4874 result's events. (But any instance data associated with the source
4875 is not copied.)
4876 </para>
4877 </listitem>
4878 </varlistentry>
4880 <varlistentry>
4881 <term>
4882 <function>PQsetResultAttrs</function>
4883 <indexterm>
4884 <primary>PQsetResultAttrs</primary>
4885 </indexterm>
4886 </term>
4888 <listitem>
4889 <para>
4890 Sets the attributes of a <structname>PGresult</structname> object.
4891 <synopsis>
4892 int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs);
4893 </synopsis>
4894 </para>
4896 <para>
4897 The provided <parameter>attDescs</parameter> are copied into the result.
4898 If the <parameter>attDescs</parameter> pointer is NULL or
4899 <parameter>numAttributes</parameter> is less than one, the request is
4900 ignored and the function succeeds. If <parameter>res</parameter>
4901 already contains attributes, the function will fail. If the function
4902 fails, the return value is zero. If the function succeeds, the return
4903 value is non-zero.
4904 </para>
4905 </listitem>
4906 </varlistentry>
4908 <varlistentry>
4909 <term>
4910 <function>PQsetvalue</function>
4911 <indexterm>
4912 <primary>PQsetvalue</primary>
4913 </indexterm>
4914 </term>
4916 <listitem>
4917 <para>
4918 Sets a tuple field value of a <structname>PGresult</structname> object.
4919 <synopsis>
4920 int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len);
4921 </synopsis>
4922 </para>
4924 <para>
4925 The function will automatically grow the result's internal tuples array
4926 as needed. However, the <parameter>tup_num</parameter> argument must be
4927 less than or equal to <function>PQntuples</function>, meaning this
4928 function can only grow the tuples array one tuple at a time. But any
4929 field of any existing tuple can be modified in any order. If a value at
4930 <parameter>field_num</parameter> already exists, it will be overwritten.
4931 If <parameter>len</parameter> is <literal>-1</literal> or
4932 <parameter>value</parameter> is <literal>NULL</literal>, the field value
4933 will be set to an SQL <literal>NULL</literal>. The
4934 <parameter>value</parameter> is copied into the result's private storage,
4935 thus is no longer needed after the function
4936 returns. If the function fails, the return value is zero. If the
4937 function succeeds, the return value is non-zero.
4938 </para>
4939 </listitem>
4940 </varlistentry>
4942 <varlistentry>
4943 <term>
4944 <function>PQresultAlloc</function>
4945 <indexterm>
4946 <primary>PQresultAlloc</primary>
4947 </indexterm>
4948 </term>
4950 <listitem>
4951 <para>
4952 Allocate subsidiary storage for a <structname>PGresult</structname> object.
4953 <synopsis>
4954 void *PQresultAlloc(PGresult *res, size_t nBytes);
4955 </synopsis>
4956 </para>
4958 <para>
4959 Any memory allocated with this function will be freed when
4960 <parameter>res</parameter> is cleared. If the function fails,
4961 the return value is <literal>NULL</literal>. The result is
4962 guaranteed to be adequately aligned for any type of data,
4963 just as for <function>malloc</>.
4964 </para>
4965 </listitem>
4966 </varlistentry>
4968 </variablelist>
4970 </sect1>
4972 <sect1 id="libpq-notice-processing">
4973 <title>Notice Processing</title>
4975 <indexterm zone="libpq-notice-processing">
4976 <primary>notice processing</primary>
4977 <secondary>in libpq</secondary>
4978 </indexterm>
4980 <para>
4981 Notice and warning messages generated by the server are not returned
4982 by the query execution functions, since they do not imply failure of
4983 the query. Instead they are passed to a notice handling function, and
4984 execution continues normally after the handler returns. The default
4985 notice handling function prints the message on
4986 <filename>stderr</filename>, but the application can override this
4987 behavior by supplying its own handling function.
4988 </para>
4990 <para>
4991 For historical reasons, there are two levels of notice handling, called
4992 the notice receiver and notice processor. The default behavior is for
4993 the notice receiver to format the notice and pass a string to the notice
4994 processor for printing. However, an application that chooses to provide
4995 its own notice receiver will typically ignore the notice processor
4996 layer and just do all the work in the notice receiver.
4997 </para>
4999 <para>
5000 The function <function>PQsetNoticeReceiver</function>
5001 <indexterm><primary>notice
5002 receiver</></><indexterm><primary>PQsetNoticeReceiver</></> sets or
5003 examines the current notice receiver for a connection object.
5004 Similarly, <function>PQsetNoticeProcessor</function>
5005 <indexterm><primary>notice
5006 processor</></><indexterm><primary>PQsetNoticeProcessor</></> sets or
5007 examines the current notice processor.
5009 <synopsis>
5010 typedef void (*PQnoticeReceiver) (void *arg, const PGresult *res);
5012 PQnoticeReceiver
5013 PQsetNoticeReceiver(PGconn *conn,
5014 PQnoticeReceiver proc,
5015 void *arg);
5017 typedef void (*PQnoticeProcessor) (void *arg, const char *message);
5019 PQnoticeProcessor
5020 PQsetNoticeProcessor(PGconn *conn,
5021 PQnoticeProcessor proc,
5022 void *arg);
5023 </synopsis>
5025 Each of these functions returns the previous notice receiver or
5026 processor function pointer, and sets the new value. If you supply a
5027 null function pointer, no action is taken, but the current pointer is
5028 returned.
5029 </para>
5031 <para>
5032 When a notice or warning message is received from the server, or
5033 generated internally by <application>libpq</application>, the notice
5034 receiver function is called. It is passed the message in the form of
5035 a <symbol>PGRES_NONFATAL_ERROR</symbol>
5036 <structname>PGresult</structname>. (This allows the receiver to extract
5037 individual fields using <function>PQresultErrorField</>, or the complete
5038 preformatted message using <function>PQresultErrorMessage</>.) The same
5039 void pointer passed to <function>PQsetNoticeReceiver</function> is also
5040 passed. (This pointer can be used to access application-specific state
5041 if needed.)
5042 </para>
5044 <para>
5045 The default notice receiver simply extracts the message (using
5046 <function>PQresultErrorMessage</>) and passes it to the notice
5047 processor.
5048 </para>
5050 <para>
5051 The notice processor is responsible for handling a notice or warning
5052 message given in text form. It is passed the string text of the message
5053 (including a trailing newline), plus a void pointer that is the same
5054 one passed to <function>PQsetNoticeProcessor</function>. (This pointer
5055 can be used to access application-specific state if needed.)
5056 </para>
5058 <para>
5059 The default notice processor is simply:
5060 <programlisting>
5061 static void
5062 defaultNoticeProcessor(void *arg, const char *message)
5064 fprintf(stderr, "%s", message);
5066 </programlisting>
5067 </para>
5069 <para>
5070 Once you have set a notice receiver or processor, you should expect
5071 that that function could be called as long as either the
5072 <structname>PGconn</> object or <structname>PGresult</> objects made
5073 from it exist. At creation of a <structname>PGresult</>, the
5074 <structname>PGconn</>'s current notice handling pointers are copied
5075 into the <structname>PGresult</> for possible use by functions like
5076 <function>PQgetvalue</function>.
5077 </para>
5079 </sect1>
5081 <sect1 id="libpq-events">
5082 <title>Event System</title>
5084 <para>
5085 <application>libpq</application>'s event system is designed to notify
5086 registered event handlers about interesting
5087 <application>libpq</application> events, such as the creation or
5088 destruction of <structname>PGconn</structname> and
5089 <structname>PGresult</structname> objects. A principal use case is that
5090 this allows applications to associate their own data with a
5091 <structname>PGconn</structname> or <structname>PGresult</structname>
5092 and ensure that that data is freed at an appropriate time.
5093 </para>
5095 <para>
5096 Each registered event handler is associated with two pieces of data,
5097 known to <application>libpq</application> only as opaque <literal>void *</>
5098 pointers. There is a <firstterm>passthrough</> pointer that is provided
5099 by the application when the event handler is registered with a
5100 <structname>PGconn</>. The passthrough pointer never changes for the
5101 life of the <structname>PGconn</> and all <structname>PGresult</>s
5102 generated from it; so if used, it must point to long-lived data.
5103 In addition there is an <firstterm>instance data</> pointer, which starts
5104 out NULL in every <structname>PGconn</> and <structname>PGresult</>.
5105 This pointer can be manipulated using the
5106 <function>PQinstanceData</function>,
5107 <function>PQsetInstanceData</function>,
5108 <function>PQresultInstanceData</function> and
5109 <function>PQsetResultInstanceData</function> functions. Note that
5110 unlike the passthrough pointer, instance data of a <structname>PGconn</>
5111 is not automatically inherited by <structname>PGresult</>s created from
5112 it. <application>libpq</application> does not know what passthrough
5113 and instance data pointers point to (if anything) and will never attempt
5114 to free them &mdash; that is the responsibility of the event handler.
5115 </para>
5117 <sect2 id="libpq-events-types">
5118 <title>Event Types</title>
5120 <para>
5121 The enum <literal>PGEventId</> names the types of events handled by
5122 the event system. All its values have names beginning with
5123 <literal>PGEVT</literal>. For each event type, there is a corresponding
5124 event info structure that carries the parameters passed to the event
5125 handlers. The event types are:
5126 </para>
5128 <variablelist>
5129 <varlistentry>
5130 <term><literal>PGEVT_REGISTER</literal></term>
5131 <listitem>
5132 <para>
5133 The register event occurs when <function>PQregisterEventProc</function>
5134 is called. It is the ideal time to initialize any
5135 <literal>instanceData</literal> an event procedure may need. Only one
5136 register event will be fired per event handler per connection. If the
5137 event procedure fails, the registration is aborted.
5139 <synopsis>
5140 typedef struct
5142 PGconn *conn;
5143 } PGEventRegister;
5144 </synopsis>
5146 When a <literal>PGEVT_REGISTER</literal> event is received, the
5147 <parameter>evtInfo</parameter> pointer should be cast to a
5148 <structname>PGEventRegister *</structname>. This structure contains a
5149 <structname>PGconn</structname> that should be in the
5150 <literal>CONNECTION_OK</literal> status; guaranteed if one calls
5151 <function>PQregisterEventProc</function> right after obtaining a good
5152 <structname>PGconn</structname>. When returning a failure code, all
5153 cleanup must be performed as no <literal>PGEVT_CONNDESTROY</literal>
5154 event will be sent.
5155 </para>
5156 </listitem>
5157 </varlistentry>
5159 <varlistentry>
5160 <term><literal>PGEVT_CONNRESET</literal></term>
5161 <listitem>
5162 <para>
5163 The connection reset event is fired on completion of
5164 <function>PQreset</function> or <function>PQresetPoll</function>. In
5165 both cases, the event is only fired if the reset was successful. If
5166 the event procedure fails, the entire connection reset will fail; the
5167 <structname>PGconn</structname> is put into
5168 <literal>CONNECTION_BAD</literal> status and
5169 <function>PQresetPoll</function> will return
5170 <literal>PGRES_POLLING_FAILED</literal>.
5172 <synopsis>
5173 typedef struct
5175 PGconn *conn;
5176 } PGEventConnReset;
5177 </synopsis>
5179 When a <literal>PGEVT_CONNRESET</literal> event is received, the
5180 <parameter>evtInfo</parameter> pointer should be cast to a
5181 <structname>PGEventConnReset *</structname>. Although the contained
5182 <structname>PGconn</structname> was just reset, all event data remains
5183 unchanged. This event should be used to reset/reload/requery any
5184 associated <literal>instanceData</literal>. Note that even if the
5185 event procedure fails to process <literal>PGEVT_CONNRESET</>, it will
5186 still receive a <literal>PGEVT_CONNDESTROY</> event when the connection
5187 is closed.
5188 </para>
5189 </listitem>
5190 </varlistentry>
5192 <varlistentry>
5193 <term><literal>PGEVT_CONNDESTROY</literal></term>
5194 <listitem>
5195 <para>
5196 The connection destroy event is fired in response to
5197 <function>PQfinish</function>. It is the event procedure's
5198 responsibility to properly clean up its event data as libpq has no
5199 ability to manage this memory. Failure to clean up will lead
5200 to memory leaks.
5202 <synopsis>
5203 typedef struct
5205 PGconn *conn;
5206 } PGEventConnDestroy;
5207 </synopsis>
5209 When a <literal>PGEVT_CONNDESTROY</literal> event is received, the
5210 <parameter>evtInfo</parameter> pointer should be cast to a
5211 <structname>PGEventConnDestroy *</structname>. This event is fired
5212 prior to <function>PQfinish</function> performing any other cleanup.
5213 The return value of the event procedure is ignored since there is no
5214 way of indicating a failure from <function>PQfinish</function>. Also,
5215 an event procedure failure should not abort the process of cleaning up
5216 unwanted memory.
5217 </para>
5218 </listitem>
5219 </varlistentry>
5221 <varlistentry>
5222 <term><literal>PGEVT_RESULTCREATE</literal></term>
5223 <listitem>
5224 <para>
5225 The result creation event is fired in response to any query execution
5226 function that generates a result, including
5227 <function>PQgetResult</function>. This event will only be fired after
5228 the result has been created successfully.
5230 <synopsis>
5231 typedef struct
5233 PGconn *conn;
5234 PGresult *result;
5235 } PGEventResultCreate;
5236 </synopsis>
5238 When a <literal>PGEVT_RESULTCREATE</literal> event is received, the
5239 <parameter>evtInfo</parameter> pointer should be cast to a
5240 <structname>PGEventResultCreate *</structname>. The
5241 <parameter>conn</parameter> is the connection used to generate the
5242 result. This is the ideal place to initialize any
5243 <literal>instanceData</literal> that needs to be associated with the
5244 result. If the event procedure fails, the result will be cleared and
5245 the failure will be propagated. The event procedure must not try to
5246 <function>PQclear</> the result object for itself. When returning a
5247 failure code, all cleanup must be performed as no
5248 <literal>PGEVT_RESULTDESTROY</literal> event will be sent.
5249 </para>
5250 </listitem>
5251 </varlistentry>
5253 <varlistentry>
5254 <term><literal>PGEVT_RESULTCOPY</literal></term>
5255 <listitem>
5256 <para>
5257 The result copy event is fired in response to
5258 <function>PQcopyResult</function>. This event will only be fired after
5259 the copy is complete. Only event procedures that have
5260 successfully handled the <literal>PGEVT_RESULTCREATE</literal>
5261 or <literal>PGEVT_RESULTCOPY</literal> event for the source result
5262 will receive <literal>PGEVT_RESULTCOPY</literal> events.
5264 <synopsis>
5265 typedef struct
5267 const PGresult *src;
5268 PGresult *dest;
5269 } PGEventResultCopy;
5270 </synopsis>
5272 When a <literal>PGEVT_RESULTCOPY</literal> event is received, the
5273 <parameter>evtInfo</parameter> pointer should be cast to a
5274 <structname>PGEventResultCopy *</structname>. The
5275 <parameter>src</parameter> result is what was copied while the
5276 <parameter>dest</parameter> result is the copy destination. This event
5277 can be used to provide a deep copy of <literal>instanceData</literal>,
5278 since <literal>PQcopyResult</literal> cannot do that. If the event
5279 procedure fails, the entire copy operation will fail and the
5280 <parameter>dest</parameter> result will be cleared. When returning a
5281 failure code, all cleanup must be performed as no
5282 <literal>PGEVT_RESULTDESTROY</literal> event will be sent for the
5283 destination result.
5284 </para>
5285 </listitem>
5286 </varlistentry>
5288 <varlistentry>
5289 <term><literal>PGEVT_RESULTDESTROY</literal></term>
5290 <listitem>
5291 <para>
5292 The result destroy event is fired in response to a
5293 <function>PQclear</function>. It is the event procedure's
5294 responsibility to properly clean up its event data as libpq has no
5295 ability to manage this memory. Failure to clean up will lead
5296 to memory leaks.
5298 <synopsis>
5299 typedef struct
5301 PGresult *result;
5302 } PGEventResultDestroy;
5303 </synopsis>
5305 When a <literal>PGEVT_RESULTDESTROY</literal> event is received, the
5306 <parameter>evtInfo</parameter> pointer should be cast to a
5307 <structname>PGEventResultDestroy *</structname>. This event is fired
5308 prior to <function>PQclear</function> performing any other cleanup.
5309 The return value of the event procedure is ignored since there is no
5310 way of indicating a failure from <function>PQclear</function>. Also,
5311 an event procedure failure should not abort the process of cleaning up
5312 unwanted memory.
5313 </para>
5314 </listitem>
5315 </varlistentry>
5316 </variablelist>
5317 </sect2>
5319 <sect2 id="libpq-events-proc">
5320 <title>Event Callback Procedure</title>
5322 <variablelist>
5323 <varlistentry>
5324 <term>
5325 <literal>PGEventProc</literal>
5326 <indexterm>
5327 <primary>PGEventProc</primary>
5328 </indexterm>
5329 </term>
5331 <listitem>
5332 <para>
5333 <literal>PGEventProc</literal> is a typedef for a pointer to an
5334 event procedure, that is, the user callback function that receives
5335 events from libpq. The signature of an event procedure must be
5337 <synopsis>
5338 int eventproc(PGEventId evtId, void *evtInfo, void *passThrough)
5339 </synopsis>
5341 The <parameter>evtId</parameter> parameter indicates which
5342 <literal>PGEVT</literal> event occurred. The
5343 <parameter>evtInfo</parameter> pointer must be cast to the appropriate
5344 structure type to obtain further information about the event.
5345 The <parameter>passThrough</parameter> parameter is the pointer
5346 provided to <function>PQregisterEventProc</function> when the event
5347 procedure was registered. The function should return a non-zero value
5348 if it succeeds and zero if it fails.
5349 </para>
5351 <para>
5352 A particular event procedure can be registered only once in any
5353 <structname>PGconn</>. This is because the address of the procedure
5354 is used as a lookup key to identify the associated instance data.
5355 </para>
5357 <caution>
5358 <para>
5359 On Windows, functions can have two different addresses: one visible
5360 from outside a DLL and another visible from inside the DLL. One
5361 should be careful that only one of these addresses is used with
5362 <application>libpq</>'s event-procedure functions, else confusion will
5363 result. The simplest rule for writing code that will work is to
5364 ensure that event procedures are declared <literal>static</>. If the
5365 procedure's address must be available outside its own source file,
5366 expose a separate function to return the address.
5367 </para>
5368 </caution>
5369 </listitem>
5370 </varlistentry>
5371 </variablelist>
5372 </sect2>
5374 <sect2 id="libpq-events-funcs">
5375 <title>Event Support Functions</title>
5377 <variablelist>
5378 <varlistentry>
5379 <term>
5380 <function>PQregisterEventProc</function>
5381 <indexterm>
5382 <primary>PQregisterEventProc</primary>
5383 </indexterm>
5384 </term>
5386 <listitem>
5387 <para>
5388 Registers an event callback procedure with libpq.
5390 <synopsis>
5391 int PQregisterEventProc(PGconn *conn, PGEventProc proc,
5392 const char *name, void *passThrough);
5393 </synopsis>
5394 </para>
5396 <para>
5397 An event procedure must be registered once on each
5398 <structname>PGconn</> you want to receive events about. There is no
5399 limit, other than memory, on the number of event procedures that
5400 can be registered with a connection. The function returns a non-zero
5401 value if it succeeds and zero if it fails.
5402 </para>
5404 <para>
5405 The <parameter>proc</parameter> argument will be called when a libpq
5406 event is fired. Its memory address is also used to lookup
5407 <literal>instanceData</literal>. The <parameter>name</parameter>
5408 argument is used to refer to the event procedure in error messages.
5409 This value cannot be NULL or a zero-length string. The name string is
5410 copied into the <structname>PGconn</>, so what is passed need not be
5411 long-lived. The <parameter>passThrough</parameter> pointer is passed
5412 to the <parameter>proc</parameter> whenever an event occurs. This
5413 argument can be NULL.
5414 </para>
5415 </listitem>
5416 </varlistentry>
5418 <varlistentry>
5419 <term>
5420 <function>PQsetInstanceData</function>
5421 <indexterm>
5422 <primary>PQsetInstanceData</primary>
5423 </indexterm>
5424 </term>
5425 <listitem>
5426 <para>
5427 Sets the conn's instanceData for proc to data. This returns non-zero
5428 for success and zero for failure. (Failure is only possible if
5429 the proc has not been properly registered in the conn.)
5431 <synopsis>
5432 int PQsetInstanceData(PGconn *conn, PGEventProc proc, void *data);
5433 </synopsis>
5434 </para>
5435 </listitem>
5436 </varlistentry>
5438 <varlistentry>
5439 <term>
5440 <function>PQinstanceData</function>
5441 <indexterm>
5442 <primary>PQinstanceData</primary>
5443 </indexterm>
5444 </term>
5445 <listitem>
5446 <para>
5447 Returns the conn's instanceData associated with proc, or NULL
5448 if there is none.
5450 <synopsis>
5451 void *PQinstanceData(const PGconn *conn, PGEventProc proc);
5452 </synopsis>
5453 </para>
5454 </listitem>
5455 </varlistentry>
5457 <varlistentry>
5458 <term>
5459 <function>PQresultSetInstanceData</function>
5460 <indexterm>
5461 <primary>PQresultSetInstanceData</primary>
5462 </indexterm>
5463 </term>
5464 <listitem>
5465 <para>
5466 Sets the result's instanceData for proc to data. This returns non-zero
5467 for success and zero for failure. (Failure is only possible if the
5468 proc has not been properly registered in the result.)
5470 <synopsis>
5471 int PQresultSetInstanceData(PGresult *res, PGEventProc proc, void *data);
5472 </synopsis>
5473 </para>
5474 </listitem>
5475 </varlistentry>
5477 <varlistentry>
5478 <term>
5479 <function>PQresultInstanceData</function>
5480 <indexterm>
5481 <primary>PQresultInstanceData</primary>
5482 </indexterm>
5483 </term>
5484 <listitem>
5485 <para>
5486 Returns the result's instanceData associated with proc, or NULL
5487 if there is none.
5489 <synopsis>
5490 void *PQresultInstanceData(const PGresult *res, PGEventProc proc);
5491 </synopsis>
5492 </para>
5493 </listitem>
5494 </varlistentry>
5495 </variablelist>
5496 </sect2>
5498 <sect2 id="libpq-events-example">
5499 <title>Event Example</title>
5501 <para>
5502 Here is a skeleton example of managing private data associated with
5503 libpq connections and results.
5504 </para>
5506 <programlisting>
5507 <![CDATA[
5508 /* required header for libpq events (note: includes libpq-fe.h) */
5509 #include <libpq-events.h>
5511 /* The instanceData */
5512 typedef struct
5514 int n;
5515 char *str;
5516 } mydata;
5518 /* PGEventProc */
5519 static int myEventProc(PGEventId evtId, void *evtInfo, void *passThrough);
5522 main(void)
5524 mydata *data;
5525 PGresult *res;
5526 PGconn *conn = PQconnectdb("dbname = postgres");
5528 if (PQstatus(conn) != CONNECTION_OK)
5530 fprintf(stderr, "Connection to database failed: %s",
5531 PQerrorMessage(conn));
5532 PQfinish(conn);
5533 return 1;
5536 /* called once on any connection that should receive events.
5537 * Sends a PGEVT_REGISTER to myEventProc.
5539 if (!PQregisterEventProc(conn, myEventProc, "mydata_proc", NULL))
5541 fprintf(stderr, "Cannot register PGEventProc\n");
5542 PQfinish(conn);
5543 return 1;
5546 /* conn instanceData is available */
5547 data = PQinstanceData(conn, myEventProc);
5549 /* Sends a PGEVT_RESULTCREATE to myEventProc */
5550 res = PQexec(conn, "SELECT 1 + 1");
5552 /* result instanceData is available */
5553 data = PQresultInstanceData(res, myEventProc);
5555 /* If PG_COPYRES_EVENTS is used, sends a PGEVT_RESULTCOPY to myEventProc */
5556 res_copy = PQcopyResult(res, PG_COPYRES_TUPLES | PG_COPYRES_EVENTS);
5558 /* result instanceData is available if PG_COPYRES_EVENTS was
5559 * used during the PQcopyResult call.
5561 data = PQresultInstanceData(res_copy, myEventProc);
5563 /* Both clears send a PGEVT_RESULTDESTROY to myEventProc */
5564 PQclear(res);
5565 PQclear(res_copy);
5567 /* Sends a PGEVT_CONNDESTROY to myEventProc */
5568 PQfinish(conn);
5570 return 0;
5573 static int
5574 myEventProc(PGEventId evtId, void *evtInfo, void *passThrough)
5576 switch (evtId)
5578 case PGEVT_REGISTER:
5580 PGEventRegister *e = (PGEventRegister *)evtInfo;
5581 mydata *data = get_mydata(e->conn);
5583 /* associate app specific data with connection */
5584 PQsetInstanceData(e->conn, myEventProc, data);
5585 break;
5588 case PGEVT_CONNRESET:
5590 PGEventConnReset *e = (PGEventConnReset *)evtInfo;
5591 mydata *data = PQinstanceData(e->conn, myEventProc);
5593 if (data)
5594 memset(data, 0, sizeof(mydata));
5595 break;
5598 case PGEVT_CONNDESTROY:
5600 PGEventConnDestroy *e = (PGEventConnDestroy *)evtInfo;
5601 mydata *data = PQinstanceData(e->conn, myEventProc);
5603 /* free instance data because the conn is being destroyed */
5604 if (data)
5605 free_mydata(data);
5606 break;
5609 case PGEVT_RESULTCREATE:
5611 PGEventResultCreate *e = (PGEventResultCreate *)evtInfo;
5612 mydata *conn_data = PQinstanceData(e->conn, myEventProc);
5613 mydata *res_data = dup_mydata(conn_data);
5615 /* associate app specific data with result (copy it from conn) */
5616 PQsetResultInstanceData(e->result, myEventProc, res_data);
5617 break;
5620 case PGEVT_RESULTCOPY:
5622 PGEventResultCopy *e = (PGEventResultCopy *)evtInfo;
5623 mydata *src_data = PQresultInstanceData(e->src, myEventProc);
5624 mydata *dest_data = dup_mydata(src_data);
5626 /* associate app specific data with result (copy it from a result) */
5627 PQsetResultInstanceData(e->dest, myEventProc, dest_data);
5628 break;
5631 case PGEVT_RESULTDESTROY:
5633 PGEventResultDestroy *e = (PGEventResultDestroy *)evtInfo;
5634 mydata *data = PQresultInstanceData(e->result, myEventProc);
5636 /* free instance data because the result is being destroyed */
5637 if (data)
5638 free_mydata(data);
5639 break;
5642 /* unknown event id, just return TRUE. */
5643 default:
5644 break;
5647 return TRUE; /* event processing succeeded */
5650 </programlisting>
5651 </sect2>
5652 </sect1>
5654 <sect1 id="libpq-envars">
5655 <title>Environment Variables</title>
5657 <indexterm zone="libpq-envars">
5658 <primary>environment variable</primary>
5659 </indexterm>
5661 <para>
5662 The following environment variables can be used to select default
5663 connection parameter values, which will be used by
5664 <function>PQconnectdb</>, <function>PQsetdbLogin</> and
5665 <function>PQsetdb</> if no value is directly specified by the calling
5666 code. These are useful to avoid hard-coding database connection
5667 information into simple client applications, for example.
5669 <itemizedlist>
5670 <listitem>
5671 <para>
5672 <indexterm>
5673 <primary><envar>PGHOST</envar></primary>
5674 </indexterm>
5675 <envar>PGHOST</envar> behaves the same as <xref
5676 linkend="libpq-connect-host"> connection parameter.
5677 </para>
5678 </listitem>
5680 <listitem>
5681 <para>
5682 <indexterm>
5683 <primary><envar>PGHOSTADDR</envar></primary>
5684 </indexterm>
5685 <envar>PGHOSTADDR</envar> behaves the same as <xref
5686 linkend="libpq-connect-hostaddr"> connection parameter.
5687 This can be set instead of or in addition to <envar>PGHOST</envar>
5688 to avoid DNS lookup overhead.
5689 </para>
5690 </listitem>
5692 <listitem>
5693 <para>
5694 <indexterm>
5695 <primary><envar>PGPORT</envar></primary>
5696 </indexterm>
5697 <envar>PGPORT</envar> behaves the same as <xref
5698 linkend="libpq-connect-port"> connection parameter.
5699 </para>
5700 </listitem>
5702 <listitem>
5703 <para>
5704 <indexterm>
5705 <primary><envar>PGDATABASE</envar></primary>
5706 </indexterm>
5707 <envar>PGDATABASE</envar> behaves the same as <xref
5708 linkend="libpq-connect-dbname"> connection parameter.
5709 </para>
5710 </listitem>
5712 <listitem>
5713 <para>
5714 <indexterm>
5715 <primary><envar>PGUSER</envar></primary>
5716 </indexterm>
5717 <envar>PGUSER</envar> behaves the same as <xref
5718 linkend="libpq-connect-user"> connection parameter.
5719 database.
5720 </para>
5721 </listitem>
5723 <listitem>
5724 <para>
5725 <indexterm>
5726 <primary><envar>PGPASSWORD</envar></primary>
5727 </indexterm>
5728 <envar>PGPASSWORD</envar> behaves the same as <xref
5729 linkend="libpq-connect-password"> connection parameter.
5730 Use of this environment variable
5731 is not recommended for security reasons (some operating systems
5732 allow non-root users to see process environment variables via
5733 <application>ps</>); instead consider using the
5734 <filename>~/.pgpass</> file (see <xref linkend="libpq-pgpass">).
5735 </para>
5736 </listitem>
5738 <listitem>
5739 <para>
5740 <indexterm>
5741 <primary><envar>PGPASSFILE</envar></primary>
5742 </indexterm>
5743 <envar>PGPASSFILE</envar> specifies the name of the password file to
5744 use for lookups. If not set, it defaults to <filename>~/.pgpass</>
5745 (see <xref linkend="libpq-pgpass">).
5746 </para>
5747 </listitem>
5749 <listitem>
5750 <para>
5751 <indexterm>
5752 <primary><envar>PGSERVICE</envar></primary>
5753 </indexterm>
5754 <envar>PGSERVICE</envar> behaves the same as <xref
5755 linkend="libpq-connect-service"> connection parameter.
5756 </para>
5757 </listitem>
5759 <listitem>
5760 <para>
5761 <indexterm>
5762 <primary><envar>PGREALM</envar></primary>
5763 </indexterm>
5764 <envar>PGREALM</envar> sets the Kerberos realm to use with
5765 <productname>PostgreSQL</productname>, if it is different from the
5766 local realm. If <envar>PGREALM</envar> is set,
5767 <application>libpq</application> applications will attempt
5768 authentication with servers for this realm and use separate ticket
5769 files to avoid conflicts with local ticket files. This
5770 environment variable is only used if Kerberos authentication is
5771 selected by the server.
5772 </para>
5773 </listitem>
5775 <listitem>
5776 <para>
5777 <indexterm>
5778 <primary><envar>PGOPTIONS</envar></primary>
5779 </indexterm>
5780 <envar>PGOPTIONS</envar> behaves the same as <xref
5781 linkend="libpq-connect-options"> connection parameter.
5782 </para>
5783 </listitem>
5785 <listitem>
5786 <para>
5787 <indexterm>
5788 <primary><envar>PGSSLMODE</envar></primary>
5789 </indexterm>
5790 <envar>PGSSLMODE</envar> behaves the same as <xref
5791 linkend="libpq-connect-sslmode"> connection parameter.
5792 </para>
5793 </listitem>
5795 <listitem>
5796 <para>
5797 <indexterm>
5798 <primary><envar>PGREQUIRESSL</envar></primary>
5799 </indexterm>
5800 <envar>PGREQUIRESSL</envar> behaves the same as <xref
5801 linkend="libpq-connect-requiressl"> connection parameter.
5802 </para>
5803 </listitem>
5805 <listitem>
5806 <para>
5807 <indexterm>
5808 <primary><envar>PGSSLCERT</envar></primary>
5809 </indexterm>
5810 <envar>PGSSLCERT</envar> behaves the same as <xref
5811 linkend="libpq-connect-sslcert"> connection parameter.
5812 </para>
5813 </listitem>
5815 <listitem>
5816 <para>
5817 <indexterm>
5818 <primary><envar>PGSSLKEY</envar></primary>
5819 </indexterm>
5820 <envar>PGSSLKEY</envar> behaves the same as <xref
5821 linkend="libpq-connect-sslkey"> connection parameter.
5822 </para>
5823 </listitem>
5825 <listitem>
5826 <para>
5827 <indexterm>
5828 <primary><envar>PGSSLROOTCERT</envar></primary>
5829 </indexterm>
5830 <envar>PGSSLROOTCERT</envar> behaves the same as <xref
5831 linkend="libpq-connect-sslrootcert"> connection parameter.
5832 </para>
5833 </listitem>
5835 <listitem>
5836 <para>
5837 <indexterm>
5838 <primary><envar>PGSSLCRL</envar></primary>
5839 </indexterm>
5840 <envar>PGSSLCRL</envar> behaves the same as <xref
5841 linkend="libpq-connect-sslcrl"> connection parameter.
5842 </para>
5843 </listitem>
5845 <listitem>
5846 <para>
5847 <indexterm>
5848 <primary><envar>PGKRBSRVNAME</envar></primary>
5849 </indexterm>
5850 <envar>PGKRBSRVNAME</envar> behaves the same as <xref
5851 linkend="libpq-connect-krbsrvname"> connection parameter.
5852 </para>
5853 </listitem>
5855 <listitem>
5856 <para>
5857 <indexterm>
5858 <primary><envar>PGGSSLIB</envar></primary>
5859 </indexterm>
5860 <envar>PGGSSLIB</envar> behaves the same as <xref
5861 linkend="libpq-connect-gsslib"> connection parameter.
5862 </para>
5863 </listitem>
5865 <listitem>
5866 <para>
5867 <indexterm>
5868 <primary><envar>PGCONNECT_TIMEOUT</envar></primary>
5869 </indexterm>
5870 <envar>PGCONNECT_TIMEOUT</envar> behaves the same as <xref
5871 linkend="libpq-connect-connect-timeout"> connection parameter.
5872 </para>
5873 </listitem>
5874 </itemizedlist>
5875 </para>
5877 <para>
5878 The following environment variables can be used to specify default
5879 behavior for each <productname>PostgreSQL</productname> session. (See
5880 also the <xref linkend="sql-alteruser" endterm="sql-alteruser-title">
5881 and <xref linkend="sql-alterdatabase" endterm="sql-alterdatabase-title">
5882 commands for ways to set default behavior on a per-user or per-database
5883 basis.)
5885 <itemizedlist>
5886 <listitem>
5887 <para>
5888 <indexterm>
5889 <primary><envar>PGDATESTYLE</envar></primary>
5890 </indexterm>
5891 <envar>PGDATESTYLE</envar> sets the default style of date/time
5892 representation. (Equivalent to <literal>SET datestyle TO
5893 ...</literal>.)
5894 </para>
5895 </listitem>
5897 <listitem>
5898 <para>
5899 <indexterm>
5900 <primary><envar>PGTZ</envar></primary>
5901 </indexterm>
5902 <envar>PGTZ</envar> sets the default time zone. (Equivalent to
5903 <literal>SET timezone TO ...</literal>.)
5904 </para>
5905 </listitem>
5907 <listitem>
5908 <para>
5909 <indexterm>
5910 <primary><envar>PGCLIENTENCODING</envar></primary>
5911 </indexterm>
5912 <envar>PGCLIENTENCODING</envar> sets the default client character
5913 set encoding. (Equivalent to <literal>SET client_encoding TO
5914 ...</literal>.)
5915 </para>
5916 </listitem>
5918 <listitem>
5919 <para>
5920 <indexterm>
5921 <primary><envar>PGGEQO</envar></primary>
5922 </indexterm>
5923 <envar>PGGEQO</envar> sets the default mode for the genetic query
5924 optimizer. (Equivalent to <literal>SET geqo TO ...</literal>.)
5925 </para>
5926 </listitem>
5927 </itemizedlist>
5929 Refer to the <acronym>SQL</acronym> command <xref linkend="sql-set"
5930 endterm="sql-set-title"> for information on correct values for these
5931 environment variables.
5932 </para>
5934 <para>
5935 The following environment variables determine internal behavior of
5936 <application>libpq</application>; they override compiled-in defaults.
5938 <itemizedlist>
5939 <listitem>
5940 <para>
5941 <indexterm>
5942 <primary><envar>PGSYSCONFDIR</envar></primary>
5943 </indexterm>
5944 <envar>PGSYSCONFDIR</envar> sets the directory containing the
5945 <filename>pg_service.conf</> file.
5946 </para>
5947 </listitem>
5949 <listitem>
5950 <para>
5951 <indexterm>
5952 <primary><envar>PGLOCALEDIR</envar></primary>
5953 </indexterm>
5954 <envar>PGLOCALEDIR</envar> sets the directory containing the
5955 <literal>locale</> files for message internationalization.
5956 </para>
5957 </listitem>
5958 </itemizedlist>
5959 </para>
5961 </sect1>
5964 <sect1 id="libpq-pgpass">
5965 <title>The Password File</title>
5967 <indexterm zone="libpq-pgpass">
5968 <primary>password file</primary>
5969 </indexterm>
5970 <indexterm zone="libpq-pgpass">
5971 <primary>.pgpass</primary>
5972 </indexterm>
5974 <para>
5975 The file <filename>.pgpass</filename> in a user's home directory or the
5976 file referenced by <envar>PGPASSFILE</envar> can contain passwords to
5977 be used if the connection requires a password (and no password has been
5978 specified otherwise). On Microsoft Windows the file is named
5979 <filename>%APPDATA%\postgresql\pgpass.conf</> (where
5980 <filename>%APPDATA%</> refers to the Application Data subdirectory in
5981 the user's profile).
5982 </para>
5984 <para>
5985 This file should contain lines of the following format:
5986 <synopsis>
5987 <replaceable>hostname</replaceable>:<replaceable>port</replaceable>:<replaceable>database</replaceable>:<replaceable>username</replaceable>:<replaceable>password</replaceable>
5988 </synopsis>
5989 Each of the first four fields can be a literal value, or
5990 <literal>*</literal>, which matches anything. The password field from
5991 the first line that matches the current connection parameters will be
5992 used. (Therefore, put more-specific entries first when you are using
5993 wildcards.) If an entry needs to contain <literal>:</literal> or
5994 <literal>\</literal>, escape this character with <literal>\</literal>.
5995 A host name of <literal>localhost</> matches both TCP (host name
5996 <literal>localhost</>) and Unix domain socket (<literal>pghost</> empty
5997 or the default socket directory) connections coming from the local
5998 machine.
5999 </para>
6001 <para>
6002 On Unix systems, the permissions on <filename>.pgpass</filename> must
6003 disallow any access to world or group; achieve this by the command
6004 <command>chmod 0600 ~/.pgpass</command>. If the permissions are less
6005 strict than this, the file will be ignored. On Microsoft Windows, it
6006 is assumed that the file is stored in a directory that is secure, so
6007 no special permissions check is made.
6008 </para>
6009 </sect1>
6012 <sect1 id="libpq-pgservice">
6013 <title>The Connection Service File</title>
6015 <indexterm zone="libpq-pgservice">
6016 <primary>connection service file</primary>
6017 </indexterm>
6018 <indexterm zone="libpq-pgservice">
6019 <primary>pg_service.conf</primary>
6020 </indexterm>
6022 <para>
6023 The connection service file allows libpq connection parameters to be
6024 associated with a single service name. That service name can then be
6025 specified by a libpq connection, and the associated settings will be
6026 used. This allows connection parameters to be modified without requiring
6027 a recompile of the libpq application. The service name can also be
6028 specified using the <envar>PGSERVICE</envar> environment variable.
6029 </para>
6031 <para>
6032 To use this feature, copy
6033 <filename>share/pg_service.conf.sample</filename> to
6034 <filename>etc/pg_service.conf</filename> and edit the file to add
6035 service names and parameters. This file can be used for client-only
6036 installs too. The file's location can also be specified by the
6037 <envar>PGSYSCONFDIR</envar> environment variable.
6038 </para>
6039 </sect1>
6042 <sect1 id="libpq-ldap">
6043 <title>LDAP Lookup of Connection Parameters</title>
6045 <indexterm zone="libpq-ldap">
6046 <primary>LDAP connection parameter lookup</primary>
6047 </indexterm>
6049 <para>
6050 If <application>libpq</application> has been compiled with LDAP support (option
6051 <literal><option>--with-ldap</option></literal> for <command>configure</command>)
6052 it is possible to retrieve connection options like <literal>host</literal>
6053 or <literal>dbname</literal> via LDAP from a central server.
6054 The advantage is that if the connection parameters for a database change,
6055 the connection information doesn't have to be updated on all client machines.
6056 </para>
6058 <para>
6059 LDAP connection parameter lookup uses the connection service file
6060 <filename>pg_service.conf</filename> (see <xref
6061 linkend="libpq-pgservice">). A line in a
6062 <filename>pg_service.conf</filename> stanza that starts with
6063 <literal>ldap://</literal> will be recognized as an LDAP URL and an
6064 LDAP query will be performed. The result must be a list of
6065 <literal>keyword = value</literal> pairs which will be used to set
6066 connection options. The URL must conform to RFC 1959 and be of the
6067 form
6068 <synopsis>
6069 ldap://[<replaceable>hostname</replaceable>[:<replaceable>port</replaceable>]]/<replaceable>search_base</replaceable>?<replaceable>attribute</replaceable>?<replaceable>search_scope</replaceable>?<replaceable>filter</replaceable>
6070 </synopsis>
6071 where <replaceable>hostname</replaceable> defaults to
6072 <literal>localhost</literal> and <replaceable>port</replaceable>
6073 defaults to 389.
6074 </para>
6076 <para>
6077 Processing of <filename>pg_service.conf</filename> is terminated after
6078 a successful LDAP lookup, but is continued if the LDAP server cannot
6079 be contacted. This is to provide a fallback with further LDAP URL
6080 lines that point to different LDAP servers, classical <literal>keyword
6081 = value</literal> pairs, or default connection options. If you would
6082 rather get an error message in this case, add a syntactically incorrect
6083 line after the LDAP URL.
6084 </para>
6086 <para>
6087 A sample LDAP entry that has been created with the LDIF file
6088 <synopsis>
6089 version:1
6090 dn:cn=mydatabase,dc=mycompany,dc=com
6091 changetype:add
6092 objectclass:top
6093 objectclass:groupOfUniqueNames
6094 cn:mydatabase
6095 uniqueMember:host=dbserver.mycompany.com
6096 uniqueMember:port=5439
6097 uniqueMember:dbname=mydb
6098 uniqueMember:user=mydb_user
6099 uniqueMember:sslmode=require
6100 </synopsis>
6101 might be queried with the following LDAP URL:
6102 <synopsis>
6103 ldap://ldap.mycompany.com/dc=mycompany,dc=com?uniqueMember?one?(cn=mydatabase)
6104 </synopsis>
6105 </para>
6107 <para>
6108 You can also mix regular service file entries with LDAP lookups.
6109 A complete example for a stanza in <filename>pg_service.conf</filename>
6110 would be:
6111 <synopsis>
6112 # only host and port are stored in LDAP, specify dbname and user explicitly
6113 [customerdb]
6114 dbname=customer
6115 user=appuser
6116 ldap://ldap.acme.com/cn=dbserver,cn=hosts?pgconnectinfo?base?(objectclass=*)
6117 </synopsis>
6118 </para>
6120 </sect1>
6123 <sect1 id="libpq-ssl">
6124 <title>SSL Support</title>
6126 <indexterm zone="libpq-ssl">
6127 <primary>SSL</primary>
6128 </indexterm>
6130 <para>
6131 <productname>PostgreSQL</> has native support for using <acronym>SSL</>
6132 connections to encrypt client/server communications for increased
6133 security. See <xref linkend="ssl-tcp"> for details about the server-side
6134 <acronym>SSL</> functionality.
6135 </para>
6137 <para>
6138 <application>libpq</application> reads the system-wide
6139 <productname>OpenSSL</productname> configuration file. By default, this
6140 file is named <filename>openssl.cnf</filename> and is located in the
6141 directory reported by <literal>openssl version -d</>. This default
6142 can be overridden by setting environment variable
6143 <envar>OPENSSL_CONF</envar> to the name of the desired configuration
6144 file.
6145 </para>
6147 <sect2 id="libq-ssl-certificates">
6148 <title>Certificate verification</title>
6150 <para>
6151 By default, <productname>PostgreSQL</> will not perform any verification of
6152 the server certificate. This means that it is possible to spoof the server
6153 identity (for example by modifying a DNS record or by taking over the server
6154 IP address) without the client knowing. In order to prevent this,
6155 <acronym>SSL</> certificate verification must be used.
6156 </para>
6158 <para>
6159 If the parameter <literal>sslmode</> is set to <literal>verify-ca</>
6160 libpq will verify that the server is trustworthy by checking the certificate
6161 chain up to a trusted <acronym>CA</>. If <literal>sslmode</> is set to
6162 <literal>verify-full</>, libpq will <emphasis>also</> verify that the server
6163 hostname matches that of the certificate. The SSL connection will fail if
6164 the server certificate cannot be verified. <literal>verify-full</> is
6165 recommended in most security sensitive environments.
6166 </para>
6168 <para>
6169 In <literal>verify-full</> mode, the <literal>cn</> attribute of the
6170 certificate is matched against the hostname. If the <literal>cn</>
6171 attribute starts with an asterisk (<literal>*</>), it will be treated as
6172 a wildcard, and will match all characters <emphasis>except</> a dot
6173 (<literal>.</>). This means the certificate will not match subdomains.
6174 If the connection is made using an IP address instead of a hostname, the
6175 IP address will be matched (without doing any DNS lookups).
6176 </para>
6178 <para>
6179 To allow verification, the certificate of a trusted <acronym>CA</> must be
6180 placed in the file <filename>~/.postgresql/root.crt</> in the user's home
6181 directory. (On Microsoft Windows the file is named
6182 <filename>%APPDATA%\postgresql\root.crt</filename>.)
6183 </para>
6185 <para>
6186 Certificate Revocation List (CRL) entries are also checked
6187 if the file <filename>~/.postgresql/root.crl</filename> exists
6188 (<filename>%APPDATA%\postgresql\root.crl</filename> on Microsoft
6189 Windows).
6190 </para>
6192 <para>
6193 The location of the root certificate store and the CRL can be overridden
6194 by the connection parameters <literal>sslrootcert</> and <literal>sslcrl</>
6195 or the environment variables <envar>PGSSLROOTCERT</> and <envar>PGSSLCRL</>.
6196 </para>
6197 </sect2>
6199 <sect2 id="libpq-ssl-clientcert">
6200 <title>Client certificates</title>
6202 <para>
6203 If the server requests a trusted client certificate,
6204 <application>libpq</application> will send the certificate stored in
6205 file <filename>~/.postgresql/postgresql.crt</> in the user's home
6206 directory. The certificate must be signed by one of the certificate
6207 authorities (<acronym>CA</acronym>) trusted by the server. A matching
6208 private key file <filename>~/.postgresql/postgresql.key</> must also
6209 be present. The private
6210 key file must not allow any access to world or group; achieve this by the
6211 command <command>chmod 0600 ~/.postgresql/postgresql.key</command>.
6212 On Microsoft Windows these files are named
6213 <filename>%APPDATA%\postgresql\postgresql.crt</filename> and
6214 <filename>%APPDATA%\postgresql\postgresql.key</filename>, and there
6215 is no special permissions check since the directory is presumed secure.
6216 The location of the certificate and key files can be overridden by the
6217 connection parameters <literal>sslcert</> and <literal>sslkey</> or the
6218 environment variables <envar>PGSSLCERT</> and <envar>PGSSLKEY</>.
6219 </para>
6221 </sect2>
6223 <sect2 id="libpq-ssl-protection">
6224 <title>Protection provided in different modes</title>
6226 <para>
6227 The different values for the <literal>sslmode</> parameter provide different
6228 levels of protection, in different environments. SSL itself provides
6229 protection against three different types of attacks:
6230 </para>
6231 <table id="libpq-ssl-protect-attacks">
6232 <title>SSL attacks</title>
6233 <tgroup cols="2">
6234 <thead>
6235 <row>
6236 <entry>Type</entry>
6237 <entry>Description</entry>
6238 </row>
6239 </thead>
6241 <tbody>
6242 <row>
6243 <entry>Eavesdropping</entry>
6244 <entry>If a third party can listen to the network traffic between the
6245 client and the server, it can read both connection information (including
6246 the username and password) and the data that is passed. <acronym>SSL</>
6247 uses encryption to prevent this.
6248 </entry>
6249 </row>
6251 <row>
6252 <entry>Man in the middle (<acronym>MITM</>)</entry>
6253 <entry>If a third party can modify the data while passing between the
6254 client and server, it can pretend to be the server and therefore see and
6255 modify data <emphasis>even if it is encrypted</>. The third party can then
6256 forward the connection information and data to the original server,
6257 making it impossible to detect this attack. Common vectors to do this
6258 include DNS poisoning and address hijacking, whereby the client is directed
6259 to a different server than intended. There are also several other
6260 attack methods that can accomplish this. <acronym>SSL</> uses certificate
6261 verification to prevent this, by authenticating the server to the client.
6262 </entry>
6263 </row>
6265 <row>
6266 <entry>Impersonation</entry>
6267 <entry>If a third party can pretend to be an authorized client, it can
6268 simply access data it should not have access to. Typically this can
6269 happen through insecure password management. <acronym>SSL</> uses
6270 client certificates to prevent this, by making sure that only holders
6271 of valid certificates can access the server.
6272 </entry>
6273 </row>
6274 </tbody>
6275 </tgroup>
6276 </table>
6278 <para>
6279 For a connection to be known secure, the two first of these have to be
6280 set up on <emphasis>both the client and the server</> before the connection
6281 is made. If it is only configured on the server, the client may end up
6282 sending sensitive information (e.g. passwords) before
6283 it knows that the server requires high security. In libpq, this is controlled
6284 by setting the <literal>sslmode</> parameter to <literal>verify-full</> or
6285 <literal>verify-ca</>, and providing the system with a root certificate to
6286 verify against. This is analogous to using a <literal>https</>
6287 <acronym>URL</> for encrypted web browsing.
6288 </para>
6290 <para>
6291 Once the server has been authenticated, the client can pass sensitive data.
6292 This means that up until this point, the client does not need to know if
6293 certificates will be used for authentication, making it safe to specify this
6294 only in the server configuration.
6295 </para>
6297 <para>
6298 All <acronym>SSL</> options carry overhead in the form of encryption and
6299 key-exchange, and it is a tradeoff that has to be made between performance
6300 and security. The following table illustrates the risks the different
6301 <literal>sslmode</> values protect against, and what statement they make
6302 about security and overhead:
6303 </para>
6305 <table id="libpq-ssl-sslmode-statements">
6306 <title>SSL mode descriptions</title>
6307 <tgroup cols="4">
6308 <thead>
6309 <row>
6310 <entry><literal>sslmode</></entry>
6311 <entry>Eavesdropping protection</entry>
6312 <entry><acronym>MITM</> protection</entry>
6313 <entry>Statement</entry>
6314 </row>
6315 </thead>
6317 <tbody>
6318 <row>
6319 <entry><literal>disabled</></entry>
6320 <entry>No</entry>
6321 <entry>No</entry>
6322 <entry>I don't care about security, and I don't want to pay the overhead
6323 of encryption.
6324 </entry>
6325 </row>
6327 <row>
6328 <entry><literal>allow</></entry>
6329 <entry>Maybe</entry>
6330 <entry>No</entry>
6331 <entry>I don't care about security, but I will pay the overhead of
6332 encryption if the server insists on it.
6333 </entry>
6334 </row>
6336 <row>
6337 <entry><literal>prefer</></entry>
6338 <entry>Maybe</entry>
6339 <entry>No</entry>
6340 <entry>I don't care about encryption, but I wish to pay the overhead of
6341 encryption if the server supports it.
6342 </entry>
6343 </row>
6345 <row>
6346 <entry><literal>require</></entry>
6347 <entry>Yes</entry>
6348 <entry>No</entry>
6349 <entry>I want my data to be encrypted, and I accept the overhead. I trust
6350 that the network will make sure I always connect to the server I want.
6351 </entry>
6352 </row>
6354 <row>
6355 <entry><literal>verify-ca</></entry>
6356 <entry>Yes</entry>
6357 <entry><literal>Depends on CA</>-policy</entry>
6358 <entry>I want my data encrypted, and I accept the overhead. I want to be
6359 sure that I connect to a server that I trust.
6360 </entry>
6361 </row>
6363 <row>
6364 <entry><literal>verify-full</></entry>
6365 <entry>Yes</entry>
6366 <entry>Yes</entry>
6367 <entry>I want my data encrypted, and I accept the overhead. I want to be
6368 sure that I connect to a server I trust, and that it's the one I
6369 specify.
6370 </entry>
6371 </row>
6373 </tbody>
6374 </tgroup>
6375 </table>
6377 <para>
6378 The difference between <literal>verify-ca</> and <literal>verify-full</>
6379 depends on the policy of the root <acronym>CA</>. If a public
6380 <acronym>CA</> is used, <literal>verify-ca</> allows connections to a server
6381 that <emphasis>somebody else</> may have registered with the <acronym>CA</>
6382 to succeed. In this case, <literal>verify-full</> should always be used. If
6383 a local <acronym>CA</> is used, or even a self-signed certificate, using
6384 <literal>verify-ca</> often provides enough protection.
6385 </para>
6387 <para>
6388 The default value for <literal>sslmode</> is <literal>prefer</>. As is shown
6389 in the table, this makes no sense from a security point of view, and it only
6390 promises performance overhead if possible. It is only provided as the default
6391 for backwards compatiblity, and not recommended in secure deployments.
6392 </para>
6394 </sect2>
6396 <sect2 id="libpq-ssl-fileusage">
6397 <title>SSL File Usage</title>
6398 <table id="libpq-ssl-file-usage">
6399 <title>Libpq/Client SSL File Usage</title>
6400 <tgroup cols="3">
6401 <thead>
6402 <row>
6403 <entry>File</entry>
6404 <entry>Contents</entry>
6405 <entry>Effect</entry>
6406 </row>
6407 </thead>
6409 <tbody>
6411 <row>
6412 <entry><filename>~/.postgresql/postgresql.crt</></entry>
6413 <entry>client certificate</entry>
6414 <entry>requested by server</entry>
6415 </row>
6417 <row>
6418 <entry><filename>~/.postgresql/postgresql.key</></entry>
6419 <entry>client private key</entry>
6420 <entry>proves client certificate sent by owner; does not indicate
6421 certificate owner is trustworthy</entry>
6422 </row>
6424 <row>
6425 <entry><filename>~/.postgresql/root.crt</></entry>
6426 <entry>trusted certificate authorities</entry>
6427 <entry>checks server certificate is signed by a trusted certificate
6428 authority</entry>
6429 </row>
6431 <row>
6432 <entry><filename>~/.postgresql/root.crl</></entry>
6433 <entry>certificates revoked by certificate authorities</entry>
6434 <entry>server certificate must not be on this list</entry>
6435 </row>
6437 </tbody>
6438 </tgroup>
6439 </table>
6440 </sect2>
6442 <sect2 id="libpq-ssl-initialize">
6443 <title>SSL library initialization</title>
6445 <para>
6446 If your application initializes <literal>libssl</> and/or
6447 <literal>libcrypto</> libraries and <application>libpq</application>
6448 is built with <acronym>SSL</> support, you should call
6449 <function>PQinitOpenSSL</> to tell <application>libpq</application>
6450 that the <literal>libssl</> and/or <literal>libcrypto</> libraries
6451 have been initialized by your application, so that
6452 <application>libpq</application> will not also initialize those libraries.
6453 <!-- If this URL changes replace it with a URL to www.archive.org. -->
6454 See <ulink
6455 url="http://h71000.www7.hp.com/doc/83final/BA554_90007/ch04.html"></ulink>
6456 for details on the SSL API.
6457 </para>
6459 <para>
6460 <variablelist>
6461 <varlistentry>
6462 <term>
6463 <function>PQinitOpenSSL</function>
6464 <indexterm>
6465 <primary>PQinitOpenSSL</primary>
6466 </indexterm>
6467 </term>
6469 <listitem>
6470 <para>
6471 Allows applications to select which security libraries to initialize.
6472 <synopsis>
6473 void PQinitOpenSSL(int do_ssl, init do_crypto);
6474 </synopsis>
6475 </para>
6477 <para>
6478 When <parameter>do_ssl</> is non-zero, <application>libpq</application>
6479 will initialize the <application>OpenSSL</> library before first
6480 opening a database connection. When <parameter>do_crypto</> is
6481 non-zero, the <literal>libcrypto</> library will be initialized. By
6482 default (if <function>PQinitOpenSSL</> is not called), both libraries
6483 are initialized. When SSL support is not compiled in, this function is
6484 present but does nothing.
6485 </para>
6487 <para>
6488 If your application uses and initializes either <application>OpenSSL</>
6489 or its underlying <literal>libcrypto</> library, you <emphasis>must</>
6490 call this function with zeroes for the appropriate parameter(s)
6491 before first opening a database connection. Also be sure that you
6492 have done that initialization before opening a database connection.
6493 </para>
6494 </listitem>
6495 </varlistentry>
6497 <varlistentry>
6498 <term>
6499 <function>PQinitSSL</function>
6500 <indexterm>
6501 <primary>PQinitSSL</primary>
6502 </indexterm>
6503 </term>
6505 <listitem>
6506 <para>
6507 Allows applications to select which security libraries to initialize.
6508 <synopsis>
6509 void PQinitSSL(int do_ssl);
6510 </synopsis>
6511 </para>
6513 <para>
6514 This function is equivalent to
6515 <literal>PQinitOpenSSL(do_ssl, do_ssl)</>.
6516 It is sufficient for applications that initialize both or neither
6517 of <application>OpenSSL</> and <literal>libcrypto</>.
6518 </para>
6520 <para>
6521 <function>PQinitSSL</> has been present since
6522 <productname>PostgreSQL</> 8.0, while <function>PQinitOpenSSL</>
6523 was added in <productname>PostgreSQL</> 8.4, so <function>PQinitSSL</>
6524 might be preferable for applications that need to work with older
6525 versions of <application>libpq</application>.
6526 </para>
6527 </listitem>
6528 </varlistentry>
6529 </variablelist>
6530 </para>
6531 </sect2>
6533 </sect1>
6536 <sect1 id="libpq-threading">
6537 <title>Behavior in Threaded Programs</title>
6539 <indexterm zone="libpq-threading">
6540 <primary>threads</primary>
6541 <secondary>with libpq</secondary>
6542 </indexterm>
6544 <para>
6545 <application>libpq</application> is reentrant and thread-safe if the
6546 <filename>configure</filename> command-line option
6547 <literal>--enable-thread-safety</> was used when the
6548 <productname>PostgreSQL</productname> distribution was built. In
6549 addition, you might need to use additional compiler command-line
6550 options when you compile your application code. Refer to your
6551 system's documentation for information about how to build
6552 thread-enabled applications, or look in
6553 <filename>src/Makefile.global</filename> for <literal>PTHREAD_CFLAGS</>
6554 and <literal>PTHREAD_LIBS</>. This function allows the querying of
6555 <application>libpq</application>'s thread-safe status:
6556 </para>
6558 <variablelist>
6559 <varlistentry>
6560 <term>
6561 <function>PQisthreadsafe</function>
6562 <indexterm>
6563 <primary>PQisthreadsafe</primary>
6564 </indexterm>
6565 </term>
6567 <listitem>
6568 <para>
6569 Returns the thread safety status of the
6570 <application>libpq</application> library.
6571 <synopsis>
6572 int PQisthreadsafe();
6573 </synopsis>
6574 </para>
6576 <para>
6577 Returns 1 if the <application>libpq</application> is thread-safe
6578 and 0 if it is not.
6579 </para>
6580 </listitem>
6581 </varlistentry>
6582 </variablelist>
6584 <para>
6585 One thread restriction is that no two threads attempt to manipulate
6586 the same <structname>PGconn</> object at the same time. In particular,
6587 you cannot issue concurrent commands from different threads through
6588 the same connection object. (If you need to run concurrent commands,
6589 use multiple connections.)
6590 </para>
6592 <para>
6593 <structname>PGresult</> objects are read-only after creation, and so
6594 can be passed around freely between threads.
6595 </para>
6597 <para>
6598 The deprecated functions <function>PQrequestCancel</function> and
6599 <function>PQoidStatus</function> are not thread-safe and should not be
6600 used in multithread programs. <function>PQrequestCancel</function>
6601 can be replaced by <function>PQcancel</function>.
6602 <function>PQoidStatus</function> can be replaced by
6603 <function>PQoidValue</function>.
6604 </para>
6606 <para>
6607 If you are using Kerberos inside your application (in addition to inside
6608 <application>libpq</application>), you will need to do locking around
6609 Kerberos calls because Kerberos functions are not thread-safe. See
6610 function <function>PQregisterThreadLock</> in the
6611 <application>libpq</application> source code for a way to do cooperative
6612 locking between <application>libpq</application> and your application.
6613 </para>
6615 <para>
6616 If you experience problems with threaded applications, run the program
6617 in <filename>src/tools/thread</> to see if your platform has
6618 thread-unsafe functions. This program is run by
6619 <filename>configure</filename>, but for binary distributions your
6620 library might not match the library used to build the binaries.
6621 </para>
6622 </sect1>
6625 <sect1 id="libpq-build">
6626 <title>Building <application>libpq</application> Programs</title>
6628 <indexterm zone="libpq-build">
6629 <primary>compiling</primary>
6630 <secondary>libpq applications</secondary>
6631 </indexterm>
6633 <para>
6634 To build (i.e., compile and link) a program using
6635 <application>libpq</application> you need to do all of the following
6636 things:
6638 <itemizedlist>
6639 <listitem>
6640 <para>
6641 Include the <filename>libpq-fe.h</filename> header file:
6642 <programlisting>
6643 #include &lt;libpq-fe.h&gt;
6644 </programlisting>
6645 If you failed to do that then you will normally get error messages
6646 from your compiler similar to:
6647 <screen>
6648 foo.c: In function `main':
6649 foo.c:34: `PGconn' undeclared (first use in this function)
6650 foo.c:35: `PGresult' undeclared (first use in this function)
6651 foo.c:54: `CONNECTION_BAD' undeclared (first use in this function)
6652 foo.c:68: `PGRES_COMMAND_OK' undeclared (first use in this function)
6653 foo.c:95: `PGRES_TUPLES_OK' undeclared (first use in this function)
6654 </screen>
6655 </para>
6656 </listitem>
6658 <listitem>
6659 <para>
6660 Point your compiler to the directory where the <productname>PostgreSQL</> header
6661 files were installed, by supplying the
6662 <literal>-I<replaceable>directory</replaceable></literal> option
6663 to your compiler. (In some cases the compiler will look into
6664 the directory in question by default, so you can omit this
6665 option.) For instance, your compile command line could look
6666 like:
6667 <programlisting>
6668 cc -c -I/usr/local/pgsql/include testprog.c
6669 </programlisting>
6670 If you are using makefiles then add the option to the
6671 <varname>CPPFLAGS</varname> variable:
6672 <programlisting>
6673 CPPFLAGS += -I/usr/local/pgsql/include
6674 </programlisting>
6675 </para>
6677 <para>
6678 If there is any chance that your program might be compiled by
6679 other users then you should not hardcode the directory location
6680 like that. Instead, you can run the utility
6681 <command>pg_config</command><indexterm><primary>pg_config</><secondary
6682 sortas="libpq">with libpq</></> to find out where the header
6683 files are on the local system:
6684 <screen>
6685 <prompt>$</prompt> pg_config --includedir
6686 <computeroutput>/usr/local/include</computeroutput>
6687 </screen>
6688 </para>
6690 <para>
6691 Failure to specify the correct option to the compiler will
6692 result in an error message such as:
6693 <screen>
6694 testlibpq.c:8:22: libpq-fe.h: No such file or directory
6695 </screen>
6696 </para>
6697 </listitem>
6699 <listitem>
6700 <para>
6701 When linking the final program, specify the option
6702 <literal>-lpq</literal> so that the <application>libpq</application>
6703 library gets pulled in, as well as the option
6704 <literal>-L<replaceable>directory</replaceable></literal> to point
6705 the compiler to the directory where the
6706 <application>libpq</application> library resides. (Again, the
6707 compiler will search some directories by default.) For maximum
6708 portability, put the <option>-L</option> option before the
6709 <option>-lpq</option> option. For example:
6710 <programlisting>
6711 cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq
6712 </programlisting>
6713 </para>
6715 <para>
6716 You can find out the library directory using
6717 <command>pg_config</command> as well:
6718 <screen>
6719 <prompt>$</prompt> pg_config --libdir
6720 <computeroutput>/usr/local/pgsql/lib</computeroutput>
6721 </screen>
6722 </para>
6724 <para>
6725 Error messages that point to problems in this area could look like
6726 the following:
6727 <screen>
6728 testlibpq.o: In function `main':
6729 testlibpq.o(.text+0x60): undefined reference to `PQsetdbLogin'
6730 testlibpq.o(.text+0x71): undefined reference to `PQstatus'
6731 testlibpq.o(.text+0xa4): undefined reference to `PQerrorMessage'
6732 </screen>
6733 This means you forgot <option>-lpq</option>.
6734 <screen>
6735 /usr/bin/ld: cannot find -lpq
6736 </screen>
6737 This means you forgot the <option>-L</option> option or did not
6738 specify the right directory.
6739 </para>
6740 </listitem>
6741 </itemizedlist>
6742 </para>
6744 </sect1>
6747 <sect1 id="libpq-example">
6748 <title>Example Programs</title>
6750 <para>
6751 These examples and others can be found in the
6752 directory <filename>src/test/examples</filename> in the source code
6753 distribution.
6754 </para>
6756 <example id="libpq-example-1">
6757 <title><application>libpq</application> Example Program 1</title>
6759 <programlisting>
6760 <![CDATA[
6762 * testlibpq.c
6764 * Test the C version of libpq, the PostgreSQL frontend library.
6766 #include <stdio.h>
6767 #include <stdlib.h>
6768 #include "libpq-fe.h"
6770 static void
6771 exit_nicely(PGconn *conn)
6773 PQfinish(conn);
6774 exit(1);
6778 main(int argc, char **argv)
6780 const char *conninfo;
6781 PGconn *conn;
6782 PGresult *res;
6783 int nFields;
6784 int i,
6788 * If the user supplies a parameter on the command line, use it as the
6789 * conninfo string; otherwise default to setting dbname=postgres and using
6790 * environment variables or defaults for all other connection parameters.
6792 if (argc > 1)
6793 conninfo = argv[1];
6794 else
6795 conninfo = "dbname = postgres";
6797 /* Make a connection to the database */
6798 conn = PQconnectdb(conninfo);
6800 /* Check to see that the backend connection was successfully made */
6801 if (PQstatus(conn) != CONNECTION_OK)
6803 fprintf(stderr, "Connection to database failed: %s",
6804 PQerrorMessage(conn));
6805 exit_nicely(conn);
6809 * Our test case here involves using a cursor, for which we must be inside
6810 * a transaction block. We could do the whole thing with a single
6811 * PQexec() of "select * from pg_database", but that's too trivial to make
6812 * a good example.
6815 /* Start a transaction block */
6816 res = PQexec(conn, "BEGIN");
6817 if (PQresultStatus(res) != PGRES_COMMAND_OK)
6819 fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn));
6820 PQclear(res);
6821 exit_nicely(conn);
6825 * Should PQclear PGresult whenever it is no longer needed to avoid memory
6826 * leaks
6828 PQclear(res);
6831 * Fetch rows from pg_database, the system catalog of databases
6833 res = PQexec(conn, "DECLARE myportal CURSOR FOR select * from pg_database");
6834 if (PQresultStatus(res) != PGRES_COMMAND_OK)
6836 fprintf(stderr, "DECLARE CURSOR failed: %s", PQerrorMessage(conn));
6837 PQclear(res);
6838 exit_nicely(conn);
6840 PQclear(res);
6842 res = PQexec(conn, "FETCH ALL in myportal");
6843 if (PQresultStatus(res) != PGRES_TUPLES_OK)
6845 fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(conn));
6846 PQclear(res);
6847 exit_nicely(conn);
6850 /* first, print out the attribute names */
6851 nFields = PQnfields(res);
6852 for (i = 0; i < nFields; i++)
6853 printf("%-15s", PQfname(res, i));
6854 printf("\n\n");
6856 /* next, print out the rows */
6857 for (i = 0; i < PQntuples(res); i++)
6859 for (j = 0; j < nFields; j++)
6860 printf("%-15s", PQgetvalue(res, i, j));
6861 printf("\n");
6864 PQclear(res);
6866 /* close the portal ... we don't bother to check for errors ... */
6867 res = PQexec(conn, "CLOSE myportal");
6868 PQclear(res);
6870 /* end the transaction */
6871 res = PQexec(conn, "END");
6872 PQclear(res);
6874 /* close the connection to the database and cleanup */
6875 PQfinish(conn);
6877 return 0;
6880 </programlisting>
6881 </example>
6883 <example id="libpq-example-2">
6884 <title><application>libpq</application> Example Program 2</title>
6886 <programlisting>
6887 <![CDATA[
6889 * testlibpq2.c
6890 * Test of the asynchronous notification interface
6892 * Start this program, then from psql in another window do
6893 * NOTIFY TBL2;
6894 * Repeat four times to get this program to exit.
6896 * Or, if you want to get fancy, try this:
6897 * populate a database with the following commands
6898 * (provided in src/test/examples/testlibpq2.sql):
6900 * CREATE TABLE TBL1 (i int4);
6902 * CREATE TABLE TBL2 (i int4);
6904 * CREATE RULE r1 AS ON INSERT TO TBL1 DO
6905 * (INSERT INTO TBL2 VALUES (new.i); NOTIFY TBL2);
6907 * and do this four times:
6909 * INSERT INTO TBL1 VALUES (10);
6911 #include <stdio.h>
6912 #include <stdlib.h>
6913 #include <string.h>
6914 #include <errno.h>
6915 #include <sys/time.h>
6916 #include "libpq-fe.h"
6918 static void
6919 exit_nicely(PGconn *conn)
6921 PQfinish(conn);
6922 exit(1);
6926 main(int argc, char **argv)
6928 const char *conninfo;
6929 PGconn *conn;
6930 PGresult *res;
6931 PGnotify *notify;
6932 int nnotifies;
6935 * If the user supplies a parameter on the command line, use it as the
6936 * conninfo string; otherwise default to setting dbname=postgres and using
6937 * environment variables or defaults for all other connection parameters.
6939 if (argc > 1)
6940 conninfo = argv[1];
6941 else
6942 conninfo = "dbname = postgres";
6944 /* Make a connection to the database */
6945 conn = PQconnectdb(conninfo);
6947 /* Check to see that the backend connection was successfully made */
6948 if (PQstatus(conn) != CONNECTION_OK)
6950 fprintf(stderr, "Connection to database failed: %s",
6951 PQerrorMessage(conn));
6952 exit_nicely(conn);
6956 * Issue LISTEN command to enable notifications from the rule's NOTIFY.
6958 res = PQexec(conn, "LISTEN TBL2");
6959 if (PQresultStatus(res) != PGRES_COMMAND_OK)
6961 fprintf(stderr, "LISTEN command failed: %s", PQerrorMessage(conn));
6962 PQclear(res);
6963 exit_nicely(conn);
6967 * should PQclear PGresult whenever it is no longer needed to avoid memory
6968 * leaks
6970 PQclear(res);
6972 /* Quit after four notifies are received. */
6973 nnotifies = 0;
6974 while (nnotifies < 4)
6977 * Sleep until something happens on the connection. We use select(2)
6978 * to wait for input, but you could also use poll() or similar
6979 * facilities.
6981 int sock;
6982 fd_set input_mask;
6984 sock = PQsocket(conn);
6986 if (sock < 0)
6987 break; /* shouldn't happen */
6989 FD_ZERO(&input_mask);
6990 FD_SET(sock, &input_mask);
6992 if (select(sock + 1, &input_mask, NULL, NULL, NULL) < 0)
6994 fprintf(stderr, "select() failed: %s\n", strerror(errno));
6995 exit_nicely(conn);
6998 /* Now check for input */
6999 PQconsumeInput(conn);
7000 while ((notify = PQnotifies(conn)) != NULL)
7002 fprintf(stderr,
7003 "ASYNC NOTIFY of '%s' received from backend pid %d\n",
7004 notify->relname, notify->be_pid);
7005 PQfreemem(notify);
7006 nnotifies++;
7010 fprintf(stderr, "Done.\n");
7012 /* close the connection to the database and cleanup */
7013 PQfinish(conn);
7015 return 0;
7018 </programlisting>
7019 </example>
7021 <example id="libpq-example-3">
7022 <title><application>libpq</application> Example Program 3</>
7024 <programlisting>
7025 <![CDATA[
7027 * testlibpq3.c
7028 * Test out-of-line parameters and binary I/O.
7030 * Before running this, populate a database with the following commands
7031 * (provided in src/test/examples/testlibpq3.sql):
7033 * CREATE TABLE test1 (i int4, t text, b bytea);
7035 * INSERT INTO test1 values (1, 'joe''s place', '\\000\\001\\002\\003\\004');
7036 * INSERT INTO test1 values (2, 'ho there', '\\004\\003\\002\\001\\000');
7038 * The expected output is:
7040 * tuple 0: got
7041 * i = (4 bytes) 1
7042 * t = (11 bytes) 'joe's place'
7043 * b = (5 bytes) \000\001\002\003\004
7045 * tuple 0: got
7046 * i = (4 bytes) 2
7047 * t = (8 bytes) 'ho there'
7048 * b = (5 bytes) \004\003\002\001\000
7050 #include <stdio.h>
7051 #include <stdlib.h>
7052 #include <string.h>
7053 #include <sys/types.h>
7054 #include "libpq-fe.h"
7056 /* for ntohl/htonl */
7057 #include <netinet/in.h>
7058 #include <arpa/inet.h>
7061 static void
7062 exit_nicely(PGconn *conn)
7064 PQfinish(conn);
7065 exit(1);
7069 * This function prints a query result that is a binary-format fetch from
7070 * a table defined as in the comment above. We split it out because the
7071 * main() function uses it twice.
7073 static void
7074 show_binary_results(PGresult *res)
7076 int i,
7078 int i_fnum,
7079 t_fnum,
7080 b_fnum;
7082 /* Use PQfnumber to avoid assumptions about field order in result */
7083 i_fnum = PQfnumber(res, "i");
7084 t_fnum = PQfnumber(res, "t");
7085 b_fnum = PQfnumber(res, "b");
7087 for (i = 0; i < PQntuples(res); i++)
7089 char *iptr;
7090 char *tptr;
7091 char *bptr;
7092 int blen;
7093 int ival;
7095 /* Get the field values (we ignore possibility they are null!) */
7096 iptr = PQgetvalue(res, i, i_fnum);
7097 tptr = PQgetvalue(res, i, t_fnum);
7098 bptr = PQgetvalue(res, i, b_fnum);
7101 * The binary representation of INT4 is in network byte order, which
7102 * we'd better coerce to the local byte order.
7104 ival = ntohl(*((uint32_t *) iptr));
7107 * The binary representation of TEXT is, well, text, and since libpq
7108 * was nice enough to append a zero byte to it, it'll work just fine
7109 * as a C string.
7111 * The binary representation of BYTEA is a bunch of bytes, which could
7112 * include embedded nulls so we have to pay attention to field length.
7114 blen = PQgetlength(res, i, b_fnum);
7116 printf("tuple %d: got\n", i);
7117 printf(" i = (%d bytes) %d\n",
7118 PQgetlength(res, i, i_fnum), ival);
7119 printf(" t = (%d bytes) '%s'\n",
7120 PQgetlength(res, i, t_fnum), tptr);
7121 printf(" b = (%d bytes) ", blen);
7122 for (j = 0; j < blen; j++)
7123 printf("\\%03o", bptr[j]);
7124 printf("\n\n");
7129 main(int argc, char **argv)
7131 const char *conninfo;
7132 PGconn *conn;
7133 PGresult *res;
7134 const char *paramValues[1];
7135 int paramLengths[1];
7136 int paramFormats[1];
7137 uint32_t binaryIntVal;
7140 * If the user supplies a parameter on the command line, use it as the
7141 * conninfo string; otherwise default to setting dbname=postgres and using
7142 * environment variables or defaults for all other connection parameters.
7144 if (argc > 1)
7145 conninfo = argv[1];
7146 else
7147 conninfo = "dbname = postgres";
7149 /* Make a connection to the database */
7150 conn = PQconnectdb(conninfo);
7152 /* Check to see that the backend connection was successfully made */
7153 if (PQstatus(conn) != CONNECTION_OK)
7155 fprintf(stderr, "Connection to database failed: %s",
7156 PQerrorMessage(conn));
7157 exit_nicely(conn);
7161 * The point of this program is to illustrate use of PQexecParams() with
7162 * out-of-line parameters, as well as binary transmission of data.
7164 * This first example transmits the parameters as text, but receives the
7165 * results in binary format. By using out-of-line parameters we can
7166 * avoid a lot of tedious mucking about with quoting and escaping, even
7167 * though the data is text. Notice how we don't have to do anything
7168 * special with the quote mark in the parameter value.
7171 /* Here is our out-of-line parameter value */
7172 paramValues[0] = "joe's place";
7174 res = PQexecParams(conn,
7175 "SELECT * FROM test1 WHERE t = $1",
7176 1, /* one param */
7177 NULL, /* let the backend deduce param type */
7178 paramValues,
7179 NULL, /* don't need param lengths since text */
7180 NULL, /* default to all text params */
7181 1); /* ask for binary results */
7183 if (PQresultStatus(res) != PGRES_TUPLES_OK)
7185 fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
7186 PQclear(res);
7187 exit_nicely(conn);
7190 show_binary_results(res);
7192 PQclear(res);
7195 * In this second example we transmit an integer parameter in binary
7196 * form, and again retrieve the results in binary form.
7198 * Although we tell PQexecParams we are letting the backend deduce
7199 * parameter type, we really force the decision by casting the parameter
7200 * symbol in the query text. This is a good safety measure when sending
7201 * binary parameters.
7204 /* Convert integer value "2" to network byte order */
7205 binaryIntVal = htonl((uint32_t) 2);
7207 /* Set up parameter arrays for PQexecParams */
7208 paramValues[0] = (char *) &binaryIntVal;
7209 paramLengths[0] = sizeof(binaryIntVal);
7210 paramFormats[0] = 1; /* binary */
7212 res = PQexecParams(conn,
7213 "SELECT * FROM test1 WHERE i = $1::int4",
7214 1, /* one param */
7215 NULL, /* let the backend deduce param type */
7216 paramValues,
7217 paramLengths,
7218 paramFormats,
7219 1); /* ask for binary results */
7221 if (PQresultStatus(res) != PGRES_TUPLES_OK)
7223 fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
7224 PQclear(res);
7225 exit_nicely(conn);
7228 show_binary_results(res);
7230 PQclear(res);
7232 /* close the connection to the database and cleanup */
7233 PQfinish(conn);
7235 return 0;
7238 </programlisting>
7239 </example>
7241 </sect1>
7242 </chapter>