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