]> granicus.if.org Git - postgresql/blob - doc/src/sgml/libpq.sgml
Remove support for Kerberos V4. It seems no one is using this, it has
[postgresql] / doc / src / sgml / libpq.sgml
1 <!--
2 $PostgreSQL: pgsql/doc/src/sgml/libpq.sgml,v 1.188 2005/06/27 02:04:24 neilc Exp $
3 -->
4
5  <chapter id="libpq">
6   <title><application>libpq</application> - C Library</title>
7
8   <indexterm zone="libpq">
9    <primary>libpq</primary>
10   </indexterm>
11
12   <indexterm zone="libpq">
13    <primary>C</primary>
14   </indexterm>
15
16   <para>
17    <application>libpq</application> is the <acronym>C</acronym>
18    application programmer's interface to <productname>PostgreSQL</>.
19    <application>libpq</> is a set of library functions that allow
20    client programs to pass queries to the <productname>PostgreSQL</>
21    backend server and to receive the results of these queries.
22   </para>
23
24   <para>
25    <application>libpq</> is also the underlying engine for several
26    other <productname>PostgreSQL</> application interfaces, including
27    those written for C++, Perl, Python, Tcl and <application>ECPG</>.
28    So some aspects of <application>libpq</>'s behavior will be
29    important to you if you use one of those packages.  In particular,
30    <xref linkend="libpq-envars">,
31    <xref linkend="libpq-pgpass"> and
32    <xref linkend="libpq-ssl">
33    describe behavior that is visible to the user of any application
34    that uses <application>libpq</>.
35   </para>
36
37   <para>
38    Some short programs are included at the end of this chapter (<xref linkend="libpq-example">) to show how
39    to write programs that use <application>libpq</application>.  There are also several
40    complete examples of <application>libpq</application> applications in the
41    directory <filename>src/test/examples</filename> in the source code distribution.
42   </para>
43
44   <para>
45    Client programs that use <application>libpq</application> must
46    include the header file
47    <filename>libpq-fe.h</filename><indexterm><primary>libpq-fe.h</></>
48    and must link with the <application>libpq</application> library.
49   </para>
50
51  <sect1 id="libpq-connect">
52   <title>Database Connection Control Functions</title>
53
54   <para>
55    The following functions deal with making a connection to a
56    <productname>PostgreSQL</productname> backend server.  An
57    application program can have several backend connections open at
58    one time.  (One reason to do that is to access more than one
59    database.)  Each connection is represented by a
60    <structname>PGconn</><indexterm><primary>PGconn</></> object, which
61    is obtained from the function <function>PQconnectdb</> or
62    <function>PQsetdbLogin</>.  Note that these functions will always
63    return a non-null object pointer, unless perhaps there is too
64    little memory even to allocate the <structname>PGconn</> object.
65    The <function>PQstatus</> function should be called to check
66    whether a connection was successfully made before queries are sent
67    via the connection object.
68
69    <variablelist>
70     <varlistentry>
71      <term><function>PQconnectdb</function><indexterm><primary>PQconnectdb</></></term>
72      <listitem>
73       <para>
74        Makes a new connection to the database server.
75 <synopsis>
76 PGconn *PQconnectdb(const char *conninfo);
77 </synopsis>
78 </para>
79
80 <para>
81    This function opens a new database connection using the parameters taken
82    from the string <literal>conninfo</literal>.  Unlike <function>PQsetdbLogin</> below,
83    the parameter set can be extended without changing the function signature,
84    so use of this function (or its nonblocking analogues <function>PQconnectStart</>
85    and <function>PQconnectPoll</function>) is preferred for new application programming.
86    </para>
87
88    <para>
89    The passed string
90    can be empty to use all default parameters, or it can contain one or more
91    parameter settings separated by whitespace.
92    Each parameter setting is in the form <literal>keyword = value</literal>.
93    Spaces around the equal sign are optional.
94    To write an empty value or a value containing
95    spaces, surround it with single quotes, e.g.,
96    <literal>keyword = 'a value'</literal>.
97    Single quotes and backslashes within the value must be escaped with a
98    backslash, i.e., <literal>\'</literal> and <literal>\\</literal>.
99    </para>
100
101    <para>
102    The currently recognized parameter key words are:
103
104    <variablelist>
105     <varlistentry>
106      <term><literal>host</literal></term>
107      <listitem>
108      <para>
109       Name of host to connect to.<indexterm><primary>host name</></>
110       If this begins with a slash, it specifies Unix-domain
111       communication rather than TCP/IP communication; the value is the
112       name of the directory in which the socket file is stored.  The
113       default behavior when <literal>host</literal> is not specified
114       is to connect to a Unix-domain
115       socket<indexterm><primary>Unix domain socket</></> in
116       <filename>/tmp</filename> (or whatever socket directory was specified
117       when <productname>PostgreSQL</> was built). On machines without
118       Unix-domain sockets, the default is to connect to <literal>localhost</>.
119      </para>
120      </listitem>
121     </varlistentry>
122
123     <varlistentry>
124      <term><literal>hostaddr</literal></term>
125      <listitem>
126      <para>
127       Numeric IP address of host to connect to.  This should be in the
128       standard IPv4 address format, e.g., <literal>172.28.40.9</>.  If
129       your machine supports IPv6, you can also use those addresses.
130       TCP/IP communication is
131       always used when a nonempty string is specified for this parameter.
132      </para>
133      <para>
134       Using <literal>hostaddr</> instead of <literal>host</> allows the
135       application to avoid a host name look-up, which may be important in
136       applications with time constraints. However, Kerberos authentication
137       requires the host name. The following therefore applies: If
138       <literal>host</> is specified without <literal>hostaddr</>, a host name
139       lookup occurs. If <literal>hostaddr</> is specified without
140       <literal>host</>, the value for <literal>hostaddr</> gives the remote
141       address. When Kerberos is used, a reverse name query occurs to obtain
142       the host name for Kerberos. If both
143       <literal>host</> and <literal>hostaddr</> are specified, the value for
144       <literal>hostaddr</> gives the remote address; the value for
145       <literal>host</> is ignored, unless Kerberos is used, in which case that
146       value is used for Kerberos authentication. (Note that authentication is
147       likely to fail if <application>libpq</application> is passed a host name
148       that is not the name of the machine at <literal>hostaddr</>.)  Also,
149       <literal>host</> rather than <literal>hostaddr</> is used to identify
150       the connection in <filename>~/.pgpass</> (see
151       <xref linkend="libpq-pgpass">).
152      </para>
153      <para>
154       Without either a host name or host address,
155       <application>libpq</application> will connect using a
156       local Unix-domain socket; or on machines without Unix-domain
157       sockets, it will attempt to connect to <literal>localhost</>.
158      </para>
159      </listitem>
160     </varlistentry>
161
162     <varlistentry>
163      <term><literal>port</literal></term>
164      <listitem>
165      <para>
166       Port number to connect to at the server host, or socket file
167       name extension for Unix-domain
168       connections.<indexterm><primary>port</></>
169      </para>
170      </listitem>
171     </varlistentry>
172
173     <varlistentry>
174      <term><literal>dbname</literal></term>
175      <listitem>
176      <para>
177       The database name.  Defaults to be the same as the user name.
178      </para>
179      </listitem>
180     </varlistentry>
181
182     <varlistentry>
183      <term><literal>user</literal></term> 
184      <listitem>
185      <para>
186       <productname>PostgreSQL</productname> user name to connect as.
187       Defaults to be the same as the operating system name of the user
188       running the application.
189      </para>
190      </listitem>
191     </varlistentry>
192
193     <varlistentry>
194      <term><literal>password</literal></term>
195      <listitem>
196      <para>
197       Password to be used if the server demands password authentication.
198      </para>
199      </listitem>
200     </varlistentry>
201
202     <varlistentry>
203      <term><literal>connect_timeout</literal></term>
204      <listitem>
205      <para>
206       Maximum wait for connection, in seconds (write as a decimal integer
207       string). Zero or not specified means wait indefinitely.  It is not
208       recommended to use a timeout of less than 2 seconds.
209      </para>
210      </listitem>
211     </varlistentry>
212
213     <varlistentry>
214      <term><literal>options</literal></term>
215      <listitem>
216       <para>
217        Command-line options to be sent to the server.
218       </para>
219      </listitem>
220     </varlistentry>
221
222     <varlistentry>
223      <term><literal>tty</literal></term>
224      <listitem>
225      <para>
226       Ignored (formerly, this specified where to send server debug output).
227      </para>
228      </listitem>
229     </varlistentry>
230
231     <varlistentry>
232      <term><literal>sslmode</literal></term>
233      <listitem>
234       <para>
235        This option determines whether or with what priority an
236        <acronym>SSL</> connection will be negotiated with the
237        server. There are four modes: <literal>disable</> will attempt
238        only an unencrypted <acronym>SSL</> connection;
239        <literal>allow</> will negotiate, trying first a
240        non-<acronym>SSL</> connection, then if that fails, trying an
241        <acronym>SSL</> connection; <literal>prefer</> (the default)
242        will negotiate, trying first an <acronym>SSL</> connection,
243        then if that fails, trying a regular non-<acronym>SSL</>
244        connection; <literal>require</> will try only an
245        <acronym>SSL</> connection.
246       </para>
247
248       <para>
249        If <productname>PostgreSQL</> is compiled without SSL support,
250        using option <literal>require</> will cause an error, while
251        options <literal>allow</> and <literal>prefer</> will be
252        accepted but <application>libpq</> will not in fact attempt
253        an <acronym>SSL</>
254        connection.<indexterm><primary>SSL</><secondary
255        sortas="libpq">with libpq</></indexterm>
256       </para>
257      </listitem>
258     </varlistentry>
259
260     <varlistentry>
261      <term><literal>requiressl</literal></term>
262      <listitem>
263       <para>
264        This option is deprecated in favor of the <literal>sslmode</>
265        setting.
266       </para>
267
268       <para>
269        If set to 1, an <acronym>SSL</acronym> connection to the server
270        is required (this is equivalent to <literal>sslmode</>
271        <literal>require</>).  <application>libpq</> will then refuse
272        to connect if the server does not accept an
273        <acronym>SSL</acronym> connection.  If set to 0 (default),
274        <application>libpq</> will negotiate the connection type with
275        the server (equivalent to <literal>sslmode</>
276        <literal>prefer</>).  This option is only available if
277        <productname>PostgreSQL</> is compiled with SSL support.
278       </para>
279      </listitem>
280     </varlistentry>
281
282     <varlistentry>
283      <term><literal>krbsrvname</literal></term>
284      <listitem>
285       <para>
286        Kerberos service name to use when authenticating with Kerberos 5.
287        This must match the service name specified in the server
288        configuration for Kerberos authentication to succeed. (See also
289        <xref linkend="kerberos-auth">.)
290       </para>
291      </listitem>
292     </varlistentry>
293
294     <varlistentry>
295      <term><literal>service</literal></term>
296      <listitem>
297      <para>
298       Service name to use for additional parameters.  It specifies a service
299       name in <filename>pg_service.conf</filename> that holds additional connection parameters.
300       This allows applications to specify only a service name so connection parameters 
301       can be centrally maintained.  See 
302       <filename>share/pg_service.conf.sample</> in the installation
303       directory for information on how to set up the file.
304      </para>
305      </listitem>
306     </varlistentry>
307    </variablelist>
308
309    If  any  parameter is unspecified, then the corresponding
310    environment variable (see <xref linkend="libpq-envars">)
311    is checked. If the  environment  variable is not set either,
312    then the indicated built-in defaults are used.
313    </para>
314   </listitem>
315  </varlistentry>
316
317  <varlistentry>
318   <term><function>PQsetdbLogin</function><indexterm><primary>PQsetdbLogin</></></term>
319   <listitem>
320    <para>
321        Makes a new connection to the database server.
322 <synopsis>
323 PGconn *PQsetdbLogin(const char *pghost,
324                      const char *pgport,
325                      const char *pgoptions,
326                      const char *pgtty,
327                      const char *dbName,
328                      const char *login,
329                      const char *pwd);
330 </synopsis>
331 </para>
332
333 <para>
334    This is the predecessor of <function>PQconnectdb</function> with a fixed
335    set of parameters.  It has the same functionality except that the
336    missing parameters will always take on default values.  Write <symbol>NULL</symbol> or an
337    empty string for any one of the fixed parameters that is to be defaulted.
338    </para>
339   </listitem>
340  </varlistentry>
341
342  <varlistentry>
343   <term><function>PQsetdb</function><indexterm><primary>PQsetdb</></></term>
344   <listitem>
345    <para>
346    Makes a new connection to the database server.
347 <synopsis>
348 PGconn *PQsetdb(char *pghost,
349                 char *pgport,
350                 char *pgoptions,
351                 char *pgtty,
352                 char *dbName);
353 </synopsis>
354 </para>
355
356 <para>
357    This is a macro that calls <function>PQsetdbLogin</function> with null pointers
358    for the <parameter>login</> and <parameter>pwd</> parameters.  It is provided
359    for backward compatibility with very old programs.
360    </para>
361   </listitem>
362  </varlistentry>
363
364  <varlistentry>
365   <term><function>PQconnectStart</function><indexterm><primary>PQconnectStart</></></term>
366   <term><function>PQconnectPoll</function><indexterm><primary>PQconnectPoll</></></term>
367   <listitem>
368   <para>
369    <indexterm><primary>nonblocking connection</primary></indexterm>
370    Make a connection to the database server in a nonblocking manner.
371 <synopsis>
372 PGconn *PQconnectStart(const char *conninfo);
373 </synopsis>
374 <synopsis>
375 PostgresPollingStatusType PQconnectPoll(PGconn *conn);
376 </synopsis>
377 </para>
378 <para>
379    These two functions are used to open a connection to a database server such
380    that your application's thread of execution is not blocked on remote I/O
381    whilst doing so.
382    The point of this approach is that the waits for I/O to complete can occur
383    in the application's main loop, rather than down inside
384    <function>PQconnectdb</>, and so the application can manage this
385    operation in parallel with other activities.
386   </para>
387   <para>
388    The database connection is made using the parameters taken from the string
389    <literal>conninfo</literal>, passed to <function>PQconnectStart</function>. This string is in
390    the same format as described above for <function>PQconnectdb</function>.
391   </para>
392   <para>
393    Neither <function>PQconnectStart</function> nor <function>PQconnectPoll</function> will block, so long as a number of
394    restrictions are met:
395    <itemizedlist>
396     <listitem>
397      <para>
398       The <literal>hostaddr</> and <literal>host</> parameters are used appropriately to ensure that
399       name and reverse name queries are not made. See the documentation of
400       these parameters under <function>PQconnectdb</function> above for details.
401      </para>
402     </listitem>
403
404     <listitem>
405      <para>
406       If you call <function>PQtrace</function>, ensure that the stream object
407       into which you trace will not block.
408      </para>
409     </listitem>
410
411     <listitem>
412      <para>
413       You ensure that the socket is in the appropriate state
414       before calling <function>PQconnectPoll</function>, as described below.
415      </para>
416     </listitem>
417    </itemizedlist>
418   </para>
419
420   <para>
421    To begin a nonblocking connection request, call <literal>conn = PQconnectStart("<replaceable>connection_info_string</>")</literal>.
422    If <varname>conn</varname> is null, then <application>libpq</> has been unable to allocate a new <structname>PGconn</>
423    structure. Otherwise, a valid <structname>PGconn</> pointer is returned (though not yet
424    representing a valid connection to the database). On return from
425    <function>PQconnectStart</function>, call <literal>status = PQstatus(conn)</literal>. If <varname>status</varname> equals
426    <symbol>CONNECTION_BAD</symbol>, <function>PQconnectStart</function> has failed.
427   </para>
428   <para>
429    If <function>PQconnectStart</> succeeds, the next stage is to poll
430    <application>libpq</> so that it may proceed with the connection sequence.
431    Use <function>PQsocket(conn)</function> to obtain the descriptor of the
432    socket underlying the database connection.
433    Loop thus: If <function>PQconnectPoll(conn)</function> last returned
434    <symbol>PGRES_POLLING_READING</symbol>, wait until the socket is ready to
435    read (as indicated by <function>select()</>, <function>poll()</>, or
436    similar system function).
437    Then call <function>PQconnectPoll(conn)</function> again.
438    Conversely, if <function>PQconnectPoll(conn)</function> last returned
439    <symbol>PGRES_POLLING_WRITING</symbol>, wait until the socket is ready
440    to write, then call <function>PQconnectPoll(conn)</function> again.
441    If you have yet to call
442    <function>PQconnectPoll</function>, i.e., just after the call to
443    <function>PQconnectStart</function>, behave as if it last returned
444    <symbol>PGRES_POLLING_WRITING</symbol>.  Continue this loop until
445    <function>PQconnectPoll(conn)</function> returns
446    <symbol>PGRES_POLLING_FAILED</symbol>, indicating the connection procedure
447    has failed, or <symbol>PGRES_POLLING_OK</symbol>, indicating the connection
448    has been successfully made.
449   </para>
450
451   <para>
452     At any time during connection, the status of the connection may be
453     checked by calling <function>PQstatus</>. If this gives <symbol>CONNECTION_BAD</>, then the
454     connection procedure has failed; if it gives <function>CONNECTION_OK</>, then the
455     connection is ready.  Both of these states are equally detectable
456     from the return value of <function>PQconnectPoll</>, described above. Other states may also occur
457     during (and only during) an asynchronous connection procedure. These
458     indicate the current stage of the connection procedure and may be useful
459     to provide feedback to the user for example. These statuses are:
460
461     <variablelist>
462      <varlistentry>
463       <term><symbol>CONNECTION_STARTED</symbol></term>
464       <listitem>
465        <para>
466         Waiting for connection to be made.
467        </para>
468       </listitem>
469      </varlistentry> 
470
471      <varlistentry>
472       <term><symbol>CONNECTION_MADE</symbol></term>
473       <listitem>
474        <para>
475         Connection OK; waiting to send.
476        </para>
477       </listitem>
478      </varlistentry>  
479
480      <varlistentry>
481       <term><symbol>CONNECTION_AWAITING_RESPONSE</symbol></term>
482       <listitem>
483        <para>
484         Waiting for a response from the server.
485        </para>
486       </listitem>
487      </varlistentry>
488
489      <varlistentry>
490       <term><symbol>CONNECTION_AUTH_OK</symbol></term>
491       <listitem>
492        <para>
493         Received authentication; waiting for backend start-up to finish.
494        </para>
495       </listitem>
496      </varlistentry>
497
498      <varlistentry>
499       <term><symbol>CONNECTION_SSL_STARTUP</symbol></term>
500       <listitem>
501        <para>
502         Negotiating SSL encryption.
503        </para>
504       </listitem>
505      </varlistentry>
506
507      <varlistentry>
508       <term><symbol>CONNECTION_SETENV</symbol></term>
509       <listitem>
510        <para>
511         Negotiating environment-driven parameter settings.
512        </para>
513       </listitem>
514      </varlistentry>
515     </variablelist>
516
517     Note that, although these constants will remain (in order to maintain
518     compatibility), an application should never rely upon these occurring in a
519     particular order, or at all, or on the status always being one of these
520     documented values. An application might do something like this:
521 <programlisting>
522 switch(PQstatus(conn))
523 {
524     case CONNECTION_STARTED:
525         feedback = "Connecting...";
526         break;
527
528     case CONNECTION_MADE:
529         feedback = "Connected to server...";
530         break;
531 .
532 .
533 .
534     default:
535         feedback = "Connecting...";
536 }
537 </programlisting>
538   </para>
539
540   <para>
541    The <literal>connect_timeout</literal> connection parameter is ignored
542    when using <function>PQconnectPoll</function>; it is the application's
543    responsibility to decide whether an excessive amount of time has elapsed.
544    Otherwise, <function>PQconnectStart</function> followed by a
545    <function>PQconnectPoll</function> loop is equivalent to
546    <function>PQconnectdb</function>.
547   </para>
548
549   <para>
550    Note that if <function>PQconnectStart</function> returns a non-null pointer, you must call
551    <function>PQfinish</function> when you are finished with it, in order to dispose of
552    the structure and any associated memory blocks. This must be done even if
553    the connection attempt fails or is abandoned.
554   </para>
555   </listitem>
556  </varlistentry>
557
558  <varlistentry>
559   <term><function>PQconndefaults</function><indexterm><primary>PQconndefaults</></></term>
560   <listitem>
561    <para>
562    Returns the default connection options.
563 <synopsis>
564 PQconninfoOption *PQconndefaults(void);
565
566 typedef struct
567 {
568     char   *keyword;   /* The keyword of the option */
569     char   *envvar;    /* Fallback environment variable name */
570     char   *compiled;  /* Fallback compiled in default value */
571     char   *val;       /* Option's current value, or NULL */
572     char   *label;     /* Label for field in connect dialog */
573     char   *dispchar;  /* Character to display for this field
574                           in a connect dialog. Values are:
575                           ""        Display entered value as is
576                           "*"       Password field - hide value
577                           "D"       Debug option - don't show by default */
578     int     dispsize;  /* Field size in characters for dialog */
579 } PQconninfoOption;
580 </synopsis>
581 </para>
582
583 <para>
584    Returns a connection options array.  This may be used to determine
585    all possible <function>PQconnectdb</function> options and their
586    current default values.  The return value points to an array of
587    <structname>PQconninfoOption</structname> structures, which ends
588    with an entry having a null <structfield>keyword</> pointer.  The
589    null pointer is returned if memory could not be allocated. Note that
590    the current default values (<structfield>val</structfield> fields)
591    will depend on environment variables and other context.  Callers
592    must treat the connection options data as read-only.
593    </para>
594
595    <para>
596     After processing the options array, free it by passing it to
597     <function>PQconninfoFree</function>.  If this is not done, a small amount of memory
598     is leaked for each call to <function>PQconndefaults</function>.
599    </para>
600
601   </listitem>
602  </varlistentry>
603
604  <varlistentry>
605   <term><function>PQfinish</function><indexterm><primary>PQfinish</></></term>
606   <listitem>
607    <para>
608    Closes  the  connection to the server.  Also frees
609    memory used by the <structname>PGconn</structname> object.
610 <synopsis>
611 void PQfinish(PGconn *conn);
612 </synopsis>
613 </para>
614
615 <para>
616    Note that even if the server connection attempt fails (as
617    indicated by <function>PQstatus</function>), the application should call <function>PQfinish</function>
618    to free the memory used by the <structname>PGconn</structname> object.
619    The <structname>PGconn</> pointer must not be used again after
620    <function>PQfinish</function> has been called.
621    </para>
622   </listitem>
623  </varlistentry>
624
625  <varlistentry>
626   <term><function>PQreset</function><indexterm><primary>PQreset</></></term>
627   <listitem>
628    <para>
629    Resets the communication channel to the server.
630 <synopsis>
631 void PQreset(PGconn *conn);
632 </synopsis>
633 </para>
634
635 <para>
636    This function will close the connection
637    to the server and attempt to  reestablish  a  new
638    connection to the same server, using all the same
639    parameters previously used.  This may be useful for
640    error recovery if a working connection is lost.
641    </para>
642   </listitem>
643  </varlistentry>
644
645  <varlistentry>
646   <term><function>PQresetStart</function><indexterm><primary>PQresetStart</></></term>
647   <term><function>PQresetPoll</function><indexterm><primary>PQresetPoll</></></term>
648   <listitem>
649    <para>
650    Reset the communication channel to the server, in a nonblocking manner.
651 <synopsis>
652 int PQresetStart(PGconn *conn);
653 </synopsis>
654 <synopsis>
655 PostgresPollingStatusType PQresetPoll(PGconn *conn);
656 </synopsis>
657 </para>
658
659 <para>
660     These functions will close the connection to the server and attempt to
661     reestablish a new connection to the same server, using all the same
662     parameters previously used. This may be useful for error recovery if a
663     working connection is lost. They differ from <function>PQreset</function> (above) in that they
664     act in a nonblocking manner. These functions suffer from the same
665     restrictions as <function>PQconnectStart</> and <function>PQconnectPoll</>.
666    </para>
667    <para>
668     To initiate a connection reset, call <function>PQresetStart</function>. If it returns 0, the reset has failed. If it returns 1,
669     poll the reset using <function>PQresetPoll</function> in exactly the same way as you would
670     create the connection using <function>PQconnectPoll</function>.
671    </para>
672   </listitem>
673  </varlistentry>
674
675  </variablelist>
676 </para>
677 </sect1>
678
679 <sect1 id="libpq-status">
680 <title>Connection Status Functions</title>
681
682   <para>
683    These functions may be used to interrogate the status
684    of an existing database connection object.
685   </para>
686
687 <tip>
688 <para>
689 <indexterm><primary>libpq-fe.h</></>
690 <indexterm><primary>libpq-int.h</></>
691 <application>libpq</application> application programmers should be careful to
692 maintain the <structname>PGconn</structname> abstraction.  Use the accessor
693 functions described below to get
694 at the contents of <structname>PGconn</structname>.  Avoid directly referencing the fields of the
695 <structname>PGconn</> structure because they are subject to change in the future.
696 (Beginning in <productname>PostgreSQL</productname> release 6.4, the
697 definition of the <type>struct</type> behind <structname>PGconn</> is not even provided in <filename>libpq-fe.h</filename>.
698 If you have old code that accesses <structname>PGconn</structname> fields directly, you can keep using it
699 by including <filename>libpq-int.h</filename> too, but you are encouraged to fix the code
700 soon.)
701 </para>
702 </tip>
703
704 <para>
705 The following functions return parameter values established at connection.
706 These values are fixed for the life of the <structname>PGconn</> object.
707
708 <variablelist>
709 <varlistentry>
710 <term><function>PQdb</function><indexterm><primary>PQdb</></></term>
711 <listitem>
712 <para>
713          Returns the database name of the connection.
714 <synopsis>
715 char *PQdb(const PGconn *conn);
716 </synopsis>
717 </para>
718 </listitem>
719 </varlistentry>
720
721 <varlistentry>
722 <term><function>PQuser</function><indexterm><primary>PQuser</></></term>
723 <listitem>
724 <para>
725          Returns the user name of the connection.
726 <synopsis>
727 char *PQuser(const PGconn *conn);
728 </synopsis>
729 </para>
730 </listitem>
731 </varlistentry>
732
733 <varlistentry>
734 <term><function>PQpass</function><indexterm><primary>PQpass</></></term>
735 <listitem>
736 <para>
737          Returns the password of the connection.
738 <synopsis>
739 char *PQpass(const PGconn *conn);
740 </synopsis>
741 </para>
742 </listitem>
743 </varlistentry>
744
745 <varlistentry>
746 <term><function>PQhost</function><indexterm><primary>PQhost</></></term>
747 <listitem>
748 <para>
749          Returns the server host name of the connection.
750 <synopsis>
751 char *PQhost(const PGconn *conn);
752 </synopsis>
753 </para>
754 </listitem>
755 </varlistentry>
756
757 <varlistentry>
758 <term><function>PQport</function><indexterm><primary>PQport</></></term>
759 <listitem>
760 <para>
761          Returns the port of the connection.
762 <synopsis>
763 char *PQport(const PGconn *conn);
764 </synopsis>
765 </para>
766 </listitem>
767 </varlistentry>
768
769 <varlistentry>
770 <term><function>PQtty</function><indexterm><primary>PQtty</></></term>
771 <listitem>
772 <para>
773          Returns the debug <acronym>TTY</acronym> of the connection.
774          (This is obsolete, since the server no longer pays attention
775          to the <acronym>TTY</acronym> setting, but the function remains
776          for backwards compatibility.)
777 <synopsis>
778 char *PQtty(const PGconn *conn);
779 </synopsis>
780 </para>
781 </listitem>
782 </varlistentry>
783
784 <varlistentry>
785 <term><function>PQoptions</function><indexterm><primary>PQoptions</></></term>
786 <listitem>
787 <para>
788        Returns the command-line options passed in the connection request.
789 <synopsis>
790 char *PQoptions(const PGconn *conn);
791 </synopsis>
792 </para>
793 </listitem>
794 </varlistentry>
795 </variablelist>
796 </para>
797
798 <para>
799 The following functions return status data that can change as operations
800 are executed on the <structname>PGconn</> object.
801
802 <variablelist>
803 <varlistentry>
804 <term><function>PQstatus</function><indexterm><primary>PQstatus</></></term>
805 <listitem>
806 <para>
807          Returns the status of the connection. 
808 <synopsis>
809 ConnStatusType PQstatus(const PGconn *conn);
810 </synopsis>
811 </para>
812
813       <para>
814        The status can be one of a number of values.
815        However, only two of these are
816        seen outside of an asynchronous connection procedure:
817        <literal>CONNECTION_OK</literal> and
818        <literal>CONNECTION_BAD</literal>. A good
819        connection to the database has the status <literal>CONNECTION_OK</literal>.
820        A failed connection
821        attempt is signaled by status
822        <literal>CONNECTION_BAD</literal>.
823        Ordinarily, an OK status will remain so until
824        <function>PQfinish</function>, but a
825        communications failure might result in the status changing to
826        <literal>CONNECTION_BAD</literal> prematurely.
827        In that case the application
828        could try to recover by calling <function>PQreset</function>.
829       </para>
830
831       <para>
832        See the entry for <function>PQconnectStart</> and <function>PQconnectPoll</> with regards
833        to other status codes
834        that might be seen.
835       </para>
836      </listitem>
837     </varlistentry>
838
839 <varlistentry>
840 <term><function>PQtransactionStatus</function><indexterm><primary>PQtransactionStatus</></></term>
841 <listitem>
842 <para>
843          Returns the current in-transaction status of the server.
844 <synopsis>
845 PGTransactionStatusType PQtransactionStatus(const PGconn *conn);
846 </synopsis>
847
848 The status can be <literal>PQTRANS_IDLE</literal> (currently idle),
849 <literal>PQTRANS_ACTIVE</literal> (a command is in progress),
850 <literal>PQTRANS_INTRANS</literal> (idle, in a valid transaction block),
851 or <literal>PQTRANS_INERROR</literal> (idle, in a failed transaction block).
852 <literal>PQTRANS_UNKNOWN</literal> is reported if the connection is bad.
853 <literal>PQTRANS_ACTIVE</literal> is reported only when a query
854 has been sent to the server and not yet completed.
855 </para>
856 <caution>
857 <para>
858 <function>PQtransactionStatus</> will give incorrect results when using
859 a <productname>PostgreSQL</> 7.3 server that has the parameter <literal>autocommit</>
860 set to off.  The server-side autocommit feature has been
861 deprecated and does not exist in later server versions.
862 </para>
863 </caution>
864 </listitem>
865 </varlistentry>
866
867 <varlistentry>
868 <term><function>PQparameterStatus</function><indexterm><primary>PQparameterStatus</></></term>
869 <listitem>
870 <para>
871          Looks up a current parameter setting of the server.
872 <synopsis>
873 const char *PQparameterStatus(const PGconn *conn, const char *paramName);
874 </synopsis>
875
876 Certain parameter values are reported by the server automatically at
877 connection startup or whenever their values change.
878 <function>PQparameterStatus</> can be used to interrogate these settings.
879 It returns the current value of a parameter if known, or <symbol>NULL</symbol>
880 if the parameter is not known.
881 </para>
882
883 <para>
884 Parameters reported as of the current release include
885 <literal>server_version</>,
886 <literal>server_encoding</>,
887 <literal>client_encoding</>,
888 <literal>is_superuser</>,
889 <literal>session_authorization</>,
890 <literal>DateStyle</>,
891 <literal>TimeZone</>,
892 <literal>integer_datetimes</>, and
893 <literal>standard_compliant_strings</>.
894 (<literal>server_encoding</>, <literal>TimeZone</>, and
895 <literal>integer_datetimes</> were not reported by releases before 8.0;
896 <literal>standard_compliant_strings</> was not reported by releases
897 before 8.1.)
898 Note that
899 <literal>server_version</>,
900 <literal>server_encoding</> and
901 <literal>integer_datetimes</>
902 cannot change after startup.
903 </para>
904
905 <para>
906 Pre-3.0-protocol servers do not report parameter settings, but
907 <application>libpq</> includes logic to obtain values for
908 <literal>server_version</> and <literal>client_encoding</> anyway.
909 Applications are encouraged to use <function>PQparameterStatus</>
910 rather than <foreignphrase>ad hoc</> code to determine these values.
911 (Beware however
912 that on a pre-3.0 connection, changing <literal>client_encoding</> via
913 <command>SET</> after connection startup will not be reflected by
914 <function>PQparameterStatus</>.)  For <literal>server_version</>,
915 see also <function>PQserverVersion</>, which returns the information
916 in a numeric form that is much easier to compare against.
917 </para>
918
919 <para>
920 If no value for <literal>standard_compliant_strings</> is reported,
921 applications may assume it is <literal>false</>, that is, backslashes
922 are treated as escapes in string literals.  Also, the presence of this
923 parameter may be taken as an indication that the escape string syntax
924 (<literal>E'...'</>) is accepted.
925 </para>
926
927 <para>
928 Although the returned pointer is declared <literal>const</>, it in fact
929 points to mutable storage associated with the <literal>PGconn</> structure.
930 It is unwise to assume the pointer will remain valid across queries.
931 </para>
932 </listitem>
933 </varlistentry>
934
935 <varlistentry>
936 <term><function>PQprotocolVersion</function><indexterm><primary>PQprotocolVersion</></></term>
937 <listitem>
938 <para>
939          Interrogates the frontend/backend protocol being used.
940 <synopsis>
941 int PQprotocolVersion(const PGconn *conn);
942 </synopsis>
943 Applications may wish to use this to determine whether certain features
944 are supported.
945 Currently, the possible values are 2 (2.0 protocol), 3 (3.0 protocol),
946 or zero (connection bad).  This will not change after connection
947 startup is complete, but it could theoretically change during a connection
948 reset.  The 3.0 protocol will normally be used when communicating with
949 <productname>PostgreSQL</> 7.4 or later servers; pre-7.4 servers support
950 only protocol 2.0.  (Protocol 1.0 is obsolete and not supported by <application>libpq</application>.)
951 </para>
952 </listitem>
953 </varlistentry>
954
955 <varlistentry>
956 <term><function>PQserverVersion</function><indexterm><primary>PQserverVersion</></></term>
957 <listitem>
958 <para>
959          Returns an integer representing the backend version.
960 <synopsis>
961 int PQserverVersion(const PGconn *conn);
962 </synopsis>
963 Applications may use this to determine the version of the database server they
964 are connected to. The number is formed by converting the major, minor, and
965 revision numbers into two-decimal-digit numbers and appending them
966 together. For example, version 7.4.2 will be returned as 70402, and version
967 8.1 will be returned as 80100 (leading zeroes are not shown).  Zero is
968 returned if the connection is bad.
969 </para>
970 </listitem>
971 </varlistentry>
972
973     <varlistentry>
974      <term><function>PQerrorMessage</function><indexterm><primary>PQerrorMessage</></></term>
975      <listitem>
976       <para>
977        <indexterm><primary>error message</></>
978        Returns the error message most recently generated by
979        an operation on the connection.
980 <synopsis>
981 char *PQerrorMessage(const PGconn *conn);
982 </synopsis>
983       </para>
984
985       <para>
986        Nearly all <application>libpq</> functions will set a message for
987        <function>PQerrorMessage</function> if they fail.
988        Note that by <application>libpq</application> convention, a nonempty
989        <function>PQerrorMessage</function> result will
990        include a trailing newline. The caller should not free the result 
991        directly. It will be freed when the associated <structname>PGconn</> 
992        handle is passed to <function>PQfinish</function>.  The result string
993        should not be expected to remain the same across operations on the
994        <literal>PGconn</> structure.
995       </para>
996      </listitem>
997     </varlistentry>
998
999     <varlistentry>
1000      <term><function>PQsocket</function><indexterm><primary>PQsocket</></></term>
1001      <listitem>
1002       <para>
1003        Obtains the file descriptor number of the connection socket to
1004        the server.  A valid descriptor will be greater than or equal
1005        to 0; a result of -1 indicates that no server connection is
1006        currently open.  (This will not change during normal operation,
1007        but could change during connection setup or reset.)
1008 <synopsis>
1009 int PQsocket(const PGconn *conn);
1010 </synopsis>
1011       </para>
1012      </listitem>
1013     </varlistentry>
1014
1015     <varlistentry>
1016      <term><function>PQbackendPID</function><indexterm><primary>PQbackendPID</></></term>
1017      <listitem>
1018       <para>
1019        Returns the process <acronym>ID</acronym>
1020        (PID)<indexterm><primary>PID</><secondary>determining PID of
1021        server process</><tertiary>in libpq</></> of the backend server
1022        process handling this connection.
1023 <synopsis>
1024 int PQbackendPID(const PGconn *conn);
1025 </synopsis>
1026 </para>
1027
1028 <para>
1029        The backend <acronym>PID</acronym> is useful for debugging
1030        purposes and for comparison to <command>NOTIFY</command>
1031        messages (which include the <acronym>PID</acronym> of the
1032        notifying backend process).  Note that the
1033        <acronym>PID</acronym> belongs to a process executing on the
1034        database server host, not the local host!
1035       </para>
1036      </listitem>
1037     </varlistentry>
1038
1039     <varlistentry>
1040      <term><function>PQgetssl</function><indexterm><primary>PQgetssl</></></term>
1041      <listitem>
1042       <para>
1043        <indexterm><primary>SSL</><secondary sortas="libpq">in libpq</secondary></indexterm>
1044        Returns the SSL structure used in the connection, or null
1045        if SSL is not in use. 
1046 <synopsis>
1047 SSL *PQgetssl(const PGconn *conn);
1048 </synopsis>
1049 </para>
1050
1051 <para>
1052        This structure can be used to verify encryption levels, check
1053        server certificates, and more. Refer to the <productname>OpenSSL</> documentation
1054        for information about this structure.
1055       </para>
1056       <para>
1057        You must define <symbol>USE_SSL</symbol> in order to get the
1058        correct prototype for this function. Doing this will also 
1059        automatically include <filename>ssl.h</filename> from <productname>OpenSSL</productname>.
1060       </para>
1061      </listitem>
1062     </varlistentry>
1063
1064 </variablelist>
1065 </para>
1066
1067 </sect1>
1068
1069 <sect1 id="libpq-exec">
1070 <title>Command Execution Functions</title>
1071
1072 <para>
1073 Once a connection to a database server has been successfully
1074 established, the functions described here are used to perform
1075 SQL queries and commands.
1076 </para>
1077
1078 <sect2 id="libpq-exec-main">
1079   <title>Main Functions</title>
1080
1081 <para>
1082 <variablelist>
1083 <varlistentry>
1084 <term><function>PQexec</function><indexterm><primary>PQexec</></></term>
1085 <listitem>
1086 <para>
1087           Submits a command to the server
1088           and waits for the result.
1089 <synopsis>
1090 PGresult *PQexec(PGconn *conn, const char *command);
1091 </synopsis>
1092 </para>
1093
1094 <para>
1095           Returns a <structname>PGresult</structname> pointer or possibly a null pointer.
1096           A non-null pointer will generally be returned except in
1097           out-of-memory conditions or serious errors such as inability
1098           to send the command to the server.
1099           If a null pointer is returned, it
1100           should be treated like a <symbol>PGRES_FATAL_ERROR</symbol> result.
1101           Use <function>PQerrorMessage</function> to get more information
1102           about such errors.
1103 </para>
1104 </listitem>
1105 </varlistentry>
1106 </variablelist>
1107
1108 It is allowed to include multiple SQL commands (separated by semicolons) in
1109 the command string.  Multiple queries sent in a single <function>PQexec</>
1110 call are processed in a single transaction, unless there are explicit
1111 <command>BEGIN</command>/<command>COMMIT</command> commands included in the query string to divide it into multiple
1112 transactions.  Note however that the returned <structname>PGresult</structname>
1113 structure describes only the result of the last command executed from the
1114 string.  Should one of the commands fail, processing of the string stops with
1115 it and the returned <structname>PGresult</structname> describes the error
1116 condition.
1117 </para>
1118
1119 <para>
1120 <variablelist>
1121 <varlistentry>
1122 <term><function>PQexecParams</function><indexterm><primary>PQexecParams</></></term>
1123 <listitem>
1124 <para>
1125           Submits a command to the server and waits for the result,
1126           with the ability to pass parameters separately from the SQL
1127           command text.
1128 <synopsis>
1129 PGresult *PQexecParams(PGconn *conn,
1130                        const char *command,
1131                        int nParams,
1132                        const Oid *paramTypes,
1133                        const char * const *paramValues,
1134                        const int *paramLengths,
1135                        const int *paramFormats,
1136                        int resultFormat);
1137 </synopsis>
1138 </para>
1139
1140 <para>
1141 <function>PQexecParams</> is like <function>PQexec</>, but offers additional
1142 functionality: parameter values can be specified separately from the command
1143 string proper, and query results can be requested in either text or binary
1144 format.  <function>PQexecParams</> is supported only in protocol 3.0 and later
1145 connections; it will fail when using protocol 2.0.
1146 </para>
1147
1148 <para>
1149 If parameters are used, they are referred to in the command string
1150 as <literal>$1</>, <literal>$2</>, etc.
1151 <parameter>nParams</> is the number of parameters supplied; it is the length
1152 of the arrays <parameter>paramTypes[]</>, <parameter>paramValues[]</>,
1153 <parameter>paramLengths[]</>, and <parameter>paramFormats[]</>.  (The
1154 array pointers may be <symbol>NULL</symbol> when <parameter>nParams</> is zero.)
1155 <parameter>paramTypes[]</> specifies, by OID, the data types to be assigned to
1156 the parameter symbols.  If <parameter>paramTypes</> is <symbol>NULL</symbol>, or any particular
1157 element in the array is zero, the server assigns a data type to the parameter
1158 symbol in the same way it would do for an untyped literal string.
1159 <parameter>paramValues[]</> specifies the actual values of the parameters.
1160 A null pointer in this array means the corresponding parameter is null;
1161 otherwise the pointer points to a zero-terminated text string (for text
1162 format) or binary data in the format expected by the server (for binary
1163 format).
1164 <parameter>paramLengths[]</> specifies the actual data lengths of
1165 binary-format parameters.  It is ignored for null parameters and text-format
1166 parameters.  The array pointer may be null when there are no binary
1167 parameters.
1168 <parameter>paramFormats[]</> specifies whether parameters are text (put a zero
1169 in the array) or binary (put a one in the array).  If the array pointer is
1170 null then all parameters are presumed to be text.
1171 <parameter>resultFormat</> is zero to obtain results in text format, or one to
1172 obtain results in binary format.  (There is not currently a provision to
1173 obtain different result columns in different formats, although that is
1174 possible in the underlying protocol.)
1175 </para>
1176 </listitem>
1177 </varlistentry>
1178 </variablelist>
1179
1180 The primary advantage of <function>PQexecParams</> over <function>PQexec</>
1181 is that parameter values may be separated from the command string, thus
1182 avoiding the need for tedious and error-prone quoting and escaping.
1183
1184 Unlike <function>PQexec</>, <function>PQexecParams</> allows at most one SQL
1185 command in the given string.  (There can be semicolons in it, but not more
1186 than one nonempty command.)  This is a limitation of the underlying protocol,
1187 but has some usefulness as an extra defense against SQL-injection attacks.
1188 </para>
1189
1190 <para>
1191 <variablelist>
1192 <varlistentry>
1193 <term><function>PQprepare</function><indexterm><primary>PQprepare</></></term>
1194 <listitem>
1195 <para>
1196           Submits a request to create a prepared statement with the
1197           given parameters, and waits for completion.
1198 <synopsis>
1199 PGresult *PQprepare(PGconn *conn,
1200                     const char *stmtName,
1201                     const char *query,
1202                     int nParams,
1203                     const Oid *paramTypes);
1204 </synopsis>
1205 </para>
1206
1207 <para>
1208 <function>PQprepare</> creates a prepared statement for later execution with
1209 <function>PQexecPrepared</>.
1210 This feature allows commands
1211 that will be used repeatedly to be parsed and planned just once, rather
1212 than each time they are executed.
1213 <function>PQprepare</> is supported only in protocol 3.0 and later
1214 connections; it will fail when using protocol 2.0.
1215 </para>
1216
1217 <para>
1218 The function creates a prepared statement named <parameter>stmtName</>
1219 from the <parameter>query</> string, which must contain a single SQL command.
1220 <parameter>stmtName</> may be <literal>""</> to create an unnamed statement,
1221 in which case any pre-existing unnamed statement is automatically replaced;
1222 otherwise it is an error if the statement name is already defined in the
1223 current session.
1224 If any parameters are used, they are referred
1225 to in the query as <literal>$1</>, <literal>$2</>, etc.
1226 <parameter>nParams</> is the number of parameters for which types are
1227 pre-specified in the array <parameter>paramTypes[]</>.  (The array pointer
1228 may be <symbol>NULL</symbol> when <parameter>nParams</> is zero.)
1229 <parameter>paramTypes[]</> specifies, by OID, the data types to be assigned to
1230 the parameter symbols.  If <parameter>paramTypes</> is <symbol>NULL</symbol>,
1231 or any particular element in the array is zero, the server assigns a data type
1232 to the parameter symbol in the same way it would do for an untyped literal
1233 string.  Also, the query may use parameter symbols with numbers higher than
1234 <parameter>nParams</>; data types will be inferred for these symbols as
1235 well.
1236 </para>
1237
1238 <para>
1239 As with <function>PQexec</>, the result is normally a
1240 <structname>PGresult</structname> object whose contents indicate server-side
1241 success or failure.  A null result indicates out-of-memory or inability to
1242 send the command at all.
1243 Use <function>PQerrorMessage</function> to get more information
1244 about such errors.
1245 </para>
1246
1247 <para>
1248 At present, there is no way to determine the actual data type inferred for
1249 any parameters whose types are not specified in <parameter>paramTypes[]</>.
1250 This is a <application>libpq</> omission that will probably be rectified
1251 in a future release.
1252 </para>
1253 </listitem>
1254 </varlistentry>
1255 </variablelist>
1256
1257 Prepared statements for use with <function>PQexecPrepared</> can also be
1258 created by executing SQL <command>PREPARE</> statements.  (But
1259 <function>PQprepare</> is more flexible since it does not require
1260 parameter types to be pre-specified.)  Also, although there is no
1261 <application>libpq</> function for deleting a prepared statement,
1262 the SQL <command>DEALLOCATE</> statement can be used for that purpose.
1263 </para>
1264
1265 <para>
1266 <variablelist>
1267 <varlistentry>
1268 <term><function>PQexecPrepared</function><indexterm><primary>PQexecPrepared</></></term>
1269 <listitem>
1270 <para>
1271           Sends a request to execute a prepared statement with given
1272           parameters, and waits for the result.
1273 <synopsis>
1274 PGresult *PQexecPrepared(PGconn *conn,
1275                          const char *stmtName,
1276                          int nParams,
1277                          const char * const *paramValues,
1278                          const int *paramLengths,
1279                          const int *paramFormats,
1280                          int resultFormat);
1281 </synopsis>
1282 </para>
1283
1284 <para>
1285 <function>PQexecPrepared</> is like <function>PQexecParams</>, but the
1286 command to be executed is specified by naming a previously-prepared
1287 statement, instead of giving a query string.
1288 This feature allows commands
1289 that will be used repeatedly to be parsed and planned just once, rather
1290 than each time they are executed.
1291 The statement must have been prepared previously in the current session.
1292 <function>PQexecPrepared</> is supported only in protocol 3.0 and later
1293 connections; it will fail when using protocol 2.0.
1294 </para>
1295
1296 <para>
1297 The parameters are identical to <function>PQexecParams</>, except that the
1298 name of a prepared statement is given instead of a query string, and the
1299 <parameter>paramTypes[]</> parameter is not present (it is not needed since
1300 the prepared statement's parameter types were determined when it was created).
1301 </para>
1302 </listitem>
1303 </varlistentry>
1304 </variablelist>
1305 </para>
1306
1307 <para>
1308 The
1309 <structname>PGresult</structname><indexterm><primary>PGresult</></>
1310 structure encapsulates the result returned by the server.
1311 <application>libpq</application> application programmers should be
1312 careful to maintain the <structname>PGresult</structname> abstraction.
1313 Use the accessor functions below to get at the contents of
1314 <structname>PGresult</structname>.  Avoid directly referencing the
1315 fields of the <structname>PGresult</structname> structure because they
1316 are subject to change in the future.
1317
1318 <variablelist>
1319 <varlistentry>
1320 <term><function>PQresultStatus</function><indexterm><primary>PQresultStatus</></></term>
1321 <listitem>
1322 <para>
1323           Returns the result status of the command.
1324 <synopsis>
1325 ExecStatusType PQresultStatus(const PGresult *res);
1326 </synopsis>
1327 </para>
1328
1329 <para>
1330 <function>PQresultStatus</function> can return one of the following values:
1331
1332 <variablelist>
1333  <varlistentry>
1334   <term><literal>PGRES_EMPTY_QUERY</literal></term>
1335   <listitem>
1336    <para>The string sent to the server was empty.</para>
1337   </listitem>
1338  </varlistentry>
1339
1340  <varlistentry>
1341   <term><literal>PGRES_COMMAND_OK</literal></term>
1342   <listitem>
1343    <para>Successful completion of a command returning no data.</para>
1344   </listitem>
1345  </varlistentry>
1346
1347  <varlistentry>
1348   <term><literal>PGRES_TUPLES_OK</literal></term>
1349   <listitem>
1350    <para>Successful completion of a command returning data (such as
1351    a <command>SELECT</> or <command>SHOW</>).</para>
1352   </listitem>
1353  </varlistentry>
1354
1355  <varlistentry>
1356   <term><literal>PGRES_COPY_OUT</literal></term>
1357   <listitem>
1358    <para>Copy Out (from server) data transfer started.</para>
1359   </listitem>
1360  </varlistentry>
1361
1362  <varlistentry>
1363   <term><literal>PGRES_COPY_IN</literal></term>
1364   <listitem>
1365    <para>Copy In (to server) data transfer started.</para>
1366   </listitem>
1367  </varlistentry>
1368
1369  <varlistentry>
1370   <term><literal>PGRES_BAD_RESPONSE</literal></term>
1371   <listitem>
1372    <para>The server's response was not understood.</para>
1373   </listitem>
1374  </varlistentry>
1375
1376  <varlistentry>
1377   <term><literal>PGRES_NONFATAL_ERROR</literal></term>
1378   <listitem>
1379    <para>A nonfatal error (a notice or warning) occurred.</para>
1380   </listitem>
1381  </varlistentry>
1382
1383  <varlistentry>
1384   <term><literal>PGRES_FATAL_ERROR</literal></term>
1385   <listitem>
1386    <para>A fatal error occurred.</para>
1387   </listitem>
1388  </varlistentry>
1389 </variablelist>
1390
1391 If the result status is <literal>PGRES_TUPLES_OK</literal>, then the
1392 functions described below can be used to retrieve the rows returned by
1393 the query.  Note that a <command>SELECT</command> command that happens
1394 to retrieve zero rows still shows <literal>PGRES_TUPLES_OK</literal>.
1395 <literal>PGRES_COMMAND_OK</literal> is for commands that can never
1396 return rows (<command>INSERT</command>, <command>UPDATE</command>,
1397 etc.). A response of <literal>PGRES_EMPTY_QUERY</literal> may indicate
1398 a bug in the client software.
1399 </para>
1400
1401 <para>
1402 A result of status <symbol>PGRES_NONFATAL_ERROR</symbol> will never be
1403 returned directly by <function>PQexec</function> or other query
1404 execution functions; results of this kind are instead passed to the notice
1405 processor (see <xref linkend="libpq-notice-processing">).
1406 </para>
1407 </listitem>
1408 </varlistentry>
1409
1410 <varlistentry>
1411 <term><function>PQresStatus</function><indexterm><primary>PQresStatus</></></term>
1412 <listitem>
1413 <para>
1414         Converts the enumerated type returned by <function>PQresultStatus</> into
1415         a string constant describing the status code. The caller should not 
1416         free the result.
1417 <synopsis>
1418 char *PQresStatus(ExecStatusType status);
1419 </synopsis>
1420 </para>
1421 </listitem>
1422 </varlistentry>
1423
1424 <varlistentry>
1425 <term><function>PQresultErrorMessage</function><indexterm><primary>PQresultErrorMessage</></></term>
1426 <listitem>
1427 <para>
1428 Returns the error message associated with the command, or an empty string
1429 if there was no error.
1430 <synopsis>
1431 char *PQresultErrorMessage(const PGresult *res);
1432 </synopsis>
1433 If there was an error, the returned string will include a trailing newline. 
1434 The caller should not free the result directly. It will be freed when the 
1435 associated <structname>PGresult</> handle is passed to 
1436 <function>PQclear</function>.
1437 </para>
1438
1439 <para>
1440 Immediately following a <function>PQexec</function> or <function>PQgetResult</function>
1441 call, <function>PQerrorMessage</function> (on the connection) will return the same
1442 string as <function>PQresultErrorMessage</function> (on the result).  However, a
1443 <structname>PGresult</structname> will retain its error message
1444 until destroyed, whereas the connection's error message will change when
1445 subsequent operations are done.  Use <function>PQresultErrorMessage</function> when you want to
1446 know the status associated with a particular <structname>PGresult</structname>; use <function>PQerrorMessage</function>
1447 when you want to know the status from the latest operation on the connection.
1448 </para>
1449 </listitem>
1450 </varlistentry>
1451
1452 <varlistentry>
1453 <term><function>PQresultErrorField</function><indexterm><primary>PQresultErrorField</></></term>
1454 <listitem>
1455 <para>
1456 Returns an individual field of an error report.
1457 <synopsis>
1458 char *PQresultErrorField(const PGresult *res, int fieldcode);
1459 </synopsis>
1460 <parameter>fieldcode</> is an error field identifier; see the symbols
1461 listed below.  <symbol>NULL</symbol> is returned if the
1462 <structname>PGresult</structname> is not an error or warning result,
1463 or does not include the specified field.  Field values will normally
1464 not include a trailing newline. The caller should not free the 
1465 result directly. It will be freed when the
1466 associated <structname>PGresult</> handle is passed to
1467 <function>PQclear</function>.
1468 </para>
1469
1470 <para>
1471 The following field codes are available:
1472 <variablelist>
1473
1474 <varlistentry>
1475 <term><symbol>PG_DIAG_SEVERITY</></term>
1476 <listitem>
1477 <para>
1478 The severity; the field contents are <literal>ERROR</>,
1479 <literal>FATAL</>, or <literal>PANIC</> (in an error message), or
1480 <literal>WARNING</>, <literal>NOTICE</>, <literal>DEBUG</>,
1481 <literal>INFO</>, or <literal>LOG</> (in a notice message), or a
1482 localized translation of one of these.  Always present.
1483 </para>
1484 </listitem>
1485 </varlistentry>
1486
1487 <varlistentry>
1488  <indexterm>
1489   <primary>error codes</primary>
1490   <secondary>libpq</secondary>
1491  </indexterm>
1492 <term><symbol>PG_DIAG_SQLSTATE</>
1493 </term>
1494 <listitem>
1495 <para>
1496 The SQLSTATE code for the error. The SQLSTATE code identifies the type
1497 of error that has occurred; it can be used by front-end applications
1498 to perform specific operations (such as error handling) in response to
1499 a particular database error. For a list of the possible SQLSTATE
1500 codes, see <xref linkend="errcodes-appendix">. This field is not
1501 localizable, and is always present.
1502 </para>
1503 </listitem>
1504 </varlistentry>
1505
1506 <varlistentry>
1507 <term><symbol>PG_DIAG_MESSAGE_PRIMARY</></term>
1508 <listitem>
1509 <para>
1510 The primary human-readable error message (typically one line).  Always
1511 present.
1512 </para>
1513 </listitem>
1514 </varlistentry>
1515
1516 <varlistentry>
1517 <term><symbol>PG_DIAG_MESSAGE_DETAIL</></term>
1518 <listitem>
1519 <para>
1520 Detail: an optional secondary error message carrying more detail about
1521 the problem.  May run to multiple lines.
1522 </para>
1523 </listitem>
1524 </varlistentry>
1525
1526 <varlistentry>
1527 <term><symbol>PG_DIAG_MESSAGE_HINT</></term>
1528 <listitem>
1529 <para>
1530 Hint: an optional suggestion what to do about the problem.  This is
1531 intended to differ from detail in that it offers advice (potentially
1532 inappropriate) rather than hard facts.  May run to multiple lines.
1533 </para>
1534 </listitem>
1535 </varlistentry>
1536
1537 <varlistentry>
1538 <term><symbol>PG_DIAG_STATEMENT_POSITION</></term>
1539 <listitem>
1540 <para>
1541 A string containing a decimal integer indicating an error cursor
1542 position as an index into the original statement string.  The first
1543 character has index 1, and positions are measured in characters not
1544 bytes.
1545 </para>
1546 </listitem>
1547 </varlistentry>
1548
1549 <varlistentry>
1550 <term><symbol>PG_DIAG_INTERNAL_POSITION</></term>
1551 <listitem>
1552 <para>
1553 This is defined the same as the <symbol>PG_DIAG_STATEMENT_POSITION</>
1554 field, but it is used when the cursor position refers to an internally
1555 generated command rather than the one submitted by the client.
1556 The <symbol>PG_DIAG_INTERNAL_QUERY</> field will always appear when this field
1557 appears.
1558 </para>
1559 </listitem>
1560 </varlistentry>
1561
1562 <varlistentry>
1563 <term><symbol>PG_DIAG_INTERNAL_QUERY</></term>
1564 <listitem>
1565 <para>
1566 The text of a failed internally-generated command.
1567 This could be, for example, a SQL query issued by a PL/pgSQL function.
1568 </para>
1569 </listitem>
1570 </varlistentry>
1571
1572 <varlistentry>
1573 <term><symbol>PG_DIAG_CONTEXT</></term>
1574 <listitem>
1575 <para>
1576 An indication of the context in which the error occurred.
1577 Presently this includes a call stack traceback of active
1578 procedural language functions and internally-generated queries.
1579 The trace is one entry per line, most recent first.
1580 </para>
1581 </listitem>
1582 </varlistentry>
1583
1584 <varlistentry>
1585 <term><symbol>PG_DIAG_SOURCE_FILE</></term>
1586 <listitem>
1587 <para>
1588 The file name of the source-code location where the error was
1589 reported.
1590 </para>
1591 </listitem>
1592 </varlistentry>
1593
1594 <varlistentry>
1595 <term><symbol>PG_DIAG_SOURCE_LINE</></term>
1596 <listitem>
1597 <para>
1598 The line number of the source-code location where the error was
1599 reported.
1600 </para>
1601 </listitem>
1602 </varlistentry>
1603
1604 <varlistentry>
1605 <term><symbol>PG_DIAG_SOURCE_FUNCTION</></term>
1606 <listitem>
1607 <para>
1608 The name of the source-code function reporting the error.
1609 </para>
1610 </listitem>
1611 </varlistentry>
1612 </variablelist>
1613 </para>
1614
1615 <para>
1616 The client is responsible for formatting displayed information to meet
1617 its needs; in particular it should break long lines as needed.
1618 Newline characters appearing in the error message fields should be
1619 treated as paragraph breaks, not line breaks.
1620 </para>
1621
1622 <para>
1623 Errors generated internally by <application>libpq</application> will
1624 have severity and primary message, but typically no other fields.
1625 Errors returned by a pre-3.0-protocol server will include severity and
1626 primary message, and sometimes a detail message, but no other fields.
1627 </para>
1628
1629 <para>
1630 Note that error fields are only available from
1631 <structname>PGresult</structname> objects, not
1632 <structname>PGconn</structname> objects; there is no
1633 <function>PQerrorField</function> function.
1634 </para>
1635 </listitem>
1636 </varlistentry>
1637
1638 <varlistentry>
1639 <term><function>PQclear</function><indexterm><primary>PQclear</></></term>
1640 <listitem>
1641 <para>
1642           Frees  the  storage  associated with a <structname>PGresult</structname>.
1643           Every command result should be freed via <function>PQclear</function> when
1644           it  is  no  longer needed.
1645 <synopsis>
1646 void PQclear(PGresult *res);
1647 </synopsis>
1648 </para>
1649
1650 <para>
1651           You can keep a <structname>PGresult</structname> object around for as long as you
1652           need it; it does not go away when you issue a new command,
1653           nor even if you close the connection.  To get rid of it,
1654           you must call <function>PQclear</function>.  Failure to do this will
1655           result in memory leaks in your application.
1656 </para>
1657 </listitem>
1658 </varlistentry>
1659
1660 <varlistentry>
1661 <term><function>PQmakeEmptyPGresult</function><indexterm><primary>PQmakeEmptyPGresult</></></term>
1662 <listitem>
1663 <para>
1664           Constructs an empty <structname>PGresult</structname> object with the given status.
1665 <synopsis>
1666 PGresult *PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status);
1667 </synopsis>
1668 </para>
1669
1670 <para>
1671 This is <application>libpq</>'s internal function to allocate and
1672 initialize an empty <structname>PGresult</structname> object.  This
1673 function returns NULL if memory could not be allocated. It is exported
1674 because some applications find it useful to generate result objects
1675 (particularly objects with error status) themselves.  If
1676 <parameter>conn</parameter> is not null and <parameter>status</>
1677 indicates an error, the current error message of the specified
1678 connection is copied into the <structname>PGresult</structname>.  Note
1679 that <function>PQclear</function> should eventually be called on the
1680 object, just as with a <structname>PGresult</structname> returned by
1681 <application>libpq</application> itself.
1682 </para>
1683 </listitem>
1684 </varlistentry>
1685 </variablelist>
1686 </para>
1687 </sect2>
1688
1689 <sect2 id="libpq-exec-select-info">
1690   <title>Retrieving Query Result Information</title>
1691
1692 <para>
1693 These functions are used to extract information from a
1694 <structname>PGresult</structname> object that represents a successful
1695 query result (that is, one that has status
1696 <literal>PGRES_TUPLES_OK</literal>).  For objects with other status
1697 values they will act as though the result has zero rows and zero columns.
1698 </para>
1699
1700 <variablelist>
1701 <varlistentry>
1702 <term><function>PQntuples</function><indexterm><primary>PQntuples</></></term>
1703 <listitem>
1704 <para>
1705           Returns the number of rows (tuples)
1706           in the query result.
1707 <synopsis>
1708 int PQntuples(const PGresult *res);
1709 </synopsis>
1710 </para>
1711 </listitem>
1712 </varlistentry>
1713
1714 <varlistentry>
1715 <term><function>PQnfields</function><indexterm><primary>PQnfields</></></term>
1716 <listitem>
1717 <para>
1718           Returns the number of columns (fields)
1719           in each row of the query result.
1720 <synopsis>
1721 int PQnfields(const PGresult *res);
1722 </synopsis>
1723 </para>
1724 </listitem>
1725 </varlistentry>
1726
1727 <varlistentry>
1728 <term><function>PQfname</function><indexterm><primary>PQfname</></></term>
1729 <listitem>
1730 <para>
1731 Returns the column name associated with the given column number.
1732 Column numbers start at 0. The caller should not free the result
1733 directly. It will be freed when the associated <structname>PGresult</>
1734 handle is passed to <function>PQclear</function>.
1735 <synopsis>
1736 char *PQfname(const PGresult *res,
1737               int column_number);
1738 </synopsis>
1739 </para>
1740
1741 <para>
1742 <symbol>NULL</symbol> is returned if the column number is out of range.
1743 </para>
1744 </listitem>
1745 </varlistentry>
1746
1747 <varlistentry>
1748 <term><function>PQfnumber</function><indexterm><primary>PQfnumber</></></term>
1749 <listitem>
1750 <para>
1751           Returns the column number associated with the given column name.
1752 <synopsis>
1753 int PQfnumber(const PGresult *res,
1754               const char *column_name);
1755 </synopsis>
1756 </para>
1757
1758 <para>
1759         -1 is returned if the given name does not match any column.
1760 </para>
1761
1762 <para>
1763         The given name is treated like an identifier in an SQL command,
1764         that is, it is downcased unless double-quoted.  For example,
1765         given a query result generated from the SQL command
1766 <programlisting>
1767 select 1 as FOO, 2 as "BAR";
1768 </programlisting>
1769         we would have the results:
1770 <programlisting>
1771 PQfname(res, 0)              <lineannotation>foo</lineannotation>
1772 PQfname(res, 1)              <lineannotation>BAR</lineannotation>
1773 PQfnumber(res, "FOO")        <lineannotation>0</lineannotation>
1774 PQfnumber(res, "foo")        <lineannotation>0</lineannotation>
1775 PQfnumber(res, "BAR")        <lineannotation>-1</lineannotation>
1776 PQfnumber(res, "\"BAR\"")    <lineannotation>1</lineannotation>
1777 </programlisting>
1778 </para>
1779 </listitem>
1780 </varlistentry>
1781
1782 <varlistentry>
1783 <term><function>PQftable</function><indexterm><primary>PQftable</></></term>
1784 <listitem>
1785 <para>
1786  Returns the OID of the table from which the given column was fetched.
1787  Column numbers start at 0.
1788 <synopsis>
1789 Oid PQftable(const PGresult *res,
1790              int column_number);
1791 </synopsis>
1792 </para>
1793
1794 <para>
1795 <literal>InvalidOid</> is returned if the column number is out of range,
1796 or if the specified column is not a simple reference to a table column,
1797 or when using pre-3.0 protocol.
1798 You can query the system table <literal>pg_class</literal> to determine
1799 exactly which table is referenced.
1800 </para>
1801
1802 <para>
1803           The type <type>Oid</type> and the constant
1804           <literal>InvalidOid</literal> will be defined when you include
1805           the <application>libpq</application> header file. They will
1806           both be some integer type.
1807 </para>
1808 </listitem>
1809 </varlistentry>
1810
1811 <varlistentry>
1812 <term><function>PQftablecol</function><indexterm><primary>PQftablecol</></></term>
1813 <listitem>
1814 <para>
1815  Returns the column number (within its table) of the column making up
1816  the specified query result column.
1817  Query-result column numbers start at 0, but table columns have nonzero
1818  numbers.
1819 <synopsis>
1820 int PQftablecol(const PGresult *res,
1821                 int column_number);
1822 </synopsis>
1823 </para>
1824
1825 <para>
1826 Zero is returned if the column number is out of range,
1827 or if the specified column is not a simple reference to a table column,
1828 or when using pre-3.0 protocol.
1829 </para>
1830 </listitem>
1831 </varlistentry>
1832
1833 <varlistentry>
1834 <term><function>PQfformat</function><indexterm><primary>PQfformat</></></term>
1835 <listitem>
1836 <para>
1837  Returns the format code indicating the format of the given column.
1838  Column numbers start at 0.
1839 <synopsis>
1840 int PQfformat(const PGresult *res,
1841               int column_number);
1842 </synopsis>
1843 </para>
1844
1845 <para>
1846 Format code zero indicates textual data representation, while format
1847 code one indicates binary representation.  (Other codes are reserved
1848 for future definition.)
1849 </para>
1850 </listitem>
1851 </varlistentry>
1852
1853 <varlistentry>
1854 <term><function>PQftype</function><indexterm><primary>PQftype</></></term>
1855 <listitem>
1856 <para>
1857           Returns the data type associated with the
1858           given  column number.  The  integer  returned is the
1859           internal OID number of the type.  Column numbers start
1860           at 0.
1861 <synopsis>
1862 Oid PQftype(const PGresult *res,
1863             int column_number);
1864 </synopsis>
1865 </para>
1866
1867 <para>
1868 You can query the system table <literal>pg_type</literal> to obtain
1869 the names and properties of the various data types. The <acronym>OID</acronym>s
1870 of the built-in data types are defined in the file <filename>src/include/catalog/pg_type.h</filename>
1871 in the source tree.
1872 </para>
1873 </listitem>
1874 </varlistentry>
1875
1876 <varlistentry>
1877 <term><function>PQfmod</function><indexterm><primary>PQfmod</></></term>
1878 <listitem>
1879 <para>
1880           Returns  the type modifier of the column
1881           associated with the given column number.
1882           Column numbers start at 0.
1883 <synopsis>
1884 int PQfmod(const PGresult *res,
1885            int column_number);
1886 </synopsis>
1887 </para>
1888
1889 <para>
1890 The interpretation of modifier values is type-specific; they typically
1891 indicate precision or size limits.  The value -1 is used to indicate
1892 <quote>no information available</>.  Most data types do not use modifiers,
1893 in which case the value is always -1.
1894 </para>
1895 </listitem>
1896 </varlistentry>
1897
1898 <varlistentry>
1899 <term><function>PQfsize</function><indexterm><primary>PQfsize</></></term>
1900 <listitem>
1901 <para>
1902           Returns  the  size  in bytes of the column
1903           associated with the given column number.
1904           Column numbers start at 0.
1905 <synopsis>
1906 int PQfsize(const PGresult *res,
1907             int column_number);
1908 </synopsis>
1909 </para>
1910
1911 <para>
1912 <function>PQfsize</> returns the space allocated for this column in a database
1913 row, in other words the size of the server's internal representation
1914 of the data type.  (Accordingly, it is not really very useful to clients.)
1915 A negative value indicates the data type is variable-length.
1916 </para>
1917 </listitem>
1918 </varlistentry>
1919
1920 <varlistentry>
1921 <term><function>PQbinaryTuples</function><indexterm><primary>PQbinaryTuples</></></term>
1922 <listitem>
1923 <para>
1924 Returns 1 if the <structname>PGresult</> contains binary data
1925 and 0 if it contains text data.
1926 <synopsis>
1927 int PQbinaryTuples(const PGresult *res);
1928 </synopsis>
1929 </para>
1930
1931 <para>
1932 This function is deprecated (except for its use in connection with
1933 <command>COPY</>), because it is possible for a single
1934 <structname>PGresult</>
1935 to contain text data in some columns and binary data in others.
1936 <function>PQfformat</> is preferred.  <function>PQbinaryTuples</>
1937 returns 1 only if all columns of the result are binary (format 1).
1938 </para>
1939 </listitem>
1940 </varlistentry>
1941
1942 <varlistentry>
1943 <term><function>PQgetvalue</function><indexterm><primary>PQgetvalue</></></term>
1944 <listitem>
1945 <para>
1946             Returns a single field value of one row of a
1947             <structname>PGresult</structname>.  Row and column numbers
1948             start at 0.  The caller should not free the result
1949             directly.  It will be freed when the associated
1950             <structname>PGresult</> handle is passed to
1951             <function>PQclear</function>.
1952 <synopsis>
1953 char *PQgetvalue(const PGresult *res,
1954                  int row_number,
1955                  int column_number);
1956 </synopsis>
1957 </para>
1958
1959 <para>
1960 For data in text format, the value returned by <function>PQgetvalue</function>
1961 is a null-terminated character string  representation
1962 of the field value.  For data in binary format, the value is in the binary
1963 representation determined by the data type's <function>typsend</> and
1964 <function>typreceive</> functions.  (The value is actually followed by
1965 a zero byte in this case too, but that is not ordinarily useful, since
1966 the value is likely to contain embedded nulls.)
1967 </para>
1968
1969 <para>
1970 An empty string is returned if the field value is null.  See
1971 <function>PQgetisnull</> to distinguish null values from empty-string values.
1972 </para>
1973
1974 <para>
1975 The pointer
1976 returned  by  <function>PQgetvalue</function> points to storage that is
1977 part of the <structname>PGresult</structname> structure.  One should not modify the data it points to,
1978 and one must explicitly 
1979 copy the data into other storage if it is to
1980 be used past the lifetime of the  <structname>PGresult</structname>  structure itself.
1981 </para>
1982 </listitem>
1983 </varlistentry>
1984
1985 <varlistentry>
1986 <term><function>PQgetisnull</function><indexterm><primary>PQgetisnull</></></term>
1987 <indexterm><primary>null value</><secondary sortas="libpq">in libpq</></indexterm><listitem>
1988 <para>
1989            Tests a field for a null value.
1990            Row and column numbers start at 0.
1991 <synopsis>
1992 int PQgetisnull(const PGresult *res,
1993                 int row_number,
1994                 int column_number);
1995 </synopsis>
1996 </para>
1997
1998 <para>
1999 This function returns  1 if the field is null and 0 if
2000 it contains a non-null value.  (Note that <function>PQgetvalue</function>
2001 will return an empty string, not a null pointer, for a null field.)
2002 </para>
2003 </listitem>
2004 </varlistentry>
2005
2006 <varlistentry>
2007 <term><function>PQgetlength</function><indexterm><primary>PQgetlength</></></term>
2008 <listitem>
2009 <para>
2010           Returns the actual length of a field value in bytes.
2011           Row and column numbers start at 0.
2012 <synopsis>
2013 int PQgetlength(const PGresult *res,
2014                 int row_number,
2015                 int column_number);
2016 </synopsis>
2017 </para>
2018
2019 <para>
2020 This is the actual data length for the particular data value, that is, the
2021 size of the object pointed to by <function>PQgetvalue</function>.  For text
2022 data format this is the same as <function>strlen()</>.  For binary format
2023 this is essential information.  Note that one should <emphasis>not</> rely
2024 on <function>PQfsize</function> to obtain the actual data length.
2025 </para>
2026 </listitem>
2027 </varlistentry>
2028
2029 <varlistentry>
2030 <term><function>PQprint</function><indexterm><primary>PQprint</></></term>
2031 <listitem>
2032 <para>
2033           Prints out all the rows and,  optionally,  the
2034           column names  to  the specified output stream.
2035 <synopsis>
2036 void PQprint(FILE *fout,      /* output stream */
2037              const PGresult *res,
2038              const PQprintOpt *po);
2039
2040 typedef struct {
2041     pqbool  header;      /* print output field headings and row count */
2042     pqbool  align;       /* fill align the fields */
2043     pqbool  standard;    /* old brain dead format */
2044     pqbool  html3;       /* output HTML tables */
2045     pqbool  expanded;    /* expand tables */
2046     pqbool  pager;       /* use pager for output if needed */
2047     char    *fieldSep;   /* field separator */
2048     char    *tableOpt;   /* attributes for HTML table element */
2049     char    *caption;    /* HTML table caption */
2050     char    **fieldName; /* null-terminated array of replacement field names */
2051 } PQprintOpt;
2052 </synopsis>
2053 </para>
2054
2055 <para>
2056 This function was formerly used by <application>psql</application>
2057 to print query results, but this is no longer the case.  Note that it
2058 assumes all the data is in text format.
2059 </para>
2060 </listitem>
2061 </varlistentry>
2062 </variablelist>
2063 </sect2>
2064
2065 <sect2 id="libpq-exec-nonselect">
2066   <title>Retrieving Result Information for Other Commands</title>
2067
2068 <para>
2069 These functions are used to extract information from
2070 <structname>PGresult</structname> objects that are not <command>SELECT</>
2071 results.
2072 </para>
2073
2074 <variablelist>
2075 <varlistentry>
2076 <term><function>PQcmdStatus</function><indexterm><primary>PQcmdStatus</></></term>
2077 <listitem>
2078 <para>
2079           Returns the command status tag from the SQL command that
2080           generated the <structname>PGresult</structname>.
2081 <synopsis>
2082 char *PQcmdStatus(PGresult *res);
2083 </synopsis>
2084 </para>
2085 <para>
2086 Commonly this is just the name of the command, but it may include additional
2087 data such as the number of rows processed. The caller should
2088 not free the result directly. It will be freed when the
2089 associated <structname>PGresult</> handle is passed to
2090 <function>PQclear</function>.
2091 </para>
2092 </listitem>
2093 </varlistentry>
2094
2095 <varlistentry>
2096 <term><function>PQcmdTuples</function><indexterm><primary>PQcmdTuples</></></term>
2097 <listitem>
2098 <para>
2099           Returns the number of rows affected by the SQL command.
2100 <synopsis>
2101 char *PQcmdTuples(PGresult *res);
2102 </synopsis>
2103 </para>
2104
2105 <para>
2106           This function returns a string containing the number of rows
2107           affected by the <acronym>SQL</> statement that generated the
2108           <structname>PGresult</>. This function can only be used
2109           following the execution of an <command>INSERT</>,
2110           <command>UPDATE</>, <command>DELETE</>, <command>MOVE</>, or
2111           <command>FETCH</> statement, or an <command>EXECUTE</> of a
2112           prepared query that contains a <command>INSERT</>,
2113           <command>UPDATE</>, or <command>DELETE</> statement.  If the
2114           command that generated the <structname>PGresult</> was
2115           anything else, <function>PQcmdTuples</> returns the empty
2116           string. The caller should not free the return value
2117           directly. It will be freed when the associated
2118           <structname>PGresult</> handle is passed to
2119           <function>PQclear</function>.
2120 </para>
2121 </listitem>
2122 </varlistentry>
2123
2124 <varlistentry>
2125 <term><function>PQoidValue</function><indexterm><primary>PQoidValue</></></term>
2126 <listitem>
2127 <para>
2128           Returns the OID<indexterm><primary>OID</><secondary>in
2129           libpq</></> of the inserted row, if the <acronym>SQL</>
2130           command was an <command>INSERT</> that inserted exactly one
2131           row into a table that has OIDs, or a <command>EXECUTE</> of
2132           a prepared query containing a suitable <command>INSERT</>
2133           statement.  Otherwise, this function returns
2134           <literal>InvalidOid</literal>. This function will also
2135           return <literal>InvalidOid</literal> if the table affected
2136           by the <command>INSERT</> statement does not contain OIDs.
2137 <synopsis>
2138 Oid PQoidValue(const PGresult *res);
2139 </synopsis>
2140 </para>
2141 </listitem>
2142 </varlistentry>
2143
2144 <varlistentry>
2145 <term><function>PQoidStatus</function><indexterm><primary>PQoidStatus</></></term>
2146 <listitem>
2147 <para>
2148           Returns a string with the OID of the inserted row, if the
2149           <acronym>SQL</acronym> command was an
2150           <command>INSERT</command> that inserted exactly one row, or
2151           a <command>EXECUTE</command> of a prepared statement
2152           consisting of a suitable <command>INSERT</command>.  (The string will be
2153           <literal>0</> if the <command>INSERT</command> did not
2154           insert exactly one row, or if the target table does not have
2155           OIDs.)  If the command was not an <command>INSERT</command>,
2156           returns an empty string.
2157 <synopsis>
2158 char *PQoidStatus(const PGresult *res);
2159 </synopsis>
2160 </para>
2161
2162 <para>
2163 This function is deprecated in favor of <function>PQoidValue</function>.
2164 It is not thread-safe.
2165 </para>
2166 </listitem>
2167 </varlistentry>
2168 </variablelist>
2169
2170 </sect2>
2171
2172 <sect2 id="libpq-exec-escape-string">
2173   <title>Escaping Strings for Inclusion in SQL Commands</title>
2174
2175    <indexterm zone="libpq-exec-escape-string"><primary>PQescapeString</></>
2176    <indexterm zone="libpq-exec-escape-string"><primary>escaping strings</></>
2177
2178 <para>
2179 <function>PQescapeString</function> escapes a string for use within an SQL
2180 command.  This is useful when inserting data values as literal constants
2181 in SQL commands.  Certain characters (such as quotes and backslashes) must
2182 be escaped to prevent them from being interpreted specially by the SQL parser.
2183 <function>PQescapeString</> performs this operation.
2184 </para>
2185
2186 <tip>
2187 <para>
2188 It is especially important to do proper escaping when handling strings that
2189 were received from an untrustworthy source.  Otherwise there is a security
2190 risk: you are vulnerable to <quote>SQL injection</> attacks wherein unwanted
2191 SQL commands are fed to your database.
2192 </para>
2193 </tip>
2194
2195 <para>
2196 Note that it is not necessary nor correct to do escaping when a data
2197 value is passed as a separate parameter in <function>PQexecParams</> or
2198 its sibling routines.
2199
2200 <synopsis>
2201 size_t PQescapeString (char *to, const char *from, size_t length);
2202 </synopsis>
2203 </para>
2204
2205 <para>
2206 The parameter <parameter>from</> points to the first character of the string
2207 that is to be escaped, and the <parameter>length</> parameter gives the
2208 number of characters in this string.  A terminating zero byte is not
2209 required, and should not be counted in <parameter>length</>.  (If
2210 a terminating zero byte is found before <parameter>length</> bytes are
2211 processed, <function>PQescapeString</> stops at the zero; the behavior
2212 is thus rather like <function>strncpy</>.)
2213 <parameter>to</> shall point to a
2214 buffer that is able to hold at least one more character than twice
2215 the value of <parameter>length</>, otherwise the behavior is
2216 undefined.  A call to <function>PQescapeString</> writes an escaped
2217 version of the <parameter>from</> string to the <parameter>to</>
2218 buffer, replacing special characters so that they cannot cause any
2219 harm, and adding a terminating zero byte.  The single quotes that
2220 must surround <productname>PostgreSQL</> string literals are not
2221 included in the result string; they should be provided in the SQL
2222 command that the result is inserted into.
2223 </para>
2224 <para>
2225 <function>PQescapeString</> returns the number of characters written
2226 to <parameter>to</>, not including the terminating zero byte.
2227 </para>
2228 <para>
2229 Behavior is undefined if the <parameter>to</> and <parameter>from</>
2230 strings overlap.
2231 </para>
2232 </sect2>
2233
2234
2235  <sect2 id="libpq-exec-escape-bytea">
2236   <title>Escaping Binary Strings for Inclusion in SQL Commands</title>
2237
2238   <indexterm zone="libpq-exec-escape-bytea">
2239    <primary>bytea</>
2240    <secondary sortas="libpq">in libpq</>
2241   </indexterm>
2242
2243   <variablelist>
2244   <varlistentry>
2245   <term><function>PQescapeBytea</function><indexterm><primary>PQescapeBytea</></></term>
2246   <listitem>
2247   <para>
2248    Escapes binary data for use within an SQL command with the type
2249    <type>bytea</type>.  As with <function>PQescapeString</function>,
2250    this is only used when inserting data directly into an SQL command string.
2251 <synopsis>
2252 unsigned char *PQescapeBytea(const unsigned char *from,
2253                              size_t from_length,
2254                              size_t *to_length);
2255 </synopsis>
2256 </para>
2257
2258 <para>
2259    Certain byte values <emphasis>must</emphasis> be escaped (but all
2260    byte values <emphasis>can</emphasis> be escaped) when used as part
2261    of a <type>bytea</type> literal in an <acronym>SQL</acronym>
2262    statement. In general, to escape a byte, it is converted into the
2263    three digit octal number equal to the octet value, and preceded by
2264    two backslashes. The single quote (<literal>'</>) and backslash
2265    (<literal>\</>) characters have special alternative escape
2266    sequences. See <xref linkend="datatype-binary"> for more
2267    information. <function>PQescapeBytea</function> performs this
2268    operation, escaping only the minimally required bytes.
2269   </para>
2270
2271   <para>
2272    The <parameter>from</parameter> parameter points to the first
2273    byte of the string that is to be escaped, and the
2274    <parameter>from_length</parameter> parameter gives the number of
2275    bytes in this binary string.  (A terminating zero byte is
2276    neither necessary nor counted.)  The <parameter>to_length</parameter>
2277    parameter points to a variable that will hold the resultant
2278    escaped string length. The result string length includes the terminating
2279    zero byte of the result.
2280   </para>
2281
2282   <para>
2283    <function>PQescapeBytea</> returns an escaped version of the
2284    <parameter>from</parameter> parameter binary string in memory
2285    allocated with <function>malloc()</> (a null pointer is returned if
2286    memory could not be allocated).  This memory must be freed using
2287    <function>PQfreemem</> when the result is no longer needed.  The
2288    return string has all special characters replaced so that they can
2289    be properly processed by the <productname>PostgreSQL</productname>
2290    string literal parser, and the <type>bytea</type> input function. A
2291    terminating zero byte is also added.  The single quotes that must
2292    surround <productname>PostgreSQL</productname> string literals are
2293    not part of the result string.
2294   </para>
2295   </listitem>
2296   </varlistentry>
2297
2298   <varlistentry>
2299   <term><function>PQunescapeBytea</function><indexterm><primary>PQunescapeBytea</></></term>
2300   <listitem>
2301   <para>
2302    Converts an escaped string representation of binary data into binary
2303    data &mdash; the reverse of <function>PQescapeBytea</function>.
2304    This is needed when retrieving <type>bytea</type> data in text format,
2305    but not when retrieving it in binary format.
2306
2307 <synopsis>
2308 unsigned char *PQunescapeBytea(const unsigned char *from, size_t *to_length);
2309 </synopsis>
2310 </para>
2311
2312 <para>
2313    The <parameter>from</parameter> parameter points to an escaped string
2314    such as might be returned by <function>PQgetvalue</function> when applied to a
2315    <type>bytea</type> column. <function>PQunescapeBytea</function> converts
2316    this string representation into its binary representation.
2317    It returns a pointer to a buffer allocated with
2318    <function>malloc()</function>, or null on error, and puts the size of
2319    the buffer in <parameter>to_length</parameter>. The result must be
2320    freed using <function>PQfreemem</> when it is no longer needed.
2321   </para>
2322   </listitem>
2323   </varlistentry>
2324
2325   <varlistentry>
2326   <term><function>PQfreemem</function><indexterm><primary>PQfreemem</></></term>
2327   <listitem>
2328   <para>
2329    Frees memory allocated by <application>libpq</>.
2330 <synopsis>
2331 void PQfreemem(void *ptr);
2332 </synopsis>
2333 </para>
2334
2335 <para>
2336    Frees memory allocated by <application>libpq</>, particularly
2337    <function>PQescapeBytea</function>,
2338    <function>PQunescapeBytea</function>,
2339    and <function>PQnotifies</function>.
2340    It is needed by Microsoft Windows, which cannot free memory across
2341    DLLs, unless multithreaded DLLs (<option>/MD</option> in VC6) are used.
2342    On other platforms, this function is the same as the standard library function <function>free()</>.
2343   </para>
2344   </listitem>
2345   </varlistentry>
2346   </variablelist>
2347    
2348  </sect2>
2349 </sect1>
2350
2351 <sect1 id="libpq-async">
2352 <title>Asynchronous Command Processing</title>
2353
2354   <indexterm zone="libpq-async"><primary>nonblocking connection</></>
2355
2356 <para>
2357 The <function>PQexec</function> function is adequate for submitting commands in
2358 normal, synchronous
2359 applications.  It has a couple of deficiencies, however, that can be of importance to some users:
2360
2361 <itemizedlist>
2362 <listitem>
2363 <para>
2364 <function>PQexec</function> waits for the command to be completed.  The application may have other
2365 work to do (such as maintaining a user interface), in which case it won't
2366 want to block waiting for the response.
2367 </para>
2368 </listitem>
2369 <listitem>
2370 <para>
2371 Since the execution of the client application is suspended while it
2372 waits for the result, it is hard for the application to decide that it
2373 would like to try to cancel the ongoing command.  (It can be done from
2374 a signal handler, but not otherwise.)
2375 </para>
2376 </listitem>
2377 <listitem>
2378 <para>
2379 <function>PQexec</function> can return only one <structname>PGresult</structname> structure.  If the submitted command
2380 string contains multiple <acronym>SQL</acronym> commands, all but the last <structname>PGresult</structname> are
2381 discarded by <function>PQexec</function>.
2382 </para>
2383 </listitem>
2384 </itemizedlist>
2385 </para>
2386
2387 <para>
2388 Applications that do not like these limitations can instead use the
2389 underlying functions that <function>PQexec</function> is built from:
2390 <function>PQsendQuery</function> and <function>PQgetResult</function>.
2391 There are also
2392 <function>PQsendQueryParams</function>,
2393 <function>PQsendPrepare</function>, and
2394 <function>PQsendQueryPrepared</function>,
2395 which can be used with <function>PQgetResult</function> to duplicate the
2396 functionality of
2397 <function>PQexecParams</function>,
2398 <function>PQprepare</function>, and
2399 <function>PQexecPrepared</function>
2400 respectively.
2401
2402 <variablelist>
2403 <varlistentry>
2404 <term><function>PQsendQuery</function><indexterm><primary>PQsendQuery</></></term>
2405 <listitem>
2406 <para>
2407           Submits a command to the server without
2408           waiting for the result(s).  1 is returned if the command was
2409           successfully dispatched and 0 if not (in which case, use
2410           <function>PQerrorMessage</> to get more information about the failure).
2411 <synopsis>
2412 int PQsendQuery(PGconn *conn, const char *command);
2413 </synopsis>
2414
2415           After successfully calling <function>PQsendQuery</function>, call
2416           <function>PQgetResult</function> one or more
2417           times to obtain the results.  <function>PQsendQuery</function> may not be called
2418           again (on the same connection) until <function>PQgetResult</function> has returned a null pointer,
2419           indicating that the command is done.
2420 </para>
2421 </listitem>
2422 </varlistentry>
2423
2424 <varlistentry>
2425 <term><function>PQsendQueryParams</function><indexterm><primary>PQsendQueryParams</></></term>
2426 <listitem>
2427 <para>
2428           Submits a command and separate parameters to the server without
2429           waiting for the result(s).
2430 <synopsis>
2431 int PQsendQueryParams(PGconn *conn,
2432                       const char *command,
2433                       int nParams,
2434                       const Oid *paramTypes,
2435                       const char * const *paramValues,
2436                       const int *paramLengths,
2437                       const int *paramFormats,
2438                       int resultFormat);
2439 </synopsis>
2440
2441         This is equivalent to <function>PQsendQuery</function> except that
2442         query parameters can be specified separately from the query string.
2443         The function's parameters are handled identically to
2444         <function>PQexecParams</function>.  Like
2445         <function>PQexecParams</function>, it will not work on 2.0-protocol
2446         connections, and it allows only one command in the query string.
2447 </para>
2448 </listitem>
2449 </varlistentry>
2450
2451 <varlistentry>
2452 <term><function>PQsendPrepare</><indexterm><primary>PQsendPrepare</></></term>
2453 <listitem>
2454 <para>
2455         Sends a request to create a prepared statement with the given
2456         parameters, without waiting for completion.
2457 <synopsis>
2458 int PQsendPrepare(PGconn *conn,
2459                   const char *stmtName,
2460                   const char *query,
2461                   int nParams,
2462                   const Oid *paramTypes);
2463 </synopsis>
2464
2465         This is an asynchronous version of <function>PQprepare</>: it
2466         returns 1 if it was able to dispatch the request, and 0 if not.
2467         After a successful call, call <function>PQgetResult</function>
2468         to determine whether the server successfully created the prepared
2469         statement.
2470         The function's parameters are handled identically to
2471         <function>PQprepare</function>.  Like
2472         <function>PQprepare</function>, it will not work on 2.0-protocol
2473         connections.
2474 </para>
2475 </listitem>
2476 </varlistentry>
2477
2478 <varlistentry>
2479 <term><function>PQsendQueryPrepared</function><indexterm><primary>PQsendQueryPrepared</></></term>
2480 <listitem>
2481 <para>
2482           Sends a request to execute a prepared statement with given
2483           parameters, without waiting for the result(s).
2484 <synopsis>
2485 int PQsendQueryPrepared(PGconn *conn,
2486                         const char *stmtName,
2487                         int nParams,
2488                         const char * const *paramValues,
2489                         const int *paramLengths,
2490                         const int *paramFormats,
2491                         int resultFormat);
2492 </synopsis>
2493
2494         This is similar to <function>PQsendQueryParams</function>, but the
2495         command to be executed is specified by naming a previously-prepared
2496         statement, instead of giving a query string.
2497         The function's parameters are handled identically to
2498         <function>PQexecPrepared</function>.  Like
2499         <function>PQexecPrepared</function>, it will not work on 2.0-protocol
2500         connections.
2501 </para>
2502 </listitem>
2503 </varlistentry>
2504
2505 <varlistentry>
2506 <term><function>PQgetResult</function><indexterm><primary>PQgetResult</></></term>
2507 <listitem>
2508 <para>
2509           Waits for the next result from a prior
2510           <function>PQsendQuery</function>,
2511           <function>PQsendQueryParams</function>,
2512           <function>PQsendPrepare</function>, or
2513           <function>PQsendQueryPrepared</function> call,
2514           and returns it.  A null pointer is returned when the command is complete
2515           and there will be no more results.
2516 <synopsis>
2517 PGresult *PQgetResult(PGconn *conn);
2518 </synopsis>
2519 </para>
2520
2521 <para>
2522           <function>PQgetResult</function> must be called repeatedly until it returns a null pointer,
2523           indicating that the command is done.  (If called when no command is
2524           active, <function>PQgetResult</function> will just return a null pointer at once.)
2525           Each non-null result from <function>PQgetResult</function> should be processed using
2526           the same <structname>PGresult</> accessor functions previously described.
2527           Don't forget to free each result object with <function>PQclear</function> when done with it.
2528           Note that <function>PQgetResult</function> will block only if a command is active and the
2529           necessary response data has not yet been read by <function>PQconsumeInput</function>.
2530 </para>
2531 </listitem>
2532 </varlistentry>
2533 </variablelist>
2534 </para>
2535
2536 <para>
2537 Using <function>PQsendQuery</function> and <function>PQgetResult</function>
2538 solves one of <function>PQexec</function>'s problems:
2539 If a command string contains multiple <acronym>SQL</acronym> commands, the results of those
2540 commands can be obtained individually.  (This allows a simple form of
2541 overlapped processing, by the way: the client can be handling the
2542 results of one command while the server is still working on later
2543 queries in the same command string.)  However, calling <function>PQgetResult</function> will
2544 still cause the client to block until the server completes the
2545 next <acronym>SQL</acronym> command.  This can be avoided by proper use of two
2546 more functions:
2547
2548 <variablelist>
2549 <varlistentry>
2550 <term><function>PQconsumeInput</function><indexterm><primary>PQconsumeInput</></></term>
2551 <listitem>
2552 <para>
2553           If input is available from the server, consume it.
2554 <synopsis>
2555 int PQconsumeInput(PGconn *conn);
2556 </synopsis>
2557 </para>
2558
2559 <para>
2560 <function>PQconsumeInput</function> normally returns 1 indicating <quote>no error</quote>,
2561 but returns 0 if there was some kind of trouble (in which case
2562 <function>PQerrorMessage</function> can be consulted).  Note that the result
2563 does not say 
2564 whether any input data was actually collected. After calling
2565 <function>PQconsumeInput</function>, the application may check
2566 <function>PQisBusy</function> and/or <function>PQnotifies</function> to see if
2567 their state has changed.
2568 </para>
2569 <para>
2570 <function>PQconsumeInput</function> may be called even if the application is not
2571 prepared to deal with a result or notification just yet.  The
2572 function will read available data and save it in a buffer, thereby
2573 causing a <function>select()</function> read-ready indication to go away.  The
2574 application can thus use <function>PQconsumeInput</function> to clear the
2575 <function>select()</function> condition immediately, and then examine the results at leisure.
2576 </para>
2577 </listitem>
2578 </varlistentry>
2579
2580 <varlistentry>
2581 <term><function>PQisBusy</function><indexterm><primary>PQisBusy</></></term>
2582 <listitem>
2583 <para>
2584 Returns 1 if a command is busy, that is, <function>PQgetResult</function> would block
2585 waiting for input.  A 0 return indicates that <function>PQgetResult</function> can
2586 be called with assurance of not blocking.
2587 <synopsis>
2588 int PQisBusy(PGconn *conn);
2589 </synopsis>
2590 </para>
2591
2592 <para>
2593 <function>PQisBusy</function> will not itself attempt to read data from the server;
2594 therefore <function>PQconsumeInput</function> must be invoked first, or the busy
2595 state will never end.
2596 </para>
2597 </listitem>
2598 </varlistentry>
2599 </variablelist>
2600 </para>
2601
2602 <para>
2603 A typical application using these functions will have a main loop that uses
2604 <function>select()</function> or <function>poll()</> to wait for all the
2605 conditions that it must
2606 respond to.  One of the conditions will be input available from the server,
2607 which in terms of <function>select()</function> means readable data on the file
2608 descriptor identified by <function>PQsocket</function>.
2609 When the main loop detects input ready, it should call
2610 <function>PQconsumeInput</function> to read the input.  It can then call
2611 <function>PQisBusy</function>, followed by <function>PQgetResult</function>
2612 if <function>PQisBusy</function> returns false (0).  It can also call
2613 <function>PQnotifies</function> to detect <command>NOTIFY</> messages (see <xref linkend="libpq-notify">).
2614 </para>
2615
2616 <para>
2617 A client that uses
2618 <function>PQsendQuery</function>/<function>PQgetResult</function> can
2619 also attempt to cancel a command that is still being processed by the
2620 server; see <xref linkend="libpq-cancel">.  But regardless of the return value
2621 of <function>PQcancel</function>, the application must continue with the
2622 normal result-reading sequence using <function>PQgetResult</function>.
2623 A successful cancellation will simply cause the command to terminate
2624 sooner than it would have otherwise.
2625 </para>
2626
2627 <para>
2628 By using the functions described above, it is possible to avoid blocking
2629 while waiting for input from the database server.  However, it is still
2630 possible that the application will block waiting to send output to the
2631 server.  This is relatively uncommon but can happen if very long SQL commands
2632 or data values are sent.  (It is much more probable if the application
2633 sends data via <command>COPY IN</command>, however.)  To prevent this possibility and achieve
2634 completely nonblocking database operation, the following additional
2635 functions may be used.
2636
2637 <variablelist>
2638 <varlistentry>
2639  <term><function>PQsetnonblocking</function><indexterm><primary>PQsetnonblocking</></></term>
2640  <listitem>
2641    <para>
2642     Sets the nonblocking status of the connection.
2643 <synopsis>
2644 int PQsetnonblocking(PGconn *conn, int arg);
2645 </synopsis>
2646 </para>
2647
2648 <para>
2649     Sets the state of the connection to nonblocking if
2650     <parameter>arg</parameter> is 1, or
2651     blocking if <parameter>arg</parameter> is 0.  Returns 0 if OK, -1 if error.
2652    </para>
2653    <para>
2654     In the nonblocking state, calls to
2655     <function>PQsendQuery</function>,
2656     <function>PQputline</function>, <function>PQputnbytes</function>,
2657     and <function>PQendcopy</function>
2658     will not block but instead return an error if they need to be called
2659     again.
2660    </para>
2661    <para>
2662     Note that <function>PQexec</function> does not honor nonblocking mode;
2663     if it is called, it will act in blocking fashion anyway.
2664    </para>
2665  </listitem>
2666 </varlistentry>
2667
2668 <varlistentry>
2669 <term><function>PQisnonblocking</function><indexterm><primary>PQisnonblocking</></></term>
2670 <listitem>
2671 <para>
2672        Returns the blocking status of the database connection.
2673 <synopsis>
2674 int PQisnonblocking(const PGconn *conn);
2675 </synopsis>
2676 </para>
2677
2678 <para>
2679        Returns 1 if the connection is set to nonblocking mode and
2680        0 if blocking.
2681 </para>
2682 </listitem>
2683 </varlistentry>
2684
2685 <varlistentry>
2686 <term><function>PQflush</function><indexterm><primary>PQflush</></></term>
2687 <listitem>
2688 <para>
2689 Attempts to flush any queued output data to the server.
2690 Returns 0 if successful (or if the send queue is empty), -1 if it failed for
2691 some reason, or 1 if it was unable to send all the data in the send queue yet
2692 (this case can only occur if the connection is nonblocking).
2693 <synopsis>
2694 int PQflush(PGconn *conn);
2695 </synopsis>
2696 </para>
2697 </listitem>
2698 </varlistentry>
2699 </variablelist>
2700 </para>
2701
2702 <para>
2703 After sending any command or data on a nonblocking connection, call
2704 <function>PQflush</function>.  If it returns 1, wait for the socket to be
2705 write-ready and call it again; repeat until it returns 0.  Once
2706 <function>PQflush</function> returns 0, wait for the socket to be read-ready
2707 and then read the response as described above.
2708 </para>
2709
2710 </sect1>
2711
2712 <sect1 id="libpq-cancel">
2713 <title>Cancelling Queries in Progress</title>
2714
2715 <indexterm zone="libpq-cancel"><primary>canceling</><secondary>SQL command</></>
2716
2717 <para>
2718 A client application can request cancellation of
2719 a command that is still being processed by the
2720 server, using the functions described in this section.
2721
2722 <variablelist>
2723 <varlistentry>
2724 <term><function>PQgetCancel</function><indexterm><primary>PQgetCancel</></></term>
2725 <listitem>
2726 <para>
2727           Creates a data structure containing the information needed to cancel
2728           a command issued through a particular database connection.
2729 <synopsis>
2730 PGcancel *PQgetCancel(PGconn *conn);
2731 </synopsis>
2732 </para>
2733
2734 <para>
2735 <function>PQgetCancel</function> creates a 
2736 <structname>PGcancel</><indexterm><primary>PGcancel</></> object given
2737 a <structname>PGconn</> connection object.  It will return NULL if the
2738 given <parameter>conn</> is NULL or an invalid connection.  The
2739 <structname>PGcancel</> object is an opaque structure that is not meant
2740 to be accessed directly by the application; it can only be passed to
2741 <function>PQcancel</function> or <function>PQfreeCancel</function>.
2742 </para>
2743 </listitem>
2744 </varlistentry>
2745
2746 <varlistentry>
2747 <term><function>PQfreeCancel</function><indexterm><primary>PQfreeCancel</></></term>
2748 <listitem>
2749 <para>
2750           Frees a data structure created by <function>PQgetCancel</function>.
2751 <synopsis>
2752 void PQfreeCancel(PGcancel *cancel);
2753 </synopsis>
2754 </para>
2755
2756 <para>
2757 <function>PQfreeCancel</function> frees a data object previously created
2758 by <function>PQgetCancel</function>.
2759 </para>
2760 </listitem>
2761 </varlistentry>
2762
2763 <varlistentry>
2764 <term><function>PQcancel</function><indexterm><primary>PQcancel</></></term>
2765 <listitem>
2766 <para>
2767           Requests that the server abandon
2768           processing of the current command.
2769 <synopsis>
2770 int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize);
2771 </synopsis>
2772 </para>
2773
2774 <para>
2775 The return value is 1 if the cancel request was successfully
2776 dispatched and 0 if not.  If not, <parameter>errbuf</> is filled with an error
2777 message explaining why not.  <parameter>errbuf</> must be a char array of size
2778 <parameter>errbufsize</> (the recommended size is 256 bytes).
2779 </para>
2780
2781 <para>
2782 Successful dispatch is no guarantee that the request will have any effect,
2783 however.  If the cancellation is effective, the current command will terminate
2784 early and return an error result.  If the cancellation fails (say, because the
2785 server was already done processing the command), then there will be no visible
2786 result at all.
2787 </para>
2788
2789 <para>
2790 <function>PQcancel</function> can safely be invoked from a signal handler,
2791 if the <parameter>errbuf</> is a local variable in the signal handler.  The
2792 <structname>PGcancel</> object is read-only as far as
2793 <function>PQcancel</function> is concerned, so it can also be invoked from a
2794 thread that is separate from the one manipulating the <structname>PGconn</>
2795 object.
2796 </para>
2797 </listitem>
2798 </varlistentry>
2799 </variablelist>
2800
2801 <variablelist>
2802 <varlistentry>
2803 <term><function>PQrequestCancel</function><indexterm><primary>PQrequestCancel</></></term>
2804 <listitem>
2805 <para>
2806           Requests that the server abandon
2807           processing of the current command.
2808 <synopsis>
2809 int PQrequestCancel(PGconn *conn);
2810 </synopsis>
2811 </para>
2812
2813 <para>
2814 <function>PQrequestCancel</function> is a deprecated variant of
2815 <function>PQcancel</function>.  It operates directly on the
2816 <structname>PGconn</> object, and in case of failure stores the
2817 error message in the <structname>PGconn</> object (whence it can be
2818 retrieved by <function>PQerrorMessage</function>).  Although the
2819 functionality is the same, this approach creates hazards for multiple-thread
2820 programs and signal handlers, since it is possible that overwriting the
2821 <structname>PGconn</>'s error message will mess up the operation currently
2822 in progress on the connection.
2823 </para>
2824 </listitem>
2825 </varlistentry>
2826 </variablelist>
2827 </para>
2828
2829 </sect1>
2830
2831 <sect1 id="libpq-fastpath">
2832 <title>The Fast-Path Interface</title>
2833
2834 <indexterm zone="libpq-fastpath"><primary>fast path</></>
2835
2836 <para>
2837 <productname>PostgreSQL</productname> provides a fast-path interface to send
2838 simple function calls to the server.
2839 </para>
2840
2841 <tip>
2842 <para>
2843 This interface is somewhat obsolete, as one may achieve similar performance
2844 and greater functionality by setting up a prepared statement to define the
2845 function call.  Then, executing the statement with binary transmission of
2846 parameters and results substitutes for a fast-path function call.
2847 </para>
2848 </tip>
2849
2850 <para>
2851 The function <function>PQfn</function><indexterm><primary>PQfn</></>
2852 requests execution of a server function via the fast-path interface:
2853 <synopsis>
2854 PGresult *PQfn(PGconn *conn,
2855                int fnid,
2856                int *result_buf,
2857                int *result_len,
2858                int result_is_int,
2859                const PQArgBlock *args,
2860                int nargs);
2861
2862 typedef struct {
2863     int len;
2864     int isint;
2865     union {
2866         int *ptr;
2867         int integer;
2868     } u;
2869 } PQArgBlock;
2870 </synopsis>
2871 </para>
2872
2873 <para>
2874      The <parameter>fnid</> argument is the OID of the function to be
2875      executed.  <parameter>args</> and <parameter>nargs</> define the
2876      parameters to be passed to the function; they must match the declared
2877      function argument list.  When the <parameter>isint</> field of a
2878      parameter
2879      structure is true,
2880      the <parameter>u.integer</> value is sent to the server as an integer
2881      of the indicated length (this must be 1, 2, or 4 bytes); proper
2882      byte-swapping occurs.  When <parameter>isint</> is false, the
2883      indicated number of bytes at <parameter>*u.ptr</> are sent with no
2884      processing; the data must be in the format expected by the server for
2885      binary transmission of the function's argument data type.
2886      <parameter>result_buf</parameter> is the buffer in which
2887      to place the return value.  The caller must  have  allocated
2888      sufficient space to store the return value.  (There is no check!)
2889      The actual result length will be returned in the integer pointed
2890      to  by  <parameter>result_len</parameter>.
2891      If a 1, 2, or 4-byte integer result is expected, set
2892      <parameter>result_is_int</parameter> to 1, otherwise set it to 0.
2893      Setting <parameter>result_is_int</parameter> to 1
2894      causes <application>libpq</> to byte-swap the value if necessary, so that
2895      it is
2896      delivered as a proper <type>int</type> value for the client machine.  When
2897      <parameter>result_is_int</> is 0, the binary-format byte string sent by
2898      the server is returned unmodified.
2899 </para>
2900
2901 <para>
2902 <function>PQfn</function> always returns a valid <structname>PGresult</structname> pointer. The result status
2903 should be checked before the result is used.   The
2904 caller is responsible for  freeing  the  <structname>PGresult</structname>  with
2905 <function>PQclear</function> when it is no longer needed.
2906 </para>
2907
2908 <para>
2909 Note that it is not possible to handle null arguments, null results, nor
2910 set-valued results when using this interface.
2911 </para>
2912
2913 </sect1>
2914
2915 <sect1 id="libpq-notify">
2916 <title>Asynchronous Notification</title>
2917
2918   <indexterm zone="libpq-notify">
2919    <primary>NOTIFY</primary>
2920    <secondary>in libpq</secondary>
2921   </indexterm>
2922
2923 <para>
2924 <productname>PostgreSQL</productname> offers asynchronous notification via the
2925 <command>LISTEN</command> and <command>NOTIFY</command> commands.  A client session registers its interest in a particular
2926 notification condition with the <command>LISTEN</command> command (and can stop listening
2927 with the <command>UNLISTEN</command> command).  All sessions listening on a
2928 particular condition will be notified asynchronously when a <command>NOTIFY</command> command with that
2929 condition name is executed by any session.  No additional information is
2930 passed from the notifier to the listener.  Thus, typically, any actual data
2931 that needs to be communicated is transferred through a database table.
2932 Commonly, the condition name is the same as the associated table, but it is
2933 not necessary for there to be any associated table.
2934 </para>
2935
2936 <para>
2937 <application>libpq</application> applications submit
2938 <command>LISTEN</command> and <command>UNLISTEN</command> commands as
2939 ordinary SQL commands.  The arrival of <command>NOTIFY</command>
2940 messages can subsequently be detected by calling
2941 <function>PQnotifies</function>.<indexterm><primary>PQnotifies</></>
2942 </para>
2943
2944 <para>
2945 The function <function>PQnotifies</function>
2946           returns  the next notification from a list of unhandled
2947           notification messages received from the server.  It returns a null pointer if
2948           there are no pending notifications.  Once a notification is
2949           returned from <function>PQnotifies</>, it is considered handled and will be
2950           removed from the list of notifications.
2951 <synopsis>
2952 PGnotify *PQnotifies(PGconn *conn);
2953
2954 typedef struct pgNotify {
2955     char *relname;              /* notification condition name */
2956     int  be_pid;                /* process ID of server process */
2957     char *extra;                /* notification parameter */
2958 } PGnotify;
2959 </synopsis>
2960 After processing a <structname>PGnotify</structname> object returned by
2961 <function>PQnotifies</function>, be sure to free it with
2962 <function>PQfreemem</function>.  It is sufficient to free the
2963 <structname>PGnotify</structname> pointer; the
2964 <structfield>relname</structfield> and <structfield>extra</structfield> fields
2965 do not represent separate allocations.
2966 (At present, the <structfield>extra</structfield> field is unused and will
2967 always point to an empty string.)
2968 </para>
2969
2970 <note>
2971 <para>
2972  In <productname>PostgreSQL</productname> 6.4 and later,
2973  the <structfield>be_pid</structfield> is that of the notifying server process,
2974  whereas in earlier versions it was always the <acronym>PID</acronym> of your own server process.
2975 </para>
2976 </note>
2977
2978 <para>
2979 <xref linkend="libpq-example-2"> gives a sample program that illustrates the use
2980 of asynchronous notification.
2981 </para>
2982
2983 <para>
2984 <function>PQnotifies</function> does not actually read data from the server; it just
2985 returns messages previously absorbed by another <application>libpq</application>
2986 function.  In prior releases of <application>libpq</application>, the only way
2987 to ensure timely receipt of <command>NOTIFY</> messages was to constantly submit commands,
2988 even empty ones, and then check <function>PQnotifies</function> after each
2989 <function>PQexec</function>.  While this still works, it is
2990 deprecated as a waste of processing power.
2991 </para>
2992
2993 <para>
2994 A better way to check for <command>NOTIFY</>
2995 messages when you have no useful commands to execute is to call
2996 <function>PQconsumeInput</function>, then check
2997 <function>PQnotifies</function>.
2998 You can use <function>select()</function> to wait for data to
2999 arrive from the server, thereby using no <acronym>CPU</acronym> power unless there is something
3000 to do.  (See <function>PQsocket</function> to obtain the file descriptor
3001 number to use with <function>select()</function>.)
3002 Note that this will work OK whether you submit commands with
3003 <function>PQsendQuery</function>/<function>PQgetResult</function> or simply
3004 use <function>PQexec</function>.  You should, however, remember to
3005 check <function>PQnotifies</function> after each
3006 <function>PQgetResult</function> or <function>PQexec</function>, to see
3007 if any notifications came in during the processing of the command.
3008 </para>
3009
3010 </sect1>
3011
3012 <sect1 id="libpq-copy">
3013 <title>Functions Associated with the <command>COPY</command> Command</title>
3014
3015 <indexterm zone="libpq-copy">
3016  <primary>COPY</primary>
3017  <secondary>with libpq</secondary>
3018 </indexterm>
3019
3020 <para>
3021  The <command>COPY</command> command in <productname>PostgreSQL</productname>
3022  has options to read from or write to the network connection used by
3023  <application>libpq</application>.  The functions described in this section
3024  allow applications to take advantage of this capability by supplying or
3025  consuming copied data.
3026 </para>
3027
3028 <para>
3029  The overall process is that the application first issues the SQL
3030  <command>COPY</command> command via <function>PQexec</function> or one
3031  of the equivalent functions.  The response to this (if there is no error
3032  in the command) will be a <structname>PGresult</> object bearing a status
3033  code of <literal>PGRES_COPY_OUT</literal> or <literal>PGRES_COPY_IN</literal>
3034  (depending on the specified copy direction).  The application should then
3035  use the functions of this section to receive or transmit data rows.
3036  When the data transfer is complete, another <structname>PGresult</> object
3037  is returned to indicate success or failure of the transfer.  Its status
3038  will be <literal>PGRES_COMMAND_OK</literal> for success or
3039  <literal>PGRES_FATAL_ERROR</literal> if some problem was encountered.
3040  At this point further SQL commands may be issued via
3041  <function>PQexec</function>.  (It is not possible to execute other SQL
3042  commands using the same connection while the <command>COPY</command>
3043  operation is in progress.)
3044 </para>
3045
3046 <para>
3047  If a <command>COPY</command> command is issued via
3048  <function>PQexec</function> in a string that could contain additional
3049  commands, the application must continue fetching results via
3050  <function>PQgetResult</> after completing the <command>COPY</command>
3051  sequence.  Only when <function>PQgetResult</> returns <symbol>NULL</symbol> is it certain
3052  that the <function>PQexec</function> command string is done and it is
3053  safe to issue more commands.
3054 </para>
3055
3056 <para>
3057  The functions of this section should be executed only after obtaining a
3058  result status of <literal>PGRES_COPY_OUT</literal> or
3059  <literal>PGRES_COPY_IN</literal> from <function>PQexec</function> or
3060  <function>PQgetResult</function>.
3061 </para>
3062
3063 <para>
3064  A <structname>PGresult</> object bearing one of these status values
3065  carries some additional data about the <command>COPY</command> operation that
3066  is starting.  This additional data is available using functions that are
3067  also used in connection with query results:
3068
3069 <variablelist>
3070 <varlistentry>
3071 <term><function>PQnfields</function><indexterm><primary>PQnfields</><secondary>with COPY</></></term>
3072 <listitem>
3073 <para>
3074           Returns the number of columns (fields) to be copied.
3075 </para>
3076 </listitem>
3077 </varlistentry>
3078
3079 <varlistentry>
3080 <term><function>PQbinaryTuples</function><indexterm><primary>PQbinaryTuples</><secondary>with COPY</></></term>
3081 <listitem>
3082 <para>
3083                 0 indicates the overall copy format is textual (rows
3084                 separated by newlines, columns separated by separator
3085                 characters, etc).
3086                 1 indicates the overall copy format is binary.
3087                 See <xref linkend="sql-copy" endterm="sql-copy-title">
3088                 for more information.
3089 </para>
3090 </listitem>
3091 </varlistentry>
3092
3093 <varlistentry>
3094 <term><function>PQfformat</function><indexterm><primary>PQfformat</><secondary>with COPY</></></term>
3095 <listitem>
3096 <para>
3097           Returns the format code (0 for text, 1 for binary) associated
3098           with each column of the copy operation.  The per-column format
3099           codes will always be zero when the overall copy format is textual,
3100           but the binary format can support both text and binary columns.
3101           (However, as of the current implementation of <command>COPY</>,
3102           only binary columns appear in a binary copy; so the per-column
3103           formats always match the overall format at present.)
3104 </para>
3105 </listitem>
3106 </varlistentry>
3107 </variablelist>
3108 </para>
3109
3110 <note>
3111 <para>
3112 These additional data values are only available when using protocol 3.0.
3113 When using protocol 2.0, all these functions will return 0.
3114 </para>
3115 </note>
3116
3117 <sect2 id="libpq-copy-send">
3118   <title>Functions for Sending <command>COPY</command> Data</title>
3119
3120 <para>
3121  These functions are used to send data during <literal>COPY FROM STDIN</>.
3122  They will fail if called when the connection is not in <literal>COPY_IN</>
3123  state.
3124 </para>
3125
3126 <variablelist>
3127 <varlistentry>
3128 <term><function>PQputCopyData</function><indexterm><primary>PQputCopyData</></></term>
3129 <listitem>
3130 <para>
3131  Sends data to the server during <literal>COPY_IN</> state.
3132 <synopsis>
3133 int PQputCopyData(PGconn *conn,
3134                   const char *buffer,
3135                   int nbytes);
3136 </synopsis>
3137 </para>
3138
3139 <para>
3140 Transmits the <command>COPY</command> data in the specified <parameter>buffer</>, of length
3141 <parameter>nbytes</>, to the server.  The result is 1 if the data was sent,
3142 zero if it was not sent because the attempt would block (this case is only
3143 possible if the connection is in nonblocking mode), or -1 if an error occurred.
3144 (Use <function>PQerrorMessage</function> to retrieve details if the return
3145 value is -1.  If the value is zero, wait for write-ready and try again.)
3146 </para>
3147
3148 <para>
3149 The application may divide the <command>COPY</command> data stream into buffer loads of any
3150 convenient size.  Buffer-load boundaries have no semantic significance when
3151 sending.  The contents of the data stream must match the data format expected
3152 by the <command>COPY</> command; see
3153 <xref linkend="sql-copy" endterm="sql-copy-title"> for details.
3154 </para>
3155 </listitem>
3156 </varlistentry>
3157
3158 <varlistentry>
3159 <term><function>PQputCopyEnd</function><indexterm><primary>PQputCopyEnd</></></term>
3160 <listitem>
3161 <para>
3162  Sends end-of-data indication to the server during <literal>COPY_IN</> state.
3163 <synopsis>
3164 int PQputCopyEnd(PGconn *conn,
3165                  const char *errormsg);
3166 </synopsis>
3167 </para>
3168
3169 <para>
3170 Ends the <literal>COPY_IN</> operation successfully if <parameter>errormsg</>
3171 is <symbol>NULL</symbol>.  If <parameter>errormsg</> is not <symbol>NULL</symbol> then the <command>COPY</>
3172 is forced to fail, with the string pointed to by <parameter>errormsg</>
3173 used as the error message.  (One should not assume that this exact error
3174 message will come back from the server, however, as the server might have
3175 already failed the <command>COPY</> for its own reasons.  Also note that the
3176 option to force failure does not work when using pre-3.0-protocol connections.)
3177 </para>
3178
3179 <para>
3180 The result is 1 if the termination data was sent,
3181 zero if it was not sent because the attempt would block (this case is only
3182 possible if the connection is in nonblocking mode), or -1 if an error occurred.
3183 (Use <function>PQerrorMessage</function> to retrieve details if the return
3184 value is -1.  If the value is zero, wait for write-ready and try again.)
3185 </para>
3186
3187 <para>
3188 After successfully calling <function>PQputCopyEnd</>, call
3189 <function>PQgetResult</> to obtain the final result status of the
3190 <command>COPY</> command.  One may wait for
3191 this result to be available in the usual way.  Then return to normal
3192 operation.
3193 </para>
3194 </listitem>
3195 </varlistentry>
3196 </variablelist>
3197
3198 </sect2>
3199
3200 <sect2 id="libpq-copy-receive">
3201   <title>Functions for Receiving <command>COPY</command> Data</title>
3202
3203 <para>
3204  These functions are used to receive data during <literal>COPY TO STDOUT</>.
3205  They will fail if called when the connection is not in <literal>COPY_OUT</>
3206  state.
3207 </para>
3208
3209 <variablelist>
3210 <varlistentry>
3211 <term><function>PQgetCopyData</function><indexterm><primary>PQgetCopyData</></></term>
3212 <listitem>
3213 <para>
3214  Receives data from the server during <literal>COPY_OUT</> state.
3215 <synopsis>
3216 int PQgetCopyData(PGconn *conn,
3217                   char **buffer,
3218                   int async);
3219 </synopsis>
3220 </para>
3221
3222 <para>
3223 Attempts to obtain another row of data from the server during a <command>COPY</command>.
3224 Data is always returned one data row at a time; if only a partial row
3225 is available, it is not returned.  Successful return of a data row
3226 involves allocating a chunk of memory to hold the data.  The
3227 <parameter>buffer</> parameter must be non-<symbol>NULL</symbol>.  <parameter>*buffer</>
3228 is set to point to the allocated memory, or to <symbol>NULL</symbol> in cases where no
3229 buffer is returned.  A non-<symbol>NULL</symbol> result buffer must be freed using
3230 <function>PQfreemem</> when no longer needed.
3231 </para>
3232
3233 <para>
3234 When a row is successfully returned, the return value is the number of
3235 data bytes in the row (this will always be greater than zero).  The
3236 returned string is always null-terminated, though this is probably only
3237 useful for textual <command>COPY</command>.  A result of zero indicates that the <command>COPY</command> is
3238 still in progress, but no row is yet available (this is only possible
3239 when <parameter>async</> is true).  A
3240 result of -1 indicates that the <command>COPY</command> is done.
3241 A result of -2 indicates that an error occurred (consult
3242 <function>PQerrorMessage</> for the reason).
3243 </para>
3244
3245 <para>
3246 When <parameter>async</> is true (not zero), <function>PQgetCopyData</>
3247 will not block waiting for input; it will return zero if the <command>COPY</command> is still
3248 in progress but no complete row is available.  (In this case wait for
3249 read-ready and then call <function>PQconsumeInput</> before calling
3250 <function>PQgetCopyData</> again.)  When <parameter>async</> is
3251 false (zero), <function>PQgetCopyData</> will block until data is available
3252 or the operation completes.
3253 </para>
3254
3255 <para>
3256 After <function>PQgetCopyData</> returns -1, call
3257 <function>PQgetResult</> to obtain the final result status of the
3258 <command>COPY</> command.  One may wait for
3259 this result to be available in the usual way.  Then return to normal
3260 operation.
3261 </para>
3262 </listitem>
3263 </varlistentry>
3264 </variablelist>
3265
3266 </sect2>
3267
3268 <sect2 id="libpq-copy-deprecated">
3269   <title>Obsolete Functions for <command>COPY</command></title>
3270
3271 <para>
3272  These functions represent older methods of handling <command>COPY</>.
3273  Although they still work, they are deprecated due to poor error handling,
3274  inconvenient methods of detecting end-of-data, and lack of support for binary
3275  or nonblocking transfers.
3276 </para>
3277
3278 <variablelist>
3279 <varlistentry>
3280 <term><function>PQgetline</function><indexterm><primary>PQgetline</></></term>
3281 <listitem>
3282 <para>
3283           Reads  a  newline-terminated  line  of  characters
3284           (transmitted  by the server) into a buffer
3285           string of size <parameter>length</>.
3286 <synopsis>
3287 int PQgetline(PGconn *conn,
3288               char *buffer,
3289               int length);
3290 </synopsis>
3291 </para>
3292
3293 <para>
3294 This function copies up to <parameter>length</>-1 characters
3295 into the buffer and converts
3296 the terminating newline into a zero byte.
3297 <function>PQgetline</function> returns <symbol>EOF</symbol> at the end of input, 0 if the
3298 entire line has been read, and 1 if the buffer is full but the
3299 terminating newline has not yet been read.
3300 </para>
3301 <para>
3302 Note that the application must check to see if a
3303 new line consists of  the  two characters  <literal>\.</literal>,
3304 which  indicates  that the server has finished sending
3305 the results  of  the <command>COPY</command> command.
3306 If  the  application might
3307 receive lines that are more than <parameter>length</>-1  characters  long,
3308 care is needed to be sure it recognizes the <literal>\.</literal> line correctly
3309 (and does not, for example, mistake the end of a long data line
3310 for a terminator line).
3311 </para>
3312 </listitem>
3313 </varlistentry>
3314
3315 <varlistentry>
3316 <term><function>PQgetlineAsync</function><indexterm><primary>PQgetlineAsync</></></term>
3317 <listitem>
3318 <para>
3319           Reads a row of <command>COPY</command> data
3320           (transmitted  by the server) into a buffer
3321           without blocking.
3322 <synopsis>
3323 int PQgetlineAsync(PGconn *conn,
3324                    char *buffer,
3325                    int bufsize);
3326 </synopsis>
3327 </para>
3328
3329 <para>
3330 This function is similar to <function>PQgetline</function>, but it can be used
3331 by applications
3332 that must read <command>COPY</command> data asynchronously, that is, without blocking.
3333 Having issued the <command>COPY</command> command and gotten a <literal>PGRES_COPY_OUT</literal>
3334 response, the
3335 application should call <function>PQconsumeInput</function> and
3336 <function>PQgetlineAsync</function> until the
3337 end-of-data signal is detected.
3338 </para>
3339 <para>
3340 Unlike <function>PQgetline</function>, this function takes
3341 responsibility for detecting end-of-data.
3342 </para>
3343 <para>
3344 On each call, <function>PQgetlineAsync</function> will return data if a
3345 complete data row is available in <application>libpq</>'s input buffer.
3346 Otherwise, no data is returned until the rest of the row arrives.
3347 The function returns -1 if the end-of-copy-data marker has been recognized,
3348 or 0 if no data is available, or a positive number giving the number of
3349 bytes of data returned.  If -1 is returned, the caller must next call
3350 <function>PQendcopy</function>, and then return to normal processing.
3351 </para>
3352 <para>
3353 The data returned will not extend beyond a data-row boundary.  If possible
3354 a whole row will be returned at one time.  But if the buffer offered by
3355 the caller is too small to hold a row sent by the server, then a partial
3356 data row will be returned.  With textual data this can be detected by testing
3357 whether the last returned byte is <literal>\n</literal> or not.  (In a binary
3358 <command>COPY</>, actual parsing of the <command>COPY</> data format will be needed to make the
3359 equivalent determination.)
3360 The returned string is not null-terminated.  (If you want to add a
3361 terminating null, be sure to pass a <parameter>bufsize</parameter> one smaller
3362 than the room actually available.)
3363 </para>
3364 </listitem>
3365 </varlistentry>
3366
3367 <varlistentry>
3368 <term><function>PQputline</function><indexterm><primary>PQputline</></></term>
3369 <listitem>
3370 <para>
3371 Sends  a  null-terminated  string  to  the server.
3372 Returns 0 if OK and <symbol>EOF</symbol> if unable to send the string.
3373 <synopsis>
3374 int PQputline(PGconn *conn,
3375               const char *string);
3376 </synopsis>
3377 </para>
3378
3379 <para>
3380 The <command>COPY</command> data stream sent by a series of calls to
3381 <function>PQputline</function> has the same format as that returned by
3382 <function>PQgetlineAsync</function>, except that applications are not
3383 obliged to send exactly one data row per <function>PQputline</function>
3384 call; it is okay to send a partial line or multiple lines per call.
3385 </para>
3386
3387 <note>
3388 <para>
3389 Before <productname>PostgreSQL</productname> protocol 3.0, it was necessary
3390 for the application to explicitly send the two characters
3391 <literal>\.</literal> as a final line to indicate to the server that it had
3392 finished sending <command>COPY</> data.  While this still works, it is deprecated and the
3393 special meaning of <literal>\.</literal> can be expected to be removed in a
3394 future release.  It is sufficient to call <function>PQendcopy</function> after
3395 having sent the actual data.
3396 </para>
3397 </note>
3398 </listitem>
3399 </varlistentry>
3400
3401 <varlistentry>
3402 <term><function>PQputnbytes</function><indexterm><primary>PQputnbytes</></></term>
3403 <listitem>
3404 <para>
3405 Sends  a  non-null-terminated  string  to  the server.
3406 Returns 0 if OK and <symbol>EOF</symbol> if unable to send the string.
3407 <synopsis>
3408 int PQputnbytes(PGconn *conn,
3409                 const char *buffer,
3410                 int nbytes);
3411 </synopsis>
3412 </para>
3413
3414 <para>
3415 This is exactly like <function>PQputline</function>, except that the data
3416 buffer need not be null-terminated since the number of bytes to send is
3417 specified directly.  Use this procedure when sending binary data.
3418 </para>
3419 </listitem>
3420 </varlistentry>
3421
3422 <varlistentry>
3423 <term><function>PQendcopy</function><indexterm><primary>PQendcopy</></></term>
3424 <listitem>
3425 <para>
3426  Synchronizes with the server.
3427 <synopsis>
3428 int PQendcopy(PGconn *conn);
3429 </synopsis>
3430  This function waits until
3431  the  server  has  finished  the copying.  It should
3432  either be issued when the  last  string  has  been
3433  sent  to  the  server using <function>PQputline</function> or when the
3434  last string has been  received  from  the  server
3435  using <function>PGgetline</function>.  It must be issued or the server
3436  will get <quote>out of sync</quote> with  the client.   Upon
3437  return from this function, the server is ready to
3438  receive the next SQL command.
3439  The return value is 0  on  successful  completion,
3440  nonzero otherwise.  (Use <function>PQerrorMessage</function> to retrieve
3441  details if the return value is nonzero.)
3442 </para>
3443
3444 <para>
3445 When using <function>PQgetResult</function>, the application should respond to
3446 a <literal>PGRES_COPY_OUT</literal> result by executing <function>PQgetline</function>
3447 repeatedly, followed by <function>PQendcopy</function> after the terminator line is seen.
3448 It should then return to the <function>PQgetResult</function> loop until
3449 <function>PQgetResult</function> returns a null pointer. Similarly a <literal>PGRES_COPY_IN</literal>
3450 result is processed by a series of <function>PQputline</function> calls followed by
3451 <function>PQendcopy</function>, then return to the <function>PQgetResult</function> loop.
3452 This arrangement will ensure that
3453 a <command>COPY</command> command embedded in a series of <acronym>SQL</acronym> commands
3454 will be executed correctly.
3455 </para>
3456
3457 <para>
3458 Older applications are likely to submit a <command>COPY</command>
3459 via <function>PQexec</function> and assume that the transaction is done after
3460 <function>PQendcopy</function>.
3461 This will work correctly only if the <command>COPY</command> is the only
3462 <acronym>SQL</acronym> command in the command string.
3463 </para>
3464 </listitem>
3465 </varlistentry>
3466 </variablelist>
3467
3468 </sect2>
3469
3470 </sect1>
3471
3472 <sect1 id="libpq-control">
3473 <title>Control Functions</title>
3474
3475 <para>
3476 These functions control miscellaneous details of
3477 <application>libpq</>'s behavior.
3478 </para>
3479
3480 <variablelist>
3481 <varlistentry>
3482 <term><function>PQsetErrorVerbosity</function><indexterm><primary>PQsetErrorVerbosity</></></term>
3483 <listitem>
3484 <para>
3485 Determines the verbosity of messages returned by
3486 <function>PQerrorMessage</> and <function>PQresultErrorMessage</>.
3487 <synopsis>
3488 typedef enum {
3489     PQERRORS_TERSE,
3490     PQERRORS_DEFAULT,
3491     PQERRORS_VERBOSE
3492 } PGVerbosity;
3493
3494 PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity);
3495 </synopsis>
3496 <function>PQsetErrorVerbosity</> sets the verbosity mode, returning
3497 the connection's previous setting.  In <firstterm>TERSE</> mode,
3498 returned messages include severity, primary text, and position only;
3499 this will normally fit on a single line.  The default mode produces
3500 messages that include the above plus any detail, hint, or context
3501 fields (these may span multiple lines).  The <firstterm>VERBOSE</>
3502 mode includes all available fields.  Changing the verbosity does not
3503 affect the messages available from already-existing
3504 <structname>PGresult</> objects, only subsequently-created ones.
3505 </para>
3506 </listitem>
3507 </varlistentry>
3508
3509 <varlistentry>
3510 <term><function>PQtrace</function><indexterm><primary>PQtrace</></></term>
3511 <listitem>
3512 <para>
3513           Enables  tracing of the client/server communication to a debugging file stream.
3514 <synopsis>
3515 void PQtrace(PGconn *conn, FILE *stream);
3516 </synopsis>
3517 </para>
3518 </listitem>
3519 </varlistentry>
3520
3521 <varlistentry>
3522 <term><function>PQuntrace</function><indexterm><primary>PQuntrace</></></term>
3523 <listitem>
3524 <para>
3525           Disables tracing started by <function>PQtrace</function>.
3526 <synopsis>
3527 void PQuntrace(PGconn *conn);
3528 </synopsis>
3529 </para>
3530 </listitem>
3531 </varlistentry>
3532 </variablelist>
3533
3534 </sect1>
3535
3536 <sect1 id="libpq-notice-processing">
3537 <title>Notice Processing</title>
3538
3539 <indexterm zone="libpq-notice-processing">
3540  <primary>notice processing</primary>
3541  <secondary>in libpq</secondary>
3542 </indexterm>
3543
3544 <para>
3545 Notice and warning messages generated by the server are not returned by the
3546 query execution functions, since they do not imply failure of the query.
3547 Instead they are passed to a notice handling function, and execution continues
3548 normally after the handler returns.  The default notice handling function
3549 prints the message on <filename>stderr</filename>, but the application can
3550 override this behavior by supplying its own handling function.
3551 </para>
3552
3553 <para>
3554 For historical reasons, there are two levels of notice handling, called the
3555 notice receiver and notice processor.  The default behavior is for the notice
3556 receiver to format the notice and pass a string to the notice processor
3557 for printing.  However, an application that chooses to provide its own notice
3558 receiver will typically ignore the notice processor layer and just do all the
3559 work in the notice receiver.
3560 </para>
3561
3562 <para>
3563 The function <function>PQsetNoticeReceiver</function>
3564 <indexterm><primary>notice receiver</></><indexterm><primary>PQsetNoticeReceiver</></>
3565 sets or examines the current notice receiver for a connection object.
3566 Similarly, <function>PQsetNoticeProcessor</function>
3567 <indexterm><primary>notice processor</></><indexterm><primary>PQsetNoticeProcessor</></>
3568 sets or examines the current notice processor.
3569
3570 <synopsis>
3571 typedef void (*PQnoticeReceiver) (void *arg, const PGresult *res);
3572
3573 PQnoticeReceiver
3574 PQsetNoticeReceiver(PGconn *conn,
3575                     PQnoticeReceiver proc,
3576                     void *arg);
3577
3578 typedef void (*PQnoticeProcessor) (void *arg, const char *message);
3579
3580 PQnoticeProcessor
3581 PQsetNoticeProcessor(PGconn *conn,
3582                      PQnoticeProcessor proc,
3583                      void *arg);
3584 </synopsis>
3585
3586 Each of these functions returns the previous notice receiver or processor
3587 function pointer, and sets the new value.
3588 If you supply a null function pointer, no action is taken,
3589 but the current pointer is returned.
3590 </para>
3591
3592 <para>
3593 When a notice or warning message is received from the server, or generated
3594 internally by <application>libpq</application>, the notice receiver function
3595 is called.  It is passed the message in the form of a
3596 <symbol>PGRES_NONFATAL_ERROR</symbol> <structname>PGresult</structname>.
3597 (This allows the receiver to extract individual fields using
3598 <function>PQresultErrorField</>, or the complete preformatted message using
3599 <function>PQresultErrorMessage</>.)
3600 The same void pointer passed to 
3601 <function>PQsetNoticeReceiver</function> is also passed.
3602 (This pointer can be used to access application-specific state if needed.)
3603 </para>
3604
3605 <para>
3606 The default notice receiver simply extracts the message (using
3607 <function>PQresultErrorMessage</>) and passes it to the notice processor.
3608 </para>
3609
3610 <para>
3611 The notice processor is responsible for handling a notice or warning message
3612 given in text form.  It is passed the string text of the message
3613 (including a trailing newline), plus
3614 a void pointer that is the same one passed to
3615 <function>PQsetNoticeProcessor</function>.
3616 (This pointer can be used to access application-specific state if needed.)
3617 </para>
3618
3619 <para>
3620 The default notice processor is simply
3621 <programlisting>
3622 static void
3623 defaultNoticeProcessor(void *arg, const char *message)
3624 {
3625     fprintf(stderr, "%s", message);
3626 }
3627 </programlisting>
3628 </para>
3629
3630 <para>
3631 Once you have set a notice receiver or processor, you should expect that that
3632 function could be called as long as either the <structname>PGconn</> object or
3633 <structname>PGresult</> objects made from it exist.  At creation of a
3634 <structname>PGresult</>, the <structname>PGconn</>'s current notice handling
3635 pointers are copied into the <structname>PGresult</> for possible use by
3636 functions like <function>PQgetvalue</function>.
3637 </para>
3638
3639 </sect1>
3640
3641 <sect1 id="libpq-envars">
3642 <title>Environment Variables</title>
3643
3644 <indexterm zone="libpq-envars">
3645  <primary>environment variable</primary>
3646 </indexterm>
3647
3648 <para>
3649 The following environment variables can be used to select default
3650 connection parameter values, which will be used by
3651 <function>PQconnectdb</>, <function>PQsetdbLogin</> and
3652 <function>PQsetdb</> if no value is directly specified by the calling
3653 code.  These are useful to avoid hard-coding database connection
3654 information into simple client applications, for example.
3655
3656 <itemizedlist>
3657 <listitem>
3658 <para>
3659 <indexterm>
3660  <primary><envar>PGHOST</envar></primary>
3661 </indexterm>
3662 <envar>PGHOST</envar> sets the database server name.
3663 If this begins with a slash, it specifies Unix-domain communication
3664 rather than TCP/IP communication; the value is then the name of the
3665 directory in which the socket file is stored (in a default installation
3666 setup this would be <filename>/tmp</filename>).
3667 </para>
3668 </listitem>
3669 <listitem>
3670 <para>
3671 <indexterm>
3672  <primary><envar>PGHOSTADDR</envar></primary>
3673 </indexterm>
3674 <envar>PGHOSTADDR</envar> specifies the numeric IP address of the database
3675 server.  This can be set instead of or in addition to <envar>PGHOST</envar>
3676 to avoid DNS lookup overhead. See the documentation of
3677 these parameters, under <function>PQconnectdb</function> above, for details
3678 on their interaction.
3679 </para>
3680 <para>
3681 When neither <envar>PGHOST</envar> nor <envar>PGHOSTADDR</envar> is set,
3682 the default behavior is to connect using a local Unix-domain socket; or on
3683 machines without Unix-domain sockets, <application>libpq</application> will
3684 attempt to connect to <literal>localhost</>.
3685 </para>
3686 </listitem>
3687 <listitem>
3688 <para>
3689 <indexterm>
3690  <primary><envar>PGPORT</envar></primary>
3691 </indexterm>
3692 <envar>PGPORT</envar> sets the TCP port number or Unix-domain
3693 socket file extension for communicating with the
3694 <productname>PostgreSQL</productname> server.
3695 </para>
3696 </listitem>
3697 <listitem>
3698 <para>
3699 <indexterm>
3700  <primary><envar>PGDATABASE</envar></primary>
3701 </indexterm>
3702 <envar>PGDATABASE</envar>  sets the 
3703 <productname>PostgreSQL</productname> database name.
3704 </para>
3705 </listitem>
3706 <listitem>
3707 <para>
3708 <indexterm>
3709  <primary><envar>PGUSER</envar></primary>
3710 </indexterm>
3711 <envar>PGUSER</envar>
3712 sets the user name used to connect to the database.
3713 </para>
3714 </listitem>
3715 <listitem>
3716 <para>
3717 <indexterm>
3718  <primary><envar>PGPASSWORD</envar></primary>
3719 </indexterm>
3720 <envar>PGPASSWORD</envar>
3721 sets the password used if the server demands password
3722 authentication.  Use of this environment variable is not 
3723 recommended for security reasons (some operating systems
3724 allow non-root users to see process environment variables via
3725 <application>ps</>); instead consider using  the 
3726 <filename>~/.pgpass</> file (see <xref linkend="libpq-pgpass">).
3727 </para>
3728 </listitem>
3729 <listitem>
3730 <para>
3731 <indexterm>
3732  <primary><envar>PGPASSFILE</envar></primary>
3733 </indexterm>
3734 <envar>PGPASSFILE</envar>
3735 specifies the name of the password file to use for lookups.
3736 If not set, it defaults to <filename>~/.pgpass</>
3737 (see <xref linkend="libpq-pgpass">).
3738 </para>
3739 </listitem>
3740 <listitem>
3741 <para>
3742 <indexterm>
3743  <primary><envar>PGSERVICE</envar></primary>
3744 </indexterm>
3745 <envar>PGSERVICE</envar>
3746 sets the service name to be looked up in <filename>pg_service.conf</filename>.
3747 This offers a shorthand way of setting all the parameters.
3748 </para>
3749 </listitem>
3750 <listitem>
3751 <para>
3752 <indexterm>
3753  <primary><envar>PGREALM</envar></primary>
3754 </indexterm>
3755 <envar>PGREALM</envar> sets the Kerberos realm to  use  with  
3756 <productname>PostgreSQL</productname>, if  it is different from the local realm.
3757 If <envar>PGREALM</envar> is set, <application>libpq</application>
3758 applications  will  attempt authentication  with  servers for this realm and use
3759 separate ticket files to avoid conflicts with  local
3760 ticket  files.   This  environment  variable is only
3761 used if Kerberos authentication is selected by the server.
3762 </para>
3763 </listitem>
3764 <listitem>
3765 <para>
3766 <indexterm>
3767  <primary><envar>PGOPTIONS</envar></primary>
3768 </indexterm>
3769 <envar>PGOPTIONS</envar> sets additional run-time  options  for  
3770 the <productname>PostgreSQL</productname> server.
3771 </para>
3772 </listitem>
3773 <listitem>
3774 <para>
3775 <indexterm>
3776  <primary><envar>PGSSLMODE</envar></primary>
3777 </indexterm>
3778 <envar>PGSSLMODE</envar> determines whether and with what priority an
3779 <acronym>SSL</> connection will be negotiated with the server. There are
3780 four modes: <literal>disable</> will attempt only an unencrypted
3781 <acronym>SSL</> connection; <literal>allow</> will negotiate,
3782 trying first a non-<acronym>SSL</> connection, then if that fails,
3783 trying an <acronym>SSL</> connection; <literal>prefer</>
3784 (the default) will negotiate, trying first an <acronym>SSL</>
3785 connection, then if that fails, trying a regular non-<acronym>SSL</>
3786 connection; <literal>require</> will try only an <acronym>SSL</>
3787 connection. If <productname>PostgreSQL</> is compiled without SSL support,
3788 using option <literal>require</> will cause an error, while options
3789 <literal>allow</> and <literal>prefer</> will be accepted but
3790 <application>libpq</> will not in fact attempt an <acronym>SSL</>
3791 connection.
3792 </para>
3793 </listitem>
3794 <listitem>
3795 <para>
3796 <indexterm>
3797  <primary><envar>PGREQUIRESSL</envar></primary>
3798 </indexterm>
3799 <envar>PGREQUIRESSL</envar> sets whether or not the connection must be
3800 made over <acronym>SSL</acronym>. If set to
3801 <quote>1</quote>, <application>libpq</>
3802 will refuse to connect if the server does not accept
3803 an <acronym>SSL</acronym> connection (equivalent to <literal>sslmode</>
3804 <literal>prefer</>).
3805 This option is deprecated in favor of the <literal>sslmode</>
3806 setting, and is only available if
3807 <productname>PostgreSQL</> is compiled with SSL support.
3808 </para>
3809 </listitem>
3810 <listitem>
3811 <para>
3812 <indexterm>
3813  <primary><envar>PGKRBSRVNAME</envar></primary>
3814 </indexterm>
3815 <envar>PGKRBSRVNAME</envar> sets the Kerberos service name to use when
3816 authenticating with Kerberos 5.
3817 </para>
3818 </listitem>
3819 <listitem>
3820 <para>
3821 <indexterm>
3822  <primary><envar>PGCONNECT_TIMEOUT</envar></primary>
3823 </indexterm>
3824 <envar>PGCONNECT_TIMEOUT</envar> sets the maximum number of seconds
3825 that <application>libpq</application> will wait when attempting to
3826 connect to the <productname>PostgreSQL</productname> server.  If unset
3827 or set to zero, <application>libpq</application> will wait indefinitely.
3828 It is not recommended to set the timeout to less than 2 seconds.
3829 </para>
3830 </listitem>
3831 </itemizedlist>
3832 </para>
3833
3834 <para>
3835 The following environment variables can be used to specify default
3836 behavior for each <productname>PostgreSQL</productname> session.
3837 (See also the
3838 <xref linkend="sql-alteruser" endterm="sql-alteruser-title"> and
3839 <xref linkend="sql-alterdatabase" endterm="sql-alterdatabase-title">
3840 commands for ways to set default behavior on a per-user or per-database
3841 basis.)
3842
3843 <itemizedlist>
3844 <listitem>
3845 <para>
3846 <indexterm>
3847  <primary><envar>PGDATESTYLE</envar></primary>
3848 </indexterm>
3849 <envar>PGDATESTYLE</envar>
3850 sets the default style of date/time representation.
3851 (Equivalent to <literal>SET datestyle TO ...</literal>.)
3852 </para>
3853 </listitem>
3854 <listitem>
3855 <para>
3856 <indexterm>
3857  <primary><envar>PGTZ</envar></primary>
3858 </indexterm>
3859 <envar>PGTZ</envar>
3860 sets the default time zone.
3861 (Equivalent to <literal>SET timezone TO ...</literal>.)
3862 </para>
3863 </listitem>
3864 <listitem>
3865 <para>
3866 <indexterm>
3867  <primary><envar>PGCLIENTENCODING</envar></primary>
3868 </indexterm>
3869 <envar>PGCLIENTENCODING</envar>
3870 sets the default client character set encoding.
3871 (Equivalent to <literal>SET client_encoding TO ...</literal>.)
3872 </para>
3873 </listitem>
3874 <listitem>
3875 <para>
3876 <indexterm>
3877  <primary><envar>PGGEQO</envar></primary>
3878 </indexterm>
3879 <envar>PGGEQO</envar>
3880 sets the default mode for the genetic query optimizer.
3881 (Equivalent to <literal>SET geqo TO ...</literal>.)
3882 </para>
3883 </listitem>
3884 </itemizedlist>
3885
3886 Refer to the <acronym>SQL</acronym> command 
3887 <xref linkend="sql-set" endterm="sql-set-title">
3888 for information on correct values for these environment variables.
3889 </para>
3890
3891 <para>
3892 The following environment variables determine internal behavior of
3893 <application>libpq</application>; they override compiled-in defaults.
3894
3895 <itemizedlist>
3896 <listitem>
3897 <para>
3898 <indexterm>
3899  <primary><envar>PGSYSCONFDIR</envar></primary>
3900 </indexterm>
3901 <envar>PGSYSCONFDIR</envar>
3902 sets the directory containing the <filename>pg_service.conf</> file.
3903 </para>
3904 </listitem>
3905 <listitem>
3906 <para>
3907 <indexterm>
3908  <primary><envar>PGLOCALEDIR</envar></primary>
3909 </indexterm>
3910 <envar>PGLOCALEDIR</envar>
3911 sets the directory containing the <literal>locale</> files for message
3912 internationalization.
3913 </para>
3914 </listitem>
3915 </itemizedlist>
3916 </para>
3917
3918 </sect1>
3919
3920
3921 <sect1 id="libpq-pgpass">
3922 <title>The Password File</title>
3923
3924 <indexterm zone="libpq-pgpass">
3925  <primary>password file</primary>
3926 </indexterm>
3927 <indexterm zone="libpq-pgpass">
3928  <primary>.pgpass</primary>
3929 </indexterm>
3930
3931 <para>
3932 The file <filename>.pgpass</filename> in a user's home directory or the
3933 file referenced by <envar>PGPASSFILE</envar> can contain passwords to
3934 be used if the connection requires a password (and no password has been
3935 specified  otherwise). On Microsoft Windows the file is named
3936 <filename>%APPDATA%\postgresql\pgpass.conf</> (where
3937 <filename>%APPDATA%</> refers to the Application Data subdirectory in
3938 the user's profile).
3939 </para>
3940
3941 <para>
3942 This file should contain lines of the following format:
3943 <synopsis>
3944 <replaceable>hostname</replaceable>:<replaceable>port</replaceable>:<replaceable>database</replaceable>:<replaceable>username</replaceable>:<replaceable>password</replaceable>
3945 </synopsis>
3946 Each of the first four fields may be a literal value, or <literal>*</literal>,
3947 which
3948 matches anything.  The password field from the first line that matches the
3949 current connection parameters will be used.  (Therefore, put more-specific
3950 entries first when you are using wildcards.)
3951 If an entry needs to contain <literal>:</literal> or
3952 <literal>\</literal>, escape this character with <literal>\</literal>.
3953 </para>
3954
3955 <para>
3956 The permissions on <filename>.pgpass</filename> must disallow any
3957 access to world or group; achieve this by the command
3958 <command>chmod 0600 ~/.pgpass</command>.
3959 If the permissions are less strict than this, the file will be ignored.
3960 (The file permissions are not currently checked on Microsoft Windows,
3961 however.)
3962 </para>
3963 </sect1>
3964
3965
3966 <sect1 id="libpq-ssl">
3967 <title>SSL Support</title>
3968
3969 <indexterm zone="libpq-ssl">
3970  <primary>SSL</primary>
3971 </indexterm>
3972
3973   <para>
3974    <productname>PostgreSQL</> has native support for using
3975    <acronym>SSL</> connections to encrypt client/server communications
3976    for increased security. See <xref linkend="ssl-tcp"> for details
3977    about the server-side <acronym>SSL</> functionality.
3978   </para>
3979
3980   <para>
3981    If the server demands a client certificate, 
3982    <application>libpq</application>
3983    will send the certificate stored in file
3984    <filename>~/.postgresql/postgresql.crt</> within the user's home directory.
3985    A matching private key file <filename>~/.postgresql/postgresql.key</>
3986    must also be present, and must not be world-readable.
3987    (On Microsoft Windows these files are named
3988    <filename>%APPDATA%\postgresql\postgresql.crt</filename> and
3989    <filename>%APPDATA%\postgresql\postgresql.key</filename>.)
3990   </para>
3991
3992   <para>
3993    If the file <filename>~/.postgresql/root.crt</> is present in the user's
3994    home directory,
3995    <application>libpq</application> will use the certificate list stored
3996    therein to verify the server's certificate.
3997    (On Microsoft Windows the file is named
3998    <filename>%APPDATA%\postgresql\root.crt</filename>.)
3999    The SSL connection will
4000    fail if the server does not present a certificate; therefore, to
4001    use this feature the server must also have a <filename>root.crt</> file.
4002   </para>
4003 </sect1>
4004
4005
4006 <sect1 id="libpq-threading">
4007 <title>Behavior in Threaded Programs</title>
4008
4009 <indexterm zone="libpq-threading">
4010  <primary>threads</primary>
4011  <secondary>with libpq</secondary>
4012 </indexterm>
4013
4014 <para>
4015 <application>libpq</application> is reentrant and thread-safe if the
4016 <filename>configure</filename> command-line option
4017 <literal>--enable-thread-safety</> was used when the
4018 <productname>PostgreSQL</productname> distribution was built.  In
4019 addition, you might need to use additional compiler command-line
4020 options when you compile your application code.  Refer to your
4021 system's documentation for information about how to build
4022 thread-enabled applications, or look in 
4023 <filename>src/Makefile.global</filename> for <literal>PTHREAD_CFLAGS</>
4024 and <literal>PTHREAD_LIBS</>.
4025 </para>
4026
4027 <para>
4028 One restriction is that no two threads attempt to manipulate the same
4029 <structname>PGconn</> object at the same time. In particular, you cannot
4030 issue concurrent commands from different threads through the same
4031 connection object. (If you need to run concurrent commands, use
4032 multiple connections.)
4033 </para>
4034
4035 <para>
4036 <structname>PGresult</> objects are read-only after creation, and so can be 
4037 passed around freely between threads.
4038 </para>
4039
4040 <para>
4041 The deprecated functions
4042 <function>PQrequestCancel</function>,
4043 <function>PQoidStatus</function> and
4044 <function>fe_setauthsvc</function>
4045 are not thread-safe and should not be used in multithread programs.
4046 <function>PQrequestCancel</function> can be replaced by
4047 <function>PQcancel</function>.
4048 <function>PQoidStatus</function> can be replaced by
4049 <function>PQoidValue</function>.
4050 There is no good reason to call <function>fe_setauthsvc</function> at all.
4051 </para>
4052
4053 <para>
4054 <application>libpq</application> applications that use the
4055 <literal>crypt</literal> authentication method rely on the
4056 <literal>crypt()</literal> operating system function, which is often
4057 not thread-safe.<indexterm><primary>crypt</><secondary>thread
4058 safety</></> It is better to use the <literal>md5</literal> method,
4059 which is thread-safe on all platforms.
4060 </para>
4061
4062 <para>
4063 If you experience problems with threaded applications, run
4064 the program in <filename>src/tools/thread</> to see if your
4065 platform has thread-unsafe functions.  This program is run 
4066 by <filename>configure</filename>, but for binary distributions
4067 your library might not match the library used to build the binaries.
4068 </para>
4069 </sect1>
4070
4071
4072  <sect1 id="libpq-build">
4073   <title>Building <application>libpq</application> Programs</title>
4074
4075   <indexterm zone="libpq-build">
4076    <primary>compiling</primary>
4077    <secondary>libpq applications</secondary>
4078   </indexterm>
4079
4080   <para>
4081    To build (i.e., compile and link) a program using
4082    <application>libpq</application> you need to 
4083    do all of the following things:
4084
4085    <itemizedlist>
4086     <listitem>
4087      <para>
4088       Include the <filename>libpq-fe.h</filename> header file:
4089 <programlisting>
4090 #include &lt;libpq-fe.h&gt;
4091 </programlisting>
4092       If you failed to do that then you will normally get error
4093       messages from your compiler similar to
4094 <screen>
4095 foo.c: In function `main':
4096 foo.c:34: `PGconn' undeclared (first use in this function)
4097 foo.c:35: `PGresult' undeclared (first use in this function)
4098 foo.c:54: `CONNECTION_BAD' undeclared (first use in this function)
4099 foo.c:68: `PGRES_COMMAND_OK' undeclared (first use in this function)
4100 foo.c:95: `PGRES_TUPLES_OK' undeclared (first use in this function)
4101 </screen>
4102      </para>
4103     </listitem>
4104
4105     <listitem>
4106      <para>
4107       Point your compiler to the directory where the <productname>PostgreSQL</> header
4108       files were installed, by supplying the
4109       <literal>-I<replaceable>directory</replaceable></literal> option
4110       to your compiler.  (In some cases the compiler will look into
4111       the directory in question by default, so you can omit this
4112       option.)  For instance, your compile command line could look
4113       like:
4114 <programlisting>
4115 cc -c -I/usr/local/pgsql/include testprog.c
4116 </programlisting>
4117       If you are using makefiles then add the option to the
4118       <varname>CPPFLAGS</varname> variable:
4119 <programlisting>
4120 CPPFLAGS += -I/usr/local/pgsql/include
4121 </programlisting>
4122      </para>
4123
4124      <para>
4125       If there is any chance that your program might be compiled by
4126       other users then you should not hardcode the directory location
4127       like that.  Instead, you can run the utility
4128       <command>pg_config</command><indexterm><primary>pg_config</><secondary
4129       sortas="libpq">with libpq</></> to find out where the header
4130       files are on the local system:
4131 <screen>
4132 <prompt>$</prompt> pg_config --includedir
4133 <computeroutput>/usr/local/include</computeroutput>
4134 </screen>
4135      </para>
4136
4137      <para>
4138       Failure to specify the correct option to the compiler will
4139       result in an error message such as
4140 <screen>
4141 testlibpq.c:8:22: libpq-fe.h: No such file or directory
4142 </screen>
4143      </para>
4144     </listitem>
4145
4146     <listitem>
4147      <para>
4148       When linking the final program, specify the option
4149       <literal>-lpq</literal> so that the <application>libpq</application> library gets pulled
4150       in, as well as the option
4151       <literal>-L<replaceable>directory</replaceable></literal> to
4152       point the compiler to the directory where the <application>libpq</application> library resides.  (Again, the
4153       compiler will search some directories by default.)  For maximum
4154       portability, put the <option>-L</option> option before the
4155       <option>-lpq</option> option.  For example:
4156 <programlisting>
4157 cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq
4158 </programlisting>
4159      </para>
4160
4161      <para>
4162       You can find out the library directory using
4163       <command>pg_config</command> as well:
4164 <screen>
4165 <prompt>$</prompt> pg_config --libdir
4166 <computeroutput>/usr/local/pgsql/lib</computeroutput>
4167 </screen>
4168      </para>
4169
4170      <para>
4171       Error messages that point to problems in this area could look
4172       like the following.
4173 <screen>
4174 testlibpq.o: In function `main':
4175 testlibpq.o(.text+0x60): undefined reference to `PQsetdbLogin'
4176 testlibpq.o(.text+0x71): undefined reference to `PQstatus'
4177 testlibpq.o(.text+0xa4): undefined reference to `PQerrorMessage'
4178 </screen>
4179       This means you forgot <option>-lpq</option>.
4180 <screen>
4181 /usr/bin/ld: cannot find -lpq
4182 </screen>
4183       This means you forgot the <option>-L</option> option or did not specify
4184       the right directory.
4185      </para>
4186     </listitem>
4187    </itemizedlist>
4188   </para>
4189
4190   <para>
4191    <indexterm><primary>libpq-int.h</></>
4192    If your codes references the header file
4193    <filename>libpq-int.h</filename> and you refuse to fix your code to
4194    not use it, starting in <productname>PostgreSQL</> 7.2, this file will be found in
4195    <filename><replaceable>includedir</replaceable>/postgresql/internal/libpq-int.h</filename>,
4196    so you need to add the appropriate <option>-I</option> option to
4197    your compiler command line.
4198   </para>
4199
4200  </sect1>
4201
4202
4203  <sect1 id="libpq-example">
4204   <title>Example Programs</title>
4205
4206   <para>
4207    These examples and others can be found in the
4208    directory <filename>src/test/examples</filename> in the source code
4209    distribution.
4210   </para>
4211
4212   <example id="libpq-example-1">
4213    <title><application>libpq</application> Example Program 1</title>
4214
4215 <programlisting>
4216 /*
4217  * testlibpq.c
4218  *
4219  *              Test the C version of LIBPQ, the POSTGRES frontend library.
4220  */
4221 #include &lt;stdio.h&gt;
4222 #include &lt;stdlib.h&gt;
4223 #include "libpq-fe.h"
4224
4225 static void
4226 exit_nicely(PGconn *conn)
4227 {
4228         PQfinish(conn);
4229         exit(1);
4230 }
4231
4232 int
4233 main(int argc, char **argv)
4234 {
4235         const char *conninfo;
4236         PGconn     *conn;
4237         PGresult   *res;
4238         int                     nFields;
4239         int                     i,
4240                                 j;
4241
4242         /*
4243          * If the user supplies a parameter on the command line, use it as
4244          * the conninfo string; otherwise default to setting dbname=postgres
4245          * and using environment variables or defaults for all other connection
4246          * parameters.
4247          */
4248         if (argc &gt; 1)
4249                 conninfo = argv[1];
4250         else
4251                 conninfo = "dbname = postgres";
4252
4253         /* Make a connection to the database */
4254         conn = PQconnectdb(conninfo);
4255
4256         /* Check to see that the backend connection was successfully made */
4257         if (PQstatus(conn) != CONNECTION_OK)
4258         {
4259                 fprintf(stderr, "Connection to database failed: %s",
4260                         PQerrorMessage(conn));
4261                 exit_nicely(conn);
4262         }
4263
4264         /*
4265          * Our test case here involves using a cursor, for which we must be
4266          * inside a transaction block.  We could do the whole thing with a
4267          * single PQexec() of "select * from pg_database", but that's too
4268          * trivial to make a good example.
4269          */
4270
4271         /* Start a transaction block */
4272         res = PQexec(conn, "BEGIN");
4273         if (PQresultStatus(res) != PGRES_COMMAND_OK)
4274         {
4275                 fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn));
4276                 PQclear(res);
4277                 exit_nicely(conn);
4278         }
4279
4280         /*
4281          * Should PQclear PGresult whenever it is no longer needed to avoid
4282          * memory leaks
4283          */
4284         PQclear(res);
4285
4286         /*
4287          * Fetch rows from pg_database, the system catalog of databases
4288          */
4289         res = PQexec(conn, "DECLARE myportal CURSOR FOR select * from pg_database");
4290         if (PQresultStatus(res) != PGRES_COMMAND_OK)
4291         {
4292                 fprintf(stderr, "DECLARE CURSOR failed: %s", PQerrorMessage(conn));
4293                 PQclear(res);
4294                 exit_nicely(conn);
4295         }
4296         PQclear(res);
4297
4298         res = PQexec(conn, "FETCH ALL in myportal");
4299         if (PQresultStatus(res) != PGRES_TUPLES_OK)
4300         {
4301                 fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(conn));
4302                 PQclear(res);
4303                 exit_nicely(conn);
4304         }
4305
4306         /* first, print out the attribute names */
4307         nFields = PQnfields(res);
4308         for (i = 0; i &lt; nFields; i++)
4309                 printf("%-15s", PQfname(res, i));
4310         printf("\n\n");
4311
4312         /* next, print out the rows */
4313         for (i = 0; i &lt; PQntuples(res); i++)
4314         {
4315                 for (j = 0; j &lt; nFields; j++)
4316                         printf("%-15s", PQgetvalue(res, i, j));
4317                 printf("\n");
4318         }
4319
4320         PQclear(res);
4321
4322         /* close the portal ... we don't bother to check for errors ... */
4323         res = PQexec(conn, "CLOSE myportal");
4324         PQclear(res);
4325
4326         /* end the transaction */
4327         res = PQexec(conn, "END");
4328         PQclear(res);
4329
4330         /* close the connection to the database and cleanup */
4331         PQfinish(conn);
4332
4333         return 0;
4334 }
4335 </programlisting>
4336   </example>
4337
4338   <example id="libpq-example-2">
4339    <title><application>libpq</application> Example Program 2</title>
4340
4341 <programlisting>
4342 /*
4343  * testlibpq2.c
4344  *              Test of the asynchronous notification interface
4345  *
4346  * Start this program, then from psql in another window do
4347  *   NOTIFY TBL2;
4348  * Repeat four times to get this program to exit.
4349  *
4350  * Or, if you want to get fancy, try this:
4351  * populate a database with the following commands
4352  * (provided in src/test/examples/testlibpq2.sql):
4353  *
4354  *   CREATE TABLE TBL1 (i int4);
4355  *
4356  *   CREATE TABLE TBL2 (i int4);
4357  *
4358  *   CREATE RULE r1 AS ON INSERT TO TBL1 DO
4359  *     (INSERT INTO TBL2 VALUES (new.i); NOTIFY TBL2);
4360  *
4361  * and do this four times:
4362  *
4363  *   INSERT INTO TBL1 VALUES (10);
4364  */
4365 #include &lt;stdio.h&gt;
4366 #include &lt;stdlib.h&gt;
4367 #include &lt;string.h&gt;
4368 #include &lt;errno.h&gt;
4369 #include &lt;sys/time.h&gt;
4370 #include "libpq-fe.h"
4371
4372 static void
4373 exit_nicely(PGconn *conn)
4374 {
4375         PQfinish(conn);
4376         exit(1);
4377 }
4378
4379 int
4380 main(int argc, char **argv)
4381 {
4382         const char *conninfo;
4383         PGconn     *conn;
4384         PGresult   *res;
4385         PGnotify   *notify;
4386         int                     nnotifies;
4387
4388         /*
4389          * If the user supplies a parameter on the command line, use it as
4390          * the conninfo string; otherwise default to setting dbname=postgres
4391          * and using environment variables or defaults for all other connection
4392          * parameters.
4393          */
4394         if (argc &gt; 1)
4395                 conninfo = argv[1];
4396         else
4397                 conninfo = "dbname = postgres";
4398
4399         /* Make a connection to the database */
4400         conn = PQconnectdb(conninfo);
4401
4402         /* Check to see that the backend connection was successfully made */
4403         if (PQstatus(conn) != CONNECTION_OK)
4404         {
4405                 fprintf(stderr, "Connection to database failed: %s",
4406                         PQerrorMessage(conn));
4407                 exit_nicely(conn);
4408         }
4409
4410         /*
4411          * Issue LISTEN command to enable notifications from the rule's NOTIFY.
4412          */
4413         res = PQexec(conn, "LISTEN TBL2");
4414         if (PQresultStatus(res) != PGRES_COMMAND_OK)
4415         {
4416                 fprintf(stderr, "LISTEN command failed: %s", PQerrorMessage(conn));
4417                 PQclear(res);
4418                 exit_nicely(conn);
4419         }
4420
4421         /*
4422          * should PQclear PGresult whenever it is no longer needed to avoid
4423          * memory leaks
4424          */
4425         PQclear(res);
4426
4427         /* Quit after four notifies are received. */
4428         nnotifies = 0;
4429         while (nnotifies &lt; 4)
4430         {
4431                 /*
4432                  * Sleep until something happens on the connection.  We use select(2)
4433                  * to wait for input, but you could also use poll() or similar
4434                  * facilities.
4435                  */
4436                 int                     sock;
4437                 fd_set          input_mask;
4438
4439                 sock = PQsocket(conn);
4440
4441                 if (sock &lt; 0)
4442                         break;                          /* shouldn't happen */
4443
4444                 FD_ZERO(&amp;input_mask);
4445                 FD_SET(sock, &amp;input_mask);
4446
4447                 if (select(sock + 1, &amp;input_mask, NULL, NULL, NULL) &lt; 0)
4448                 {
4449                         fprintf(stderr, "select() failed: %s\n", strerror(errno));
4450                         exit_nicely(conn);
4451                 }
4452
4453                 /* Now check for input */
4454                 PQconsumeInput(conn);
4455                 while ((notify = PQnotifies(conn)) != NULL)
4456                 {
4457                         fprintf(stderr,
4458                                         "ASYNC NOTIFY of '%s' received from backend pid %d\n",
4459                                         notify-&gt;relname, notify-&gt;be_pid);
4460                         PQfreemem(notify);
4461                         nnotifies++;
4462                 }
4463         }
4464
4465         fprintf(stderr, "Done.\n");
4466
4467         /* close the connection to the database and cleanup */
4468         PQfinish(conn);
4469
4470         return 0;
4471 }
4472 </programlisting>
4473   </example>
4474
4475   <example id="libpq-example-3">
4476    <title><application>libpq</application> Example Program 3</>
4477
4478 <programlisting>
4479 /*
4480  * testlibpq3.c
4481  *              Test out-of-line parameters and binary I/O.
4482  *
4483  * Before running this, populate a database with the following commands
4484  * (provided in src/test/examples/testlibpq3.sql):
4485  *
4486  * CREATE TABLE test1 (i int4, t text, b bytea);
4487  *
4488  * INSERT INTO test1 values (1, 'joe''s place', '\\000\\001\\002\\003\\004');
4489  * INSERT INTO test1 values (2, 'ho there', '\\004\\003\\002\\001\\000');
4490  *
4491  * The expected output is:
4492  *
4493  * tuple 0: got
4494  *  i = (4 bytes) 1
4495  *  t = (11 bytes) 'joe's place'
4496  *  b = (5 bytes) \000\001\002\003\004
4497  *
4498  */
4499 #include &lt;stdio.h&gt;
4500 #include &lt;stdlib.h&gt;
4501 #include &lt;string.h&gt;
4502 #include &lt;sys/types.h&gt;
4503 #include "libpq-fe.h"
4504
4505 /* for ntohl/htonl */
4506 #include &lt;netinet/in.h&gt;
4507 #include &lt;arpa/inet.h&gt;
4508
4509
4510 static void
4511 exit_nicely(PGconn *conn)
4512 {
4513         PQfinish(conn);
4514         exit(1);
4515 }
4516
4517 int
4518 main(int argc, char **argv)
4519 {
4520         const char *conninfo;
4521         PGconn     *conn;
4522         PGresult   *res;
4523         const char *paramValues[1];
4524         int                     i,
4525                                 j;
4526         int                     i_fnum,
4527                                 t_fnum,
4528                                 b_fnum;
4529
4530         /*
4531          * If the user supplies a parameter on the command line, use it as
4532          * the conninfo string; otherwise default to setting dbname=postgres
4533          * and using environment variables or defaults for all other connection
4534          * parameters.
4535          */
4536         if (argc &gt; 1)
4537                 conninfo = argv[1];
4538         else
4539                 conninfo = "dbname = postgres";
4540
4541         /* Make a connection to the database */
4542         conn = PQconnectdb(conninfo);
4543
4544         /* Check to see that the backend connection was successfully made */
4545         if (PQstatus(conn) != CONNECTION_OK)
4546         {
4547                 fprintf(stderr, "Connection to database failed: %s",
4548                         PQerrorMessage(conn));
4549                 exit_nicely(conn);
4550         }
4551
4552         /*
4553          * The point of this program is to illustrate use of PQexecParams()
4554          * with out-of-line parameters, as well as binary transmission of
4555          * results.  By using out-of-line parameters we can avoid a lot of
4556          * tedious mucking about with quoting and escaping.  Notice how we
4557          * don't have to do anything special with the quote mark in the
4558          * parameter value.
4559          */
4560
4561         /* Here is our out-of-line parameter value */
4562         paramValues[0] = "joe's place";
4563
4564         res = PQexecParams(conn,
4565                                            "SELECT * FROM test1 WHERE t = $1",
4566                                            1,           /* one param */
4567                                            NULL,        /* let the backend deduce param type */
4568                                            paramValues,
4569                                            NULL,        /* don't need param lengths since text */
4570                                            NULL,        /* default to all text params */
4571                                            1);          /* ask for binary results */
4572
4573         if (PQresultStatus(res) != PGRES_TUPLES_OK)
4574         {
4575                 fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
4576                 PQclear(res);
4577                 exit_nicely(conn);
4578         }
4579
4580         /* Use PQfnumber to avoid assumptions about field order in result */
4581         i_fnum = PQfnumber(res, "i");
4582         t_fnum = PQfnumber(res, "t");
4583         b_fnum = PQfnumber(res, "b");
4584
4585         for (i = 0; i &lt; PQntuples(res); i++)
4586         {
4587                 char       *iptr;
4588                 char       *tptr;
4589                 char       *bptr;
4590                 int                     blen;
4591                 int                     ival;
4592
4593                 /* Get the field values (we ignore possibility they are null!) */
4594                 iptr = PQgetvalue(res, i, i_fnum);
4595                 tptr = PQgetvalue(res, i, t_fnum);
4596                 bptr = PQgetvalue(res, i, b_fnum);
4597
4598                 /*
4599                  * The binary representation of INT4 is in network byte order,
4600                  * which we'd better coerce to the local byte order.
4601                  */
4602                 ival = ntohl(*((uint32_t *) iptr));
4603
4604                 /*
4605                  * The binary representation of TEXT is, well, text, and since
4606                  * libpq was nice enough to append a zero byte to it, it'll work
4607                  * just fine as a C string.
4608                  *
4609                  * The binary representation of BYTEA is a bunch of bytes, which
4610                  * could include embedded nulls so we have to pay attention to
4611                  * field length.
4612                  */
4613                 blen = PQgetlength(res, i, b_fnum);
4614
4615                 printf("tuple %d: got\n", i);
4616                 printf(" i = (%d bytes) %d\n",
4617                            PQgetlength(res, i, i_fnum), ival);
4618                 printf(" t = (%d bytes) '%s'\n",
4619                            PQgetlength(res, i, t_fnum), tptr);
4620                 printf(" b = (%d bytes) ", blen);
4621                 for (j = 0; j &lt; blen; j++)
4622                         printf("\\%03o", bptr[j]);
4623                 printf("\n\n");
4624         }
4625
4626         PQclear(res);
4627
4628         /* close the connection to the database and cleanup */
4629         PQfinish(conn);
4630
4631         return 0;
4632 }
4633 </programlisting>
4634   </example>
4635
4636  </sect1>
4637 </chapter>
4638
4639 <!-- Keep this comment at the end of the file
4640 Local variables:
4641 mode:sgml
4642 sgml-omittag:nil
4643 sgml-shorttag:t
4644 sgml-minimize-attributes:nil
4645 sgml-always-quote-attributes:t
4646 sgml-indent-step:1
4647 sgml-indent-data:t
4648 sgml-parent-document:nil
4649 sgml-default-dtd-file:"./reference.ced"
4650 sgml-exposed-tags:nil
4651 sgml-local-catalogs:("/usr/lib/sgml/catalog")
4652 sgml-local-ecat-files:nil
4653 End:
4654 -->