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