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