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