Debian Codegraph @

doc/src/sgml/libpq.sgml

raw
1 <!-- doc/src/sgml/libpq.sgml -->
2
3 <chapter id="libpq">
4 <title><application>libpq</application> &mdash; 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</productname>.
17 <application>libpq</application> is a set of library functions that allow
18 client programs to pass queries to the <productname>PostgreSQL</productname>
19 backend server and to receive the results of these queries.
20 </para>
21
22 <para>
23 <application>libpq</application> is also the underlying engine for several
24 other <productname>PostgreSQL</productname> application interfaces, including
25 those written for C++, Perl, Python, Tcl and <application>ECPG</application>.
26 So some aspects of <application>libpq</application>'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</application>.
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</primary></indexterm>
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</structname><indexterm><primary>PGconn</primary></indexterm> object, which
59 is obtained from the function <xref linkend="libpq-PQconnectdb"/>,
60 <xref linkend="libpq-PQconnectdbParams"/>, or
61 <xref linkend="libpq-PQsetdbLogin"/>. Note that these functions will always
62 return a non-null object pointer, unless perhaps there is too
63 little memory even to allocate the <structname>PGconn</structname> object.
64 The <xref linkend="libpq-PQstatus"/> function should be called to check
65 the return value for a successful connection before queries are sent
66 via the connection object.
67
68 <warning>
69 <para>
70 If untrusted users have access to a database that has not adopted a
71 <link linkend="ddl-schemas-patterns">secure schema usage pattern</link>,
72 begin each session by removing publicly-writable schemas from
73 <varname>search_path</varname>. One can set parameter key
74 word <literal>options</literal> to
75 value <literal>-csearch_path=</literal>. Alternately, one can
76 issue <literal>PQexec(<replaceable>conn</replaceable>, "SELECT
77 pg_catalog.set_config('search_path', '', false)")</literal> after
78 connecting. This consideration is not specific
79 to <application>libpq</application>; it applies to every interface for
80 executing arbitrary SQL commands.
81 </para>
82 </warning>
83
84 <warning>
85 <para>
86 On Unix, forking a process with open libpq connections can lead to
87 unpredictable results because the parent and child processes share
88 the same sockets and operating system resources. For this reason,
89 such usage is not recommended, though doing an <function>exec</function> from
90 the child process to load a new executable is safe.
91 </para>
92 </warning>
93
94 <variablelist>
95 <varlistentry id="libpq-PQconnectdbParams">
96 <term><function>PQconnectdbParams</function><indexterm><primary>PQconnectdbParams</primary></indexterm></term>
97 <listitem>
98 <para>
99 Makes a new connection to the database server.
100
101 <synopsis>
102 PGconn *PQconnectdbParams(const char * const *keywords,
103 const char * const *values,
104 int expand_dbname);
105 </synopsis>
106 </para>
107
108 <para>
109 This function opens a new database connection using the parameters taken
110 from two <symbol>NULL</symbol>-terminated arrays. The first,
111 <literal>keywords</literal>, is defined as an array of strings, each one
112 being a key word. The second, <literal>values</literal>, gives the value
113 for each key word. Unlike <xref linkend="libpq-PQsetdbLogin"/> below, the parameter
114 set can be extended without changing the function signature, so use of
115 this function (or its nonblocking analogs <xref linkend="libpq-PQconnectStartParams"/>
116 and <function>PQconnectPoll</function>) is preferred for new application
117 programming.
118 </para>
119
120 <para>
121 The currently recognized parameter key words are listed in
122 <xref linkend="libpq-paramkeywords"/>.
123 </para>
124
125 <para>
126 The passed arrays can be empty to use all default parameters, or can
127 contain one or more parameter settings. They must be matched in length.
128 Processing will stop at the first <symbol>NULL</symbol> entry
129 in the <literal>keywords</literal> array.
130 Also, if the <literal>values</literal> entry associated with a
131 non-<symbol>NULL</symbol> <literal>keywords</literal> entry is
132 <symbol>NULL</symbol> or an empty string, that entry is ignored and
133 processing continues with the next pair of array entries.
134 </para>
135
136 <para>
137 When <literal>expand_dbname</literal> is non-zero, the value for
138 the first <parameter>dbname</parameter> key word is checked to see
139 if it is a <firstterm>connection string</firstterm>. If so, it
140 is <quote>expanded</quote> into the individual connection
141 parameters extracted from the string. The value is considered to
142 be a connection string, rather than just a database name, if it
143 contains an equal sign (<literal>=</literal>) or it begins with a
144 URI scheme designator. (More details on connection string formats
145 appear in <xref linkend="libpq-connstring"/>.) Only the first
146 occurrence of <parameter>dbname</parameter> is treated in this way;
147 any subsequent <parameter>dbname</parameter> parameter is processed
148 as a plain database name.
149 </para>
150
151 <para>
152 In general the parameter arrays are processed from start to end.
153 If any key word is repeated, the last value (that is
154 not <symbol>NULL</symbol> or empty) is used. This rule applies in
155 particular when a key word found in a connection string conflicts
156 with one appearing in the <literal>keywords</literal> array. Thus,
157 the programmer may determine whether array entries can override or
158 be overridden by values taken from a connection string. Array
159 entries appearing before an expanded <parameter>dbname</parameter>
160 entry can be overridden by fields of the connection string, and in
161 turn those fields are overridden by array entries appearing
162 after <parameter>dbname</parameter> (but, again, only if those
163 entries supply non-empty values).
164 </para>
165
166 <para>
167 After processing all the array entries and any expanded connection
168 string, any connection parameters that remain unset are filled with
169 default values. If an unset parameter's corresponding environment
170 variable (see <xref linkend="libpq-envars"/>) is set, its value is
171 used. If the environment variable is not set either, then the
172 parameter's built-in default value is used.
173 </para>
174
175 </listitem>
176 </varlistentry>
177
178 <varlistentry id="libpq-PQconnectdb">
179 <term><function>PQconnectdb</function><indexterm><primary>PQconnectdb</primary></indexterm></term>
180 <listitem>
181 <para>
182 Makes a new connection to the database server.
183
184 <synopsis>
185 PGconn *PQconnectdb(const char *conninfo);
186 </synopsis>
187 </para>
188
189 <para>
190 This function opens a new database connection using the parameters taken
191 from the string <literal>conninfo</literal>.
192 </para>
193
194 <para>
195 The passed string can be empty to use all default parameters, or it can
196 contain one or more parameter settings separated by whitespace,
197 or it can contain a <acronym>URI</acronym>.
198 See <xref linkend="libpq-connstring"/> for details.
199 </para>
200
201
202 </listitem>
203 </varlistentry>
204
205 <varlistentry id="libpq-PQsetdbLogin">
206 <term><function>PQsetdbLogin</function><indexterm><primary>PQsetdbLogin</primary></indexterm></term>
207 <listitem>
208 <para>
209 Makes a new connection to the database server.
210 <synopsis>
211 PGconn *PQsetdbLogin(const char *pghost,
212 const char *pgport,
213 const char *pgoptions,
214 const char *pgtty,
215 const char *dbName,
216 const char *login,
217 const char *pwd);
218 </synopsis>
219 </para>
220
221 <para>
222 This is the predecessor of <xref linkend="libpq-PQconnectdb"/> with a fixed
223 set of parameters. It has the same functionality except that the
224 missing parameters will always take on default values. Write <symbol>NULL</symbol> or an
225 empty string for any one of the fixed parameters that is to be defaulted.
226 </para>
227
228 <para>
229 If the <parameter>dbName</parameter> contains
230 an <symbol>=</symbol> sign or has a valid connection <acronym>URI</acronym> prefix, it
231 is taken as a <parameter>conninfo</parameter> string in exactly the same way as
232 if it had been passed to <xref linkend="libpq-PQconnectdb"/>, and the remaining
233 parameters are then applied as specified for <xref linkend="libpq-PQconnectdbParams"/>.
234 </para>
235
236 <para>
237 <literal>pgtty</literal> is no longer used and any value passed will
238 be ignored.
239 </para>
240 </listitem>
241 </varlistentry>
242
243 <varlistentry id="libpq-PQsetdb">
244 <term><function>PQsetdb</function><indexterm><primary>PQsetdb</primary></indexterm></term>
245 <listitem>
246 <para>
247 Makes a new connection to the database server.
248 <synopsis>
249 PGconn *PQsetdb(char *pghost,
250 char *pgport,
251 char *pgoptions,
252 char *pgtty,
253 char *dbName);
254 </synopsis>
255 </para>
256
257 <para>
258 This is a macro that calls <xref linkend="libpq-PQsetdbLogin"/> with null pointers
259 for the <parameter>login</parameter> and <parameter>pwd</parameter> parameters. It is provided
260 for backward compatibility with very old programs.
261 </para>
262 </listitem>
263 </varlistentry>
264
265 <varlistentry id="libpq-PQconnectStartParams">
266 <term><function>PQconnectStartParams</function><indexterm><primary>PQconnectStartParams</primary></indexterm></term>
267 <term><function>PQconnectStart</function><indexterm><primary>PQconnectStart</primary></indexterm></term>
268 <term id="libpq-PQconnectPoll"><function>PQconnectPoll</function><indexterm><primary>PQconnectPoll</primary></indexterm></term>
269 <listitem>
270 <para>
271 <indexterm><primary>nonblocking connection</primary></indexterm>
272 Make a connection to the database server in a nonblocking manner.
273
274 <synopsis>
275 PGconn *PQconnectStartParams(const char * const *keywords,
276 const char * const *values,
277 int expand_dbname);
278
279 PGconn *PQconnectStart(const char *conninfo);
280
281 PostgresPollingStatusType PQconnectPoll(PGconn *conn);
282 </synopsis>
283 </para>
284
285 <para>
286 These three functions are used to open a connection to a database server such
287 that your application's thread of execution is not blocked on remote I/O
288 whilst doing so. The point of this approach is that the waits for I/O to
289 complete can occur in the application's main loop, rather than down inside
290 <xref linkend="libpq-PQconnectdbParams"/> or <xref linkend="libpq-PQconnectdb"/>, and so the
291 application can manage this operation in parallel with other activities.
292 </para>
293
294 <para>
295 With <xref linkend="libpq-PQconnectStartParams"/>, the database connection is made
296 using the parameters taken from the <literal>keywords</literal> and
297 <literal>values</literal> arrays, and controlled by <literal>expand_dbname</literal>,
298 as described above for <xref linkend="libpq-PQconnectdbParams"/>.
299 </para>
300
301 <para>
302 With <function>PQconnectStart</function>, the database connection is made
303 using the parameters taken from the string <literal>conninfo</literal> as
304 described above for <xref linkend="libpq-PQconnectdb"/>.
305 </para>
306
307 <para>
308 Neither <xref linkend="libpq-PQconnectStartParams"/> nor <function>PQconnectStart</function>
309 nor <function>PQconnectPoll</function> will block, so long as a number of
310 restrictions are met:
311 <itemizedlist>
312 <listitem>
313 <para>
314 The <literal>hostaddr</literal> parameter must be used appropriately
315 to prevent DNS queries from being made. See the documentation of
316 this parameter in <xref linkend="libpq-paramkeywords"/> for details.
317 </para>
318 </listitem>
319
320 <listitem>
321 <para>
322 If you call <xref linkend="libpq-PQtrace"/>, ensure that the stream object
323 into which you trace will not block.
324 </para>
325 </listitem>
326
327 <listitem>
328 <para>
329 You must ensure that the socket is in the appropriate state
330 before calling <function>PQconnectPoll</function>, as described below.
331 </para>
332 </listitem>
333 </itemizedlist>
334 </para>
335
336 <para>
337 To begin a nonblocking connection request,
338 call <function>PQconnectStart</function>
339 or <xref linkend="libpq-PQconnectStartParams"/>. If the result is null,
340 then <application>libpq</application> has been unable to allocate a
341 new <structname>PGconn</structname> structure. Otherwise, a
342 valid <structname>PGconn</structname> pointer is returned (though not
343 yet representing a valid connection to the database). Next
344 call <literal>PQstatus(conn)</literal>. If the result
345 is <symbol>CONNECTION_BAD</symbol>, the connection attempt has already
346 failed, typically because of invalid connection parameters.
347 </para>
348
349 <para>
350 If <function>PQconnectStart</function>
351 or <xref linkend="libpq-PQconnectStartParams"/> succeeds, the next stage
352 is to poll <application>libpq</application> so that it can proceed with
353 the connection sequence.
354 Use <function>PQsocket(conn)</function> to obtain the descriptor of the
355 socket underlying the database connection.
356 (Caution: do not assume that the socket remains the same
357 across <function>PQconnectPoll</function> calls.)
358 Loop thus: If <function>PQconnectPoll(conn)</function> last returned
359 <symbol>PGRES_POLLING_READING</symbol>, wait until the socket is ready to
360 read (as indicated by <function>select()</function>, <function>poll()</function>, or
361 similar system function). Note that <function>PQsocketPoll</function>
362 can help reduce boilerplate by abstracting the setup of
363 <function>select(2)</function> or <function>poll(2)</function> if it is
364 available on your system.
365 Then call <function>PQconnectPoll(conn)</function> again.
366 Conversely, if <function>PQconnectPoll(conn)</function> last returned
367 <symbol>PGRES_POLLING_WRITING</symbol>, wait until the socket is ready
368 to write, then call <function>PQconnectPoll(conn)</function> again.
369 On the first iteration, i.e., if you have yet to call
370 <function>PQconnectPoll</function>, behave as if it last returned
371 <symbol>PGRES_POLLING_WRITING</symbol>. Continue this loop until
372 <function>PQconnectPoll(conn)</function> returns
373 <symbol>PGRES_POLLING_FAILED</symbol>, indicating the connection procedure
374 has failed, or <symbol>PGRES_POLLING_OK</symbol>, indicating the connection
375 has been successfully made.
376 </para>
377
378 <para>
379 At any time during connection, the status of the connection can be
380 checked by calling <xref linkend="libpq-PQstatus"/>. If this call returns <symbol>CONNECTION_BAD</symbol>, then the
381 connection procedure has failed; if the call returns <symbol>CONNECTION_OK</symbol>, then the
382 connection is ready. Both of these states are equally detectable
383 from the return value of <function>PQconnectPoll</function>, described above. Other states might also occur
384 during (and only during) an asynchronous connection procedure. These
385 indicate the current stage of the connection procedure and might be useful
386 to provide feedback to the user for example. These statuses are:
387
388 <variablelist>
389 <varlistentry id="libpq-connection-started">
390 <term><symbol>CONNECTION_STARTED</symbol></term>
391 <listitem>
392 <para>
393 Waiting for connection to be made.
394 </para>
395 </listitem>
396 </varlistentry>
397
398 <varlistentry id="libpq-connection-made">
399 <term><symbol>CONNECTION_MADE</symbol></term>
400 <listitem>
401 <para>
402 Connection OK; waiting to send.
403 </para>
404 </listitem>
405 </varlistentry>
406
407 <varlistentry id="libpq-connection-awaiting-response">
408 <term><symbol>CONNECTION_AWAITING_RESPONSE</symbol></term>
409 <listitem>
410 <para>
411 Waiting for a response from the server.
412 </para>
413 </listitem>
414 </varlistentry>
415
416 <varlistentry id="libpq-connection-auth-ok">
417 <term><symbol>CONNECTION_AUTH_OK</symbol></term>
418 <listitem>
419 <para>
420 Received authentication; waiting for backend start-up to finish.
421 </para>
422 </listitem>
423 </varlistentry>
424
425 <varlistentry id="libpq-connection-ssl-startup">
426 <term><symbol>CONNECTION_SSL_STARTUP</symbol></term>
427 <listitem>
428 <para>
429 Negotiating SSL encryption.
430 </para>
431 </listitem>
432 </varlistentry>
433
434 <varlistentry id="libpq-connection-gss-startup">
435 <term><symbol>CONNECTION_GSS_STARTUP</symbol></term>
436 <listitem>
437 <para>
438 Negotiating GSS encryption.
439 </para>
440 </listitem>
441 </varlistentry>
442
443 <varlistentry id="libpq-connection-check-writable">
444 <term><symbol>CONNECTION_CHECK_WRITABLE</symbol></term>
445 <listitem>
446 <para>
447 Checking if connection is able to handle write transactions.
448 </para>
449 </listitem>
450 </varlistentry>
451
452 <varlistentry id="libpq-connection-check-standby">
453 <term><symbol>CONNECTION_CHECK_STANDBY</symbol></term>
454 <listitem>
455 <para>
456 Checking if connection is to a server in standby mode.
457 </para>
458 </listitem>
459 </varlistentry>
460
461 <varlistentry id="libpq-connection-consume">
462 <term><symbol>CONNECTION_CONSUME</symbol></term>
463 <listitem>
464 <para>
465 Consuming any remaining response messages on connection.
466 </para>
467 </listitem>
468 </varlistentry>
469 </variablelist>
470
471 Note that, although these constants will remain (in order to maintain
472 compatibility), an application should never rely upon these occurring in a
473 particular order, or at all, or on the status always being one of these
474 documented values. An application might do something like this:
475 <programlisting>
476 switch(PQstatus(conn))
477 {
478 case CONNECTION_STARTED:
479 feedback = "Connecting...";
480 break;
481
482 case CONNECTION_MADE:
483 feedback = "Connected to server...";
484 break;
485 .
486 .
487 .
488 default:
489 feedback = "Connecting...";
490 }
491 </programlisting>
492 </para>
493
494 <para>
495 The <literal>connect_timeout</literal> connection parameter is ignored
496 when using <function>PQconnectPoll</function>; it is the application's
497 responsibility to decide whether an excessive amount of time has elapsed.
498 Otherwise, <function>PQconnectStart</function> followed by a
499 <function>PQconnectPoll</function> loop is equivalent to
500 <xref linkend="libpq-PQconnectdb"/>.
501 </para>
502
503 <para>
504 Note that when <function>PQconnectStart</function>
505 or <xref linkend="libpq-PQconnectStartParams"/> returns a non-null
506 pointer, you must call <xref linkend="libpq-PQfinish"/> when you are
507 finished with it, in order to dispose of the structure and any
508 associated memory blocks. This must be done even if the connection
509 attempt fails or is abandoned.
510 </para>
511 </listitem>
512 </varlistentry>
513
514 <varlistentry id="libpq-PQsocketPoll">
515 <term><function>PQsocketPoll</function><indexterm><primary>PQsocketPoll</primary></indexterm></term>
516 <listitem>
517 <para>
518 <indexterm><primary>nonblocking connection</primary></indexterm>
519 Poll a connection's underlying socket descriptor retrieved with
520 <xref linkend="libpq-PQsocket"/>.
521 The primary use of this function is iterating through the connection
522 sequence described in the documentation of
523 <xref linkend="libpq-PQconnectStartParams"/>.
524 <synopsis>
525 typedef int64_t pg_usec_time_t;
526
527 int PQsocketPoll(int sock, int forRead, int forWrite,
528 pg_usec_time_t end_time);
529 </synopsis>
530 </para>
531
532 <para>
533 This function performs polling of a file descriptor, optionally with
534 a timeout.
535 If <parameter>forRead</parameter> is nonzero, the
536 function will terminate when the socket is ready for
537 reading. If <parameter>forWrite</parameter> is nonzero,
538 the function will terminate when the
539 socket is ready for writing.
540 </para>
541
542 <para>
543 The timeout is specified by <parameter>end_time</parameter>, which
544 is the time to stop waiting expressed as a number of microseconds since
545 the Unix epoch (that is, <type>time_t</type> times 1 million).
546 Timeout is infinite if <parameter>end_time</parameter>
547 is <literal>-1</literal>. Timeout is immediate (no blocking) if
548 <parameter>end_time</parameter> is <literal>0</literal> (or indeed, any
549 time before now). Timeout values can be calculated conveniently by
550 adding the desired number of microseconds to the result of
551 <xref linkend="libpq-PQgetCurrentTimeUSec"/>.
552 Note that the underlying system calls may have less than microsecond
553 precision, so that the actual delay may be imprecise.
554 </para>
555
556 <para>
557 The function returns a value greater than <literal>0</literal> if the
558 specified condition is met, <literal>0</literal> if a timeout occurred,
559 or <literal>-1</literal> if an error occurred. The error can be
560 retrieved by checking the <literal>errno(3)</literal> value. In the
561 event both <parameter>forRead</parameter>
562 and <parameter>forWrite</parameter> are zero, the function immediately
563 returns a timeout indication.
564 </para>
565
566 <para>
567 <function>PQsocketPoll</function> is implemented using either
568 <function>poll(2)</function> or <function>select(2)</function>,
569 depending on platform. See <literal>POLLIN</literal>
570 and <literal>POLLOUT</literal> from <function>poll(2)</function>,
571 or <parameter>readfds</parameter> and
572 <parameter>writefds</parameter> from <function>select(2)</function>,
573 for more information.
574 </para>
575 </listitem>
576 </varlistentry>
577
578 <varlistentry id="libpq-PQconndefaults">
579 <term><function>PQconndefaults</function><indexterm><primary>PQconndefaults</primary></indexterm></term>
580 <listitem>
581 <para>
582 Returns the default connection options.
583 <synopsis>
584 PQconninfoOption *PQconndefaults(void);
585
586 typedef struct
587 {
588 char *keyword; /* The keyword of the option */
589 char *envvar; /* Fallback environment variable name */
590 char *compiled; /* Fallback compiled in default value */
591 char *val; /* Option's current value, or NULL */
592 char *label; /* Label for field in connect dialog */
593 char *dispchar; /* Indicates how to display this field
594 in a connect dialog. Values are:
595 "" Display entered value as is
596 "*" Password field - hide value
597 "D" Debug option - don't show by default */
598 int dispsize; /* Field size in characters for dialog */
599 } PQconninfoOption;
600 </synopsis>
601 </para>
602
603 <para>
604 Returns a connection options array. This can be used to determine
605 all possible <xref linkend="libpq-PQconnectdb"/> options and their
606 current default values. The return value points to an array of
607 <structname>PQconninfoOption</structname> structures, which ends
608 with an entry having a null <structfield>keyword</structfield> pointer. The
609 null pointer is returned if memory could not be allocated. Note that
610 the current default values (<structfield>val</structfield> fields)
611 will depend on environment variables and other context. A
612 missing or invalid service file will be silently ignored. Callers
613 must treat the connection options data as read-only.
614 </para>
615
616 <para>
617 After processing the options array, free it by passing it to
618 <xref linkend="libpq-PQconninfoFree"/>. If this is not done, a small amount of memory
619 is leaked for each call to <xref linkend="libpq-PQconndefaults"/>.
620 </para>
621
622 </listitem>
623 </varlistentry>
624
625 <varlistentry id="libpq-PQconninfo">
626 <term><function>PQconninfo</function><indexterm><primary>PQconninfo</primary></indexterm></term>
627 <listitem>
628 <para>
629 Returns the connection options used by a live connection.
630 <synopsis>
631 PQconninfoOption *PQconninfo(PGconn *conn);
632 </synopsis>
633 </para>
634
635 <para>
636 Returns a connection options array. This can be used to determine
637 all possible <xref linkend="libpq-PQconnectdb"/> options and the
638 values that were used to connect to the server. The return
639 value points to an array of <structname>PQconninfoOption</structname>
640 structures, which ends with an entry having a null <structfield>keyword</structfield>
641 pointer. All notes above for <xref linkend="libpq-PQconndefaults"/> also
642 apply to the result of <xref linkend="libpq-PQconninfo"/>.
643 </para>
644
645 </listitem>
646 </varlistentry>
647
648
649 <varlistentry id="libpq-PQconninfoParse">
650 <term><function>PQconninfoParse</function><indexterm><primary>PQconninfoParse</primary></indexterm></term>
651 <listitem>
652 <para>
653 Returns parsed connection options from the provided connection string.
654
655 <synopsis>
656 PQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg);
657 </synopsis>
658 </para>
659
660 <para>
661 Parses a connection string and returns the resulting options as an
662 array; or returns <symbol>NULL</symbol> if there is a problem with the connection
663 string. This function can be used to extract
664 the <xref linkend="libpq-PQconnectdb"/> options in the provided
665 connection string. The return value points to an array of
666 <structname>PQconninfoOption</structname> structures, which ends
667 with an entry having a null <structfield>keyword</structfield> pointer.
668 </para>
669
670 <para>
671 All legal options will be present in the result array, but the
672 <literal>PQconninfoOption</literal> for any option not present
673 in the connection string will have <literal>val</literal> set to
674 <literal>NULL</literal>; default values are not inserted.
675 </para>
676
677 <para>
678 If <literal>errmsg</literal> is not <symbol>NULL</symbol>, then <literal>*errmsg</literal> is set
679 to <symbol>NULL</symbol> on success, else to a <function>malloc</function>'d error string explaining
680 the problem. (It is also possible for <literal>*errmsg</literal> to be
681 set to <symbol>NULL</symbol> and the function to return <symbol>NULL</symbol>;
682 this indicates an out-of-memory condition.)
683 </para>
684
685 <para>
686 After processing the options array, free it by passing it to
687 <xref linkend="libpq-PQconninfoFree"/>. If this is not done, some memory
688 is leaked for each call to <xref linkend="libpq-PQconninfoParse"/>.
689 Conversely, if an error occurs and <literal>errmsg</literal> is not <symbol>NULL</symbol>,
690 be sure to free the error string using <xref linkend="libpq-PQfreemem"/>.
691 </para>
692
693 </listitem>
694 </varlistentry>
695
696 <varlistentry id="libpq-PQfinish">
697 <term><function>PQfinish</function><indexterm><primary>PQfinish</primary></indexterm></term>
698 <listitem>
699 <para>
700 Closes the connection to the server. Also frees
701 memory used by the <structname>PGconn</structname> object.
702 <synopsis>
703 void PQfinish(PGconn *conn);
704 </synopsis>
705 </para>
706
707 <para>
708 Note that even if the server connection attempt fails (as
709 indicated by <xref linkend="libpq-PQstatus"/>), the application should call <xref linkend="libpq-PQfinish"/>
710 to free the memory used by the <structname>PGconn</structname> object.
711 The <structname>PGconn</structname> pointer must not be used again after
712 <xref linkend="libpq-PQfinish"/> has been called.
713 </para>
714 </listitem>
715 </varlistentry>
716
717 <varlistentry id="libpq-PQreset">
718 <term><function>PQreset</function><indexterm><primary>PQreset</primary></indexterm></term>
719 <listitem>
720 <para>
721 Resets the communication channel to the server.
722 <synopsis>
723 void PQreset(PGconn *conn);
724 </synopsis>
725 </para>
726
727 <para>
728 This function will close the connection
729 to the server and attempt to establish a new
730 connection, using all the same
731 parameters previously used. This might be useful for
732 error recovery if a working connection is lost.
733 </para>
734 </listitem>
735 </varlistentry>
736
737 <varlistentry id="libpq-PQresetStart">
738 <term><function>PQresetStart</function><indexterm><primary>PQresetStart</primary></indexterm></term>
739 <term><function>PQresetPoll</function><indexterm><primary>PQresetPoll</primary></indexterm></term>
740 <listitem>
741 <para>
742 Reset the communication channel to the server, in a nonblocking manner.
743
744 <synopsis>
745 int PQresetStart(PGconn *conn);
746
747 PostgresPollingStatusType PQresetPoll(PGconn *conn);
748 </synopsis>
749 </para>
750
751 <para>
752 These functions will close the connection to the server and attempt to
753 establish a new connection, using all the same
754 parameters previously used. This can be useful for error recovery if a
755 working connection is lost. They differ from <xref linkend="libpq-PQreset"/> (above) in that they
756 act in a nonblocking manner. These functions suffer from the same
757 restrictions as <xref linkend="libpq-PQconnectStartParams"/>, <function>PQconnectStart</function>
758 and <function>PQconnectPoll</function>.
759 </para>
760
761 <para>
762 To initiate a connection reset, call
763 <xref linkend="libpq-PQresetStart"/>. If it returns 0, the reset has
764 failed. If it returns 1, poll the reset using
765 <function>PQresetPoll</function> in exactly the same way as you
766 would create the connection using <function>PQconnectPoll</function>.
767 </para>
768 </listitem>
769 </varlistentry>
770
771 <varlistentry id="libpq-PQpingParams">
772 <term><function>PQpingParams</function><indexterm><primary>PQpingParams</primary></indexterm></term>
773 <listitem>
774 <para>
775 <xref linkend="libpq-PQpingParams"/> reports the status of the
776 server. It accepts connection parameters identical to those of
777 <xref linkend="libpq-PQconnectdbParams"/>, described above. It is not
778 necessary to supply correct user name, password, or database name
779 values to obtain the server status; however, if incorrect values
780 are provided, the server will log a failed connection attempt.
781
782 <synopsis>
783 PGPing PQpingParams(const char * const *keywords,
784 const char * const *values,
785 int expand_dbname);
786 </synopsis>
787
788 The function returns one of the following values:
789
790 <variablelist>
791 <varlistentry id="libpq-PQpingParams-PQPING_OK">
792 <term><literal>PQPING_OK</literal></term>
793 <listitem>
794 <para>
795 The server is running and appears to be accepting connections.
796 </para>
797 </listitem>
798 </varlistentry>
799
800 <varlistentry id="libpq-PQpingParams-PQPING_REJECT">
801 <term><literal>PQPING_REJECT</literal></term>
802 <listitem>
803 <para>
804 The server is running but is in a state that disallows connections
805 (startup, shutdown, or crash recovery).
806 </para>
807 </listitem>
808 </varlistentry>
809
810 <varlistentry id="libpq-PQpingParams-PQPING_NO_RESPONSE">
811 <term><literal>PQPING_NO_RESPONSE</literal></term>
812 <listitem>
813 <para>
814 The server could not be contacted. This might indicate that the
815 server is not running, or that there is something wrong with the
816 given connection parameters (for example, wrong port number), or
817 that there is a network connectivity problem (for example, a
818 firewall blocking the connection request).
819 </para>
820 </listitem>
821 </varlistentry>
822
823 <varlistentry id="libpq-PQpingParams-PQPING_NO_ATTEMPT">
824 <term><literal>PQPING_NO_ATTEMPT</literal></term>
825 <listitem>
826 <para>
827 No attempt was made to contact the server, because the supplied
828 parameters were obviously incorrect or there was some client-side
829 problem (for example, out of memory).
830 </para>
831 </listitem>
832 </varlistentry>
833 </variablelist>
834
835 </para>
836
837 </listitem>
838 </varlistentry>
839
840 <varlistentry id="libpq-PQping">
841 <term><function>PQping</function><indexterm><primary>PQping</primary></indexterm></term>
842 <listitem>
843 <para>
844 <xref linkend="libpq-PQping"/> reports the status of the
845 server. It accepts connection parameters identical to those of
846 <xref linkend="libpq-PQconnectdb"/>, described above. It is not
847 necessary to supply correct user name, password, or database name
848 values to obtain the server status; however, if incorrect values
849 are provided, the server will log a failed connection attempt.
850
851 <synopsis>
852 PGPing PQping(const char *conninfo);
853 </synopsis>
854 </para>
855
856 <para>
857 The return values are the same as for <xref linkend="libpq-PQpingParams"/>.
858 </para>
859
860 </listitem>
861 </varlistentry>
862
863 <varlistentry id="libpq-pqsetsslkeypasshook-openssl">
864 <term><function>PQsetSSLKeyPassHook_OpenSSL</function><indexterm><primary>PQsetSSLKeyPassHook_OpenSSL</primary></indexterm></term>
865 <listitem>
866 <para>
867 <function>PQsetSSLKeyPassHook_OpenSSL</function> lets an application override
868 <application>libpq</application>'s <link linkend="libpq-ssl-clientcert">default
869 handling of encrypted client certificate key files</link> using
870 <xref linkend="libpq-connect-sslpassword"/> or interactive prompting.
871
872 <synopsis>
873 void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook);
874 </synopsis>
875
876 The application passes a pointer to a callback function with signature:
877 <programlisting>
878 int callback_fn(char *buf, int size, PGconn *conn);
879 </programlisting>
880 which <application>libpq</application> will then call
881 <emphasis>instead of</emphasis> its default
882 <function>PQdefaultSSLKeyPassHook_OpenSSL</function> handler. The
883 callback should determine the password for the key and copy it to
884 result-buffer <parameter>buf</parameter> of size
885 <parameter>size</parameter>. The string in <parameter>buf</parameter>
886 must be null-terminated. The callback must return the length of the
887 password stored in <parameter>buf</parameter> excluding the null
888 terminator. On failure, the callback should set
889 <literal>buf[0] = '\0'</literal> and return 0. See
890 <function>PQdefaultSSLKeyPassHook_OpenSSL</function> in
891 <application>libpq</application>'s source code for an example.
892 </para>
893
894 <para>
895 If the user specified an explicit key location,
896 its path will be in <literal>conn->sslkey</literal> when the callback
897 is invoked. This will be empty if the default key path is being used.
898 For keys that are engine specifiers, it is up to engine implementations
899 whether they use the <productname>OpenSSL</productname> password
900 callback or define their own handling.
901 </para>
902
903 <para>
904 The app callback may choose to delegate unhandled cases to
905 <function>PQdefaultSSLKeyPassHook_OpenSSL</function>,
906 or call it first and try something else if it returns 0, or completely override it.
907 </para>
908
909 <para>
910 The callback <emphasis>must not</emphasis> escape normal flow control with exceptions,
911 <function>longjmp(...)</function>, etc. It must return normally.
912 </para>
913
914 </listitem>
915 </varlistentry>
916
917 <varlistentry id="libpq-pqgetsslkeypasshook-openssl">
918 <term><function>PQgetSSLKeyPassHook_OpenSSL</function><indexterm><primary>PQgetSSLKeyPassHook_OpenSSL</primary></indexterm></term>
919 <listitem>
920 <para>
921 <function>PQgetSSLKeyPassHook_OpenSSL</function> returns the current
922 client certificate key password hook, or <literal>NULL</literal>
923 if none has been set.
924
925 <synopsis>
926 PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void);
927 </synopsis>
928 </para>
929
930 </listitem>
931 </varlistentry>
932
933 </variablelist>
934 </para>
935
936 <sect2 id="libpq-connstring">
937 <title>Connection Strings</title>
938
939 <indexterm zone="libpq-connstring">
940 <primary><literal>conninfo</literal></primary>
941 </indexterm>
942
943 <indexterm zone="libpq-connstring">
944 <primary><literal>URI</literal></primary>
945 </indexterm>
946
947 <para>
948 Several <application>libpq</application> functions parse a user-specified string to obtain
949 connection parameters. There are two accepted formats for these strings:
950 plain keyword/value strings
951 and URIs. URIs generally follow
952 <ulink url="https://datatracker.ietf.org/doc/html/rfc3986">RFC
953 3986</ulink>, except that multi-host connection strings are allowed
954 as further described below.
955 </para>
956
957 <sect3 id="libpq-connstring-keyword-value">
958 <title>Keyword/Value Connection Strings</title>
959
960 <para>
961 In the keyword/value format, each parameter setting is in the form
962 <replaceable>keyword</replaceable> <literal>=</literal>
963 <replaceable>value</replaceable>, with space(s) between settings.
964 Spaces around a setting's equal sign are
965 optional. To write an empty value, or a value containing spaces, surround it
966 with single quotes, for example <literal>keyword = 'a value'</literal>.
967 Single quotes and backslashes within
968 a value must be escaped with a backslash, i.e., <literal>\'</literal> and
969 <literal>\\</literal>.
970 </para>
971
972 <para>
973 Example:
974 <programlisting>
975 host=localhost port=5432 dbname=mydb connect_timeout=10
976 </programlisting>
977 </para>
978
979 <para>
980 The recognized parameter key words are listed in <xref
981 linkend="libpq-paramkeywords"/>.
982 </para>
983 </sect3>
984
985 <sect3 id="libpq-connstring-uris">
986 <title>Connection URIs</title>
987
988 <para>
989 The general form for a connection <acronym>URI</acronym> is:
990 <synopsis>
991 postgresql://<optional><replaceable>userspec</replaceable>@</optional><optional><replaceable>hostspec</replaceable></optional><optional>/<replaceable>dbname</replaceable></optional><optional>?<replaceable>paramspec</replaceable></optional>
992
993 <phrase>where <replaceable>userspec</replaceable> is:</phrase>
994
995 <replaceable>user</replaceable><optional>:<replaceable>password</replaceable></optional>
996
997 <phrase>and <replaceable>hostspec</replaceable> is:</phrase>
998
999 <optional><replaceable>host</replaceable></optional><optional>:<replaceable>port</replaceable></optional><optional>,...</optional>
1000
1001 <phrase>and <replaceable>paramspec</replaceable> is:</phrase>
1002
1003 <replaceable>name</replaceable>=<replaceable>value</replaceable><optional>&amp;...</optional>
1004 </synopsis>
1005 </para>
1006
1007 <para>
1008 The <acronym>URI</acronym> scheme designator can be either
1009 <literal>postgresql://</literal> or <literal>postgres://</literal>. Each
1010 of the remaining <acronym>URI</acronym> parts is optional. The
1011 following examples illustrate valid <acronym>URI</acronym> syntax:
1012 <programlisting>
1013 postgresql://
1014 postgresql://localhost
1015 postgresql://localhost:5433
1016 postgresql://localhost/mydb
1017 postgresql://user@localhost
1018 postgresql://user:secret@localhost
1019 postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp
1020 postgresql://host1:123,host2:456/somedb?target_session_attrs=any&amp;application_name=myapp
1021 </programlisting>
1022 Values that would normally appear in the hierarchical part of
1023 the <acronym>URI</acronym> can alternatively be given as named
1024 parameters. For example:
1025 <programlisting>
1026 postgresql:///mydb?host=localhost&amp;port=5433
1027 </programlisting>
1028 All named parameters must match key words listed in
1029 <xref linkend="libpq-paramkeywords"/>, except that for compatibility
1030 with JDBC connection <acronym>URI</acronym>s, instances
1031 of <literal>ssl=true</literal> are translated into
1032 <literal>sslmode=require</literal>.
1033 </para>
1034
1035 <para>
1036 The connection <acronym>URI</acronym> needs to be encoded with <ulink
1037 url="https://datatracker.ietf.org/doc/html/rfc3986#section-2.1">percent-encoding</ulink>
1038 if it includes symbols with special meaning in any of its parts. Here is
1039 an example where the equal sign (<literal>=</literal>) is replaced with
1040 <literal>%3D</literal> and the space character with
1041 <literal>%20</literal>:
1042 <programlisting>
1043 postgresql://user@localhost:5433/mydb?options=-c%20synchronous_commit%3Doff
1044 </programlisting>
1045 </para>
1046
1047 <para>
1048 The host part may be either a host name or an IP address. To specify an
1049 IPv6 address, enclose it in square brackets:
1050 <synopsis>
1051 postgresql://[2001:db8::1234]/database
1052 </synopsis>
1053 </para>
1054
1055 <para>
1056 The host part is interpreted as described for the parameter <xref
1057 linkend="libpq-connect-host"/>. In particular, a Unix-domain socket
1058 connection is chosen if the host part is either empty or looks like an
1059 absolute path name,
1060 otherwise a TCP/IP connection is initiated. Note, however, that the
1061 slash is a reserved character in the hierarchical part of the URI. So, to
1062 specify a non-standard Unix-domain socket directory, either omit the host
1063 part of the URI and specify the host as a named parameter, or
1064 percent-encode the path in the host part of the URI:
1065 <programlisting>
1066 postgresql:///dbname?host=/var/lib/postgresql
1067 postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
1068 </programlisting>
1069 </para>
1070
1071 <para>
1072 It is possible to specify multiple host components, each with an optional
1073 port component, in a single URI. A URI of the form
1074 <literal>postgresql://host1:port1,host2:port2,host3:port3/</literal>
1075 is equivalent to a connection string of the form
1076 <literal>host=host1,host2,host3 port=port1,port2,port3</literal>.
1077 As further described below, each
1078 host will be tried in turn until a connection is successfully established.
1079 </para>
1080 </sect3>
1081
1082 <sect3 id="libpq-multiple-hosts">
1083 <title>Specifying Multiple Hosts</title>
1084
1085 <para>
1086 It is possible to specify multiple hosts to connect to, so that they are
1087 tried in the given order. In the Keyword/Value format, the <literal>host</literal>,
1088 <literal>hostaddr</literal>, and <literal>port</literal> options accept comma-separated
1089 lists of values. The same number of elements must be given in each
1090 option that is specified, such
1091 that e.g., the first <literal>hostaddr</literal> corresponds to the first host name,
1092 the second <literal>hostaddr</literal> corresponds to the second host name, and so
1093 forth. As an exception, if only one <literal>port</literal> is specified, it
1094 applies to all the hosts.
1095 </para>
1096
1097 <para>
1098 In the connection URI format, you can list multiple <literal>host:port</literal> pairs
1099 separated by commas in the <literal>host</literal> component of the URI.
1100 </para>
1101
1102 <para>
1103 In either format, a single host name can translate to multiple network
1104 addresses. A common example of this is a host that has both an IPv4 and
1105 an IPv6 address.
1106 </para>
1107
1108 <para>
1109 When multiple hosts are specified, or when a single host name is
1110 translated to multiple addresses, all the hosts and addresses will be
1111 tried in order, until one succeeds. If none of the hosts can be reached,
1112 the connection fails. If a connection is established successfully, but
1113 authentication fails, the remaining hosts in the list are not tried.
1114 </para>
1115
1116 <para>
1117 If a password file is used, you can have different passwords for
1118 different hosts. All the other connection options are the same for every
1119 host in the list; it is not possible to e.g., specify different
1120 usernames for different hosts.
1121 </para>
1122 </sect3>
1123 </sect2>
1124
1125 <sect2 id="libpq-paramkeywords">
1126 <title>Parameter Key Words</title>
1127
1128 <para>
1129 The currently recognized parameter key words are:
1130
1131 <variablelist>
1132 <varlistentry id="libpq-connect-host" xreflabel="host">
1133 <term><literal>host</literal></term>
1134 <listitem>
1135 <para>
1136 Name of host to connect to.<indexterm><primary>host
1137 name</primary></indexterm> If a host name looks like an absolute path
1138 name, it specifies Unix-domain communication rather than TCP/IP
1139 communication; the value is the name of the directory in which the
1140 socket file is stored. (On Unix, an absolute path name begins with a
1141 slash. On Windows, paths starting with drive letters are also
1142 recognized.) If the host name starts with <literal>@</literal>, it is
1143 taken as a Unix-domain socket in the abstract namespace (currently
1144 supported on Linux and Windows).
1145 The default behavior when <literal>host</literal> is not
1146 specified, or is empty, is to connect to a Unix-domain
1147 socket<indexterm><primary>Unix domain socket</primary></indexterm> in
1148 <filename>/tmp</filename> (or whatever socket directory was specified
1149 when <productname>PostgreSQL</productname> was built). On Windows,
1150 the default is to connect to <literal>localhost</literal>.
1151 </para>
1152 <para>
1153 A comma-separated list of host names is also accepted, in which case
1154 each host name in the list is tried in order; an empty item in the
1155 list selects the default behavior as explained above. See
1156 <xref linkend="libpq-multiple-hosts"/> for details.
1157 </para>
1158 </listitem>
1159 </varlistentry>
1160
1161 <varlistentry id="libpq-connect-hostaddr" xreflabel="hostaddr">
1162 <term><literal>hostaddr</literal></term>
1163 <listitem>
1164 <para>
1165 Numeric IP address of host to connect to. This should be in the
1166 standard IPv4 address format, e.g., <literal>172.28.40.9</literal>. If
1167 your machine supports IPv6, you can also use those addresses.
1168 TCP/IP communication is
1169 always used when a nonempty string is specified for this parameter.
1170 If this parameter is not specified, the value of <literal>host</literal>
1171 will be looked up to find the corresponding IP address &mdash; or, if
1172 <literal>host</literal> specifies an IP address, that value will be
1173 used directly.
1174 </para>
1175
1176 <para>
1177 Using <literal>hostaddr</literal> allows the
1178 application to avoid a host name look-up, which might be important
1179 in applications with time constraints. However, a host name is
1180 required for GSSAPI or SSPI authentication
1181 methods, as well as for <literal>verify-full</literal> SSL
1182 certificate verification. The following rules are used:
1183 <itemizedlist>
1184 <listitem>
1185 <para>
1186 If <literal>host</literal> is specified
1187 without <literal>hostaddr</literal>, a host name lookup occurs.
1188 (When using <function>PQconnectPoll</function>, the lookup occurs
1189 when <function>PQconnectPoll</function> first considers this host
1190 name, and it may cause <function>PQconnectPoll</function> to block
1191 for a significant amount of time.)
1192 </para>
1193 </listitem>
1194 <listitem>
1195 <para>
1196 If <literal>hostaddr</literal> is specified without <literal>host</literal>,
1197 the value for <literal>hostaddr</literal> gives the server network address.
1198 The connection attempt will fail if the authentication
1199 method requires a host name.
1200 </para>
1201 </listitem>
1202 <listitem>
1203 <para>
1204 If both <literal>host</literal> and <literal>hostaddr</literal> are specified,
1205 the value for <literal>hostaddr</literal> gives the server network address.
1206 The value for <literal>host</literal> is ignored unless the
1207 authentication method requires it, in which case it will be
1208 used as the host name.
1209 </para>
1210 </listitem>
1211 </itemizedlist>
1212 Note that authentication is likely to fail if <literal>host</literal>
1213 is not the name of the server at network address <literal>hostaddr</literal>.
1214 Also, when both <literal>host</literal> and <literal>hostaddr</literal>
1215 are specified, <literal>host</literal>
1216 is used to identify the connection in a password file (see
1217 <xref linkend="libpq-pgpass"/>).
1218 </para>
1219
1220 <para>
1221 A comma-separated list of <literal>hostaddr</literal> values is also
1222 accepted, in which case each host in the list is tried in order.
1223 An empty item in the list causes the corresponding host name to be
1224 used, or the default host name if that is empty as well. See
1225 <xref linkend="libpq-multiple-hosts"/> for details.
1226 </para>
1227 <para>
1228 Without either a host name or host address,
1229 <application>libpq</application> will connect using a local
1230 Unix-domain socket; or on Windows, it will attempt to connect to
1231 <literal>localhost</literal>.
1232 </para>
1233 </listitem>
1234 </varlistentry>
1235
1236 <varlistentry id="libpq-connect-port" xreflabel="port">
1237 <term><literal>port</literal></term>
1238 <listitem>
1239 <para>
1240 Port number to connect to at the server host, or socket file
1241 name extension for Unix-domain
1242 connections.<indexterm><primary>port</primary></indexterm>
1243 If multiple hosts were given in the <literal>host</literal> or
1244 <literal>hostaddr</literal> parameters, this parameter may specify a
1245 comma-separated list of ports of the same length as the host list, or
1246 it may specify a single port number to be used for all hosts.
1247 An empty string, or an empty item in a comma-separated list,
1248 specifies the default port number established
1249 when <productname>PostgreSQL</productname> was built.
1250 </para>
1251 </listitem>
1252 </varlistentry>
1253
1254 <varlistentry id="libpq-connect-dbname" xreflabel="dbname">
1255 <term><literal>dbname</literal></term>
1256 <listitem>
1257 <para>
1258 The database name. Defaults to be the same as the user name.
1259 In certain contexts, the value is checked for extended
1260 formats; see <xref linkend="libpq-connstring"/> for more details on
1261 those.
1262 </para>
1263 </listitem>
1264 </varlistentry>
1265
1266 <varlistentry id="libpq-connect-user" xreflabel="user">
1267 <term><literal>user</literal></term>
1268 <listitem>
1269 <para>
1270 <productname>PostgreSQL</productname> user name to connect as.
1271 Defaults to be the same as the operating system name of the user
1272 running the application.
1273 </para>
1274 </listitem>
1275 </varlistentry>
1276
1277 <varlistentry id="libpq-connect-password" xreflabel="password">
1278 <term><literal>password</literal></term>
1279 <listitem>
1280 <para>
1281 Password to be used if the server demands password authentication.
1282 </para>
1283 </listitem>
1284 </varlistentry>
1285
1286 <varlistentry id="libpq-connect-passfile" xreflabel="passfile">
1287 <term><literal>passfile</literal></term>
1288 <listitem>
1289 <para>
1290 Specifies the name of the file used to store passwords
1291 (see <xref linkend="libpq-pgpass"/>).
1292 Defaults to <filename>~/.pgpass</filename>, or
1293 <filename>%APPDATA%\postgresql\pgpass.conf</filename> on Microsoft Windows.
1294 (No error is reported if this file does not exist.)
1295 </para>
1296 </listitem>
1297 </varlistentry>
1298
1299 <varlistentry id="libpq-connect-require-auth" xreflabel="require_auth">
1300 <term><literal>require_auth</literal></term>
1301 <listitem>
1302 <para>
1303 Specifies the authentication method that the client requires from the
1304 server. If the server does not use the required method to authenticate
1305 the client, or if the authentication handshake is not fully completed by
1306 the server, the connection will fail. A comma-separated list of methods
1307 may also be provided, of which the server must use exactly one in order
1308 for the connection to succeed. By default, any authentication method is
1309 accepted, and the server is free to skip authentication altogether.
1310 </para>
1311 <para>
1312 Methods may be negated with the addition of a <literal>!</literal>
1313 prefix, in which case the server must <emphasis>not</emphasis> attempt
1314 the listed method; any other method is accepted, and the server is free
1315 not to authenticate the client at all. If a comma-separated list is
1316 provided, the server may not attempt <emphasis>any</emphasis> of the
1317 listed negated methods. Negated and non-negated forms may not be
1318 combined in the same setting.
1319 </para>
1320 <para>
1321 As a final special case, the <literal>none</literal> method requires the
1322 server not to use an authentication challenge. (It may also be negated,
1323 to require some form of authentication.)
1324 </para>
1325 <para>
1326 The following methods may be specified:
1327
1328 <variablelist>
1329 <varlistentry>
1330 <term><literal>password</literal></term>
1331 <listitem>
1332 <para>
1333 The server must request plaintext password authentication.
1334 </para>
1335 </listitem>
1336 </varlistentry>
1337
1338 <varlistentry>
1339 <term><literal>md5</literal></term>
1340 <listitem>
1341 <para>
1342 The server must request MD5 hashed password authentication.
1343 </para>
1344 <warning>
1345 <para>
1346 Support for MD5-encrypted passwords is deprecated and will be
1347 removed in a future release of
1348 <productname>PostgreSQL</productname>. Refer to
1349 <xref linkend="auth-password"/> for details about migrating to
1350 another password type.
1351 </para>
1352 </warning>
1353 </listitem>
1354 </varlistentry>
1355
1356 <varlistentry>
1357 <term><literal>gss</literal></term>
1358 <listitem>
1359 <para>
1360 The server must either request a Kerberos handshake via
1361 <acronym>GSSAPI</acronym> or establish a
1362 <acronym>GSS</acronym>-encrypted channel (see also
1363 <xref linkend="libpq-connect-gssencmode" />).
1364 </para>
1365 </listitem>
1366 </varlistentry>
1367
1368 <varlistentry>
1369 <term><literal>sspi</literal></term>
1370 <listitem>
1371 <para>
1372 The server must request Windows <acronym>SSPI</acronym>
1373 authentication.
1374 </para>
1375 </listitem>
1376 </varlistentry>
1377
1378 <varlistentry>
1379 <term><literal>scram-sha-256</literal></term>
1380 <listitem>
1381 <para>
1382 The server must successfully complete a SCRAM-SHA-256 authentication
1383 exchange with the client.
1384 </para>
1385 </listitem>
1386 </varlistentry>
1387
1388 <varlistentry>
1389 <term><literal>oauth</literal></term>
1390 <listitem>
1391 <para>
1392 The server must request an OAuth bearer token from the client.
1393 </para>
1394 </listitem>
1395 </varlistentry>
1396
1397 <varlistentry>
1398 <term><literal>none</literal></term>
1399 <listitem>
1400 <para>
1401 The server must not prompt the client for an authentication
1402 exchange. (This does not prohibit client certificate authentication
1403 via TLS, nor GSS authentication via its encrypted transport.)
1404 </para>
1405 </listitem>
1406 </varlistentry>
1407 </variablelist>
1408 </para>
1409 </listitem>
1410 </varlistentry>
1411
1412 <varlistentry id="libpq-connect-channel-binding" xreflabel="channel_binding">
1413 <term><literal>channel_binding</literal></term>
1414 <listitem>
1415 <para>
1416 This option controls the client's use of channel binding. A setting
1417 of <literal>require</literal> means that the connection must employ
1418 channel binding, <literal>prefer</literal> means that the client will
1419 choose channel binding if available, and <literal>disable</literal>
1420 prevents the use of channel binding. The default
1421 is <literal>prefer</literal> if
1422 <productname>PostgreSQL</productname> is compiled with SSL support;
1423 otherwise the default is <literal>disable</literal>.
1424 </para>
1425 <para>
1426 Channel binding is a method for the server to authenticate itself to
1427 the client. It is only supported over SSL connections
1428 with <productname>PostgreSQL</productname> 11 or later servers using
1429 the <literal>SCRAM</literal> authentication method.
1430 </para>
1431 </listitem>
1432 </varlistentry>
1433
1434 <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout">
1435 <term><literal>connect_timeout</literal></term>
1436 <listitem>
1437 <para>
1438 Maximum time to wait while connecting, in seconds (write as a decimal integer,
1439 e.g., <literal>10</literal>). Zero, negative, or not specified means
1440 wait indefinitely.
1441 This timeout applies separately to each host name or IP address.
1442 For example, if you specify two hosts and <literal>connect_timeout</literal>
1443 is 5, each host will time out if no connection is made within 5
1444 seconds, so the total time spent waiting for a connection might be
1445 up to 10 seconds.
1446 </para>
1447 </listitem>
1448 </varlistentry>
1449
1450 <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding">
1451 <term><literal>client_encoding</literal></term>
1452 <listitem>
1453 <para>
1454 This sets the <varname>client_encoding</varname>
1455 configuration parameter for this connection. In addition to
1456 the values accepted by the corresponding server option, you
1457 can use <literal>auto</literal> to determine the right
1458 encoding from the current locale in the client
1459 (<envar>LC_CTYPE</envar> environment variable on Unix
1460 systems).
1461 </para>
1462 </listitem>
1463 </varlistentry>
1464
1465 <varlistentry id="libpq-connect-options" xreflabel="options">
1466 <term><literal>options</literal></term>
1467 <listitem>
1468 <para>
1469 Specifies command-line options to send to the server at connection
1470 start. For example, setting this to <literal>-c geqo=off</literal>
1471 or <literal>--geqo=off</literal> sets the session's value of the
1472 <varname>geqo</varname> parameter to <literal>off</literal>.
1473 Spaces within this string are considered to
1474 separate command-line arguments, unless escaped with a backslash
1475 (<literal>\</literal>); write <literal>\\</literal> to represent a literal
1476 backslash. For a detailed discussion of the available
1477 options, consult <xref linkend="runtime-config"/>.
1478 </para>
1479 </listitem>
1480 </varlistentry>
1481
1482 <varlistentry id="libpq-connect-application-name" xreflabel="application_name">
1483 <term><literal>application_name</literal></term>
1484 <listitem>
1485 <para>
1486 Specifies a value for the <xref linkend="guc-application-name"/>
1487 configuration parameter.
1488 </para>
1489 </listitem>
1490 </varlistentry>
1491
1492 <varlistentry id="libpq-connect-fallback-application-name" xreflabel="fallback_application_name">
1493 <term><literal>fallback_application_name</literal></term>
1494 <listitem>
1495 <para>
1496 Specifies a fallback value for the <xref
1497 linkend="guc-application-name"/> configuration parameter.
1498 This value will be used if no value has been given for
1499 <literal>application_name</literal> via a connection parameter or the
1500 <envar>PGAPPNAME</envar> environment variable. Specifying
1501 a fallback name is useful in generic utility programs that
1502 wish to set a default application name but allow it to be
1503 overridden by the user.
1504 </para>
1505 </listitem>
1506 </varlistentry>
1507
1508 <varlistentry id="libpq-keepalives" xreflabel="keepalives">
1509 <term><literal>keepalives</literal></term>
1510 <listitem>
1511 <para>
1512 Controls whether client-side TCP keepalives are used. The default
1513 value is 1, meaning on, but you can change this to 0, meaning off,
1514 if keepalives are not wanted. This parameter is ignored for
1515 connections made via a Unix-domain socket.
1516 </para>
1517 </listitem>
1518 </varlistentry>
1519
1520 <varlistentry id="libpq-keepalives-idle" xreflabel="keepalives_idle">
1521 <term><literal>keepalives_idle</literal></term>
1522 <listitem>
1523 <para>
1524 Controls the number of seconds of inactivity after which TCP should
1525 send a keepalive message to the server. A value of zero uses the
1526 system default. This parameter is ignored for connections made via a
1527 Unix-domain socket, or if keepalives are disabled.
1528 It is only supported on systems where <symbol>TCP_KEEPIDLE</symbol> or
1529 an equivalent socket option is available, and on Windows; on other
1530 systems, it has no effect.
1531 </para>
1532 </listitem>
1533 </varlistentry>
1534
1535 <varlistentry id="libpq-keepalives-interval" xreflabel="keepalives_interval">
1536 <term><literal>keepalives_interval</literal></term>
1537 <listitem>
1538 <para>
1539 Controls the number of seconds after which a TCP keepalive message
1540 that is not acknowledged by the server should be retransmitted. A
1541 value of zero uses the system default. This parameter is ignored for
1542 connections made via a Unix-domain socket, or if keepalives are disabled.
1543 It is only supported on systems where <symbol>TCP_KEEPINTVL</symbol> or
1544 an equivalent socket option is available, and on Windows; on other
1545 systems, it has no effect.
1546 </para>
1547 </listitem>
1548 </varlistentry>
1549
1550 <varlistentry id="libpq-keepalives-count" xreflabel="keepalives_count">
1551 <term><literal>keepalives_count</literal></term>
1552 <listitem>
1553 <para>
1554 Controls the number of TCP keepalives that can be lost before the
1555 client's connection to the server is considered dead. A value of
1556 zero uses the system default. This parameter is ignored for
1557 connections made via a Unix-domain socket, or if keepalives are disabled.
1558 It is only supported on systems where <symbol>TCP_KEEPCNT</symbol> or
1559 an equivalent socket option is available; on other systems, it has no
1560 effect.
1561 </para>
1562 </listitem>
1563 </varlistentry>
1564
1565 <varlistentry id="libpq-tcp-user-timeout" xreflabel="tcp_user_timeout">
1566 <term><literal>tcp_user_timeout</literal></term>
1567 <listitem>
1568 <para>
1569 Controls the number of milliseconds that transmitted data may
1570 remain unacknowledged before a connection is forcibly closed.
1571 A value of zero uses the system default. This parameter is
1572 ignored for connections made via a Unix-domain socket.
1573 It is only supported on systems where <symbol>TCP_USER_TIMEOUT</symbol>
1574 is available; on other systems, it has no effect.
1575 </para>
1576 </listitem>
1577 </varlistentry>
1578
1579 <varlistentry id="libpq-connect-replication" xreflabel="replication">
1580 <term><literal>replication</literal></term>
1581 <listitem>
1582 <para>
1583 This option determines whether the connection should use the
1584 replication protocol instead of the normal protocol. This is what
1585 PostgreSQL replication connections as well as tools such as
1586 <application>pg_basebackup</application> use internally, but it can
1587 also be used by third-party applications. For a description of the
1588 replication protocol, consult <xref linkend="protocol-replication"/>.
1589 </para>
1590
1591 <para>
1592 The following values, which are case-insensitive, are supported:
1593 <variablelist>
1594 <varlistentry>
1595 <term>
1596 <literal>true</literal>, <literal>on</literal>,
1597 <literal>yes</literal>, <literal>1</literal>
1598 </term>
1599 <listitem>
1600 <para>
1601 The connection goes into physical replication mode.
1602 </para>
1603 </listitem>
1604 </varlistentry>
1605
1606 <varlistentry>
1607 <term><literal>database</literal></term>
1608 <listitem>
1609 <para>
1610 The connection goes into logical replication mode, connecting to
1611 the database specified in the <literal>dbname</literal> parameter.
1612 </para>
1613 </listitem>
1614 </varlistentry>
1615
1616 <varlistentry>
1617 <term>
1618 <literal>false</literal>, <literal>off</literal>,
1619 <literal>no</literal>, <literal>0</literal>
1620 </term>
1621 <listitem>
1622 <para>
1623 The connection is a regular one, which is the default behavior.
1624 </para>
1625 </listitem>
1626 </varlistentry>
1627 </variablelist>
1628 </para>
1629
1630 <para>
1631 In physical or logical replication mode, only the simple query protocol
1632 can be used.
1633 </para>
1634 </listitem>
1635 </varlistentry>
1636
1637 <varlistentry id="libpq-connect-gssencmode" xreflabel="gssencmode">
1638 <term><literal>gssencmode</literal></term>
1639 <listitem>
1640 <para>
1641 This option determines whether or with what priority a secure
1642 <acronym>GSS</acronym> TCP/IP connection will be negotiated with the
1643 server. There are three modes:
1644
1645 <variablelist>
1646 <varlistentry>
1647 <term><literal>disable</literal></term>
1648 <listitem>
1649 <para>
1650 only try a non-<acronym>GSSAPI</acronym>-encrypted connection
1651 </para>
1652 </listitem>
1653 </varlistentry>
1654
1655 <varlistentry>
1656 <term><literal>prefer</literal> (default)</term>
1657 <listitem>
1658 <para>
1659 if there are <acronym>GSSAPI</acronym> credentials present (i.e.,
1660 in a credentials cache), first try
1661 a <acronym>GSSAPI</acronym>-encrypted connection; if that fails or
1662 there are no credentials, try a
1663 non-<acronym>GSSAPI</acronym>-encrypted connection. This is the
1664 default when <productname>PostgreSQL</productname> has been
1665 compiled with <acronym>GSSAPI</acronym> support.
1666 </para>
1667 </listitem>
1668 </varlistentry>
1669
1670 <varlistentry>
1671 <term><literal>require</literal></term>
1672 <listitem>
1673 <para>
1674 only try a <acronym>GSSAPI</acronym>-encrypted connection
1675 </para>
1676 </listitem>
1677 </varlistentry>
1678 </variablelist>
1679 </para>
1680
1681 <para>
1682 <literal>gssencmode</literal> is ignored for Unix domain socket
1683 communication. If <productname>PostgreSQL</productname> is compiled
1684 without GSSAPI support, using the <literal>require</literal> option
1685 will cause an error, while <literal>prefer</literal> will be accepted
1686 but <application>libpq</application> will not actually attempt
1687 a <acronym>GSSAPI</acronym>-encrypted
1688 connection.<indexterm><primary>GSSAPI</primary><secondary sortas="libpq">with
1689 libpq</secondary></indexterm>
1690 </para>
1691 </listitem>
1692 </varlistentry>
1693
1694 <varlistentry id="libpq-connect-sslmode" xreflabel="sslmode">
1695 <term><literal>sslmode</literal></term>
1696 <listitem>
1697 <para>
1698 This option determines whether or with what priority a secure
1699 <acronym>SSL</acronym> TCP/IP connection will be negotiated with the
1700 server. There are six modes:
1701
1702 <variablelist>
1703 <varlistentry>
1704 <term><literal>disable</literal></term>
1705 <listitem>
1706 <para>
1707 only try a non-<acronym>SSL</acronym> connection
1708 </para>
1709 </listitem>
1710 </varlistentry>
1711
1712 <varlistentry>
1713 <term><literal>allow</literal></term>
1714 <listitem>
1715 <para>
1716 first try a non-<acronym>SSL</acronym> connection; if that
1717 fails, try an <acronym>SSL</acronym> connection
1718 </para>
1719 </listitem>
1720 </varlistentry>
1721
1722 <varlistentry>
1723 <term><literal>prefer</literal> (default)</term>
1724 <listitem>
1725 <para>
1726 first try an <acronym>SSL</acronym> connection; if that fails,
1727 try a non-<acronym>SSL</acronym> connection
1728 </para>
1729 </listitem>
1730 </varlistentry>
1731
1732 <varlistentry>
1733 <term><literal>require</literal></term>
1734 <listitem>
1735 <para>
1736 only try an <acronym>SSL</acronym> connection. If a root CA
1737 file is present, verify the certificate in the same way as
1738 if <literal>verify-ca</literal> was specified
1739 </para>
1740 </listitem>
1741 </varlistentry>
1742
1743 <varlistentry>
1744 <term><literal>verify-ca</literal></term>
1745 <listitem>
1746 <para>
1747 only try an <acronym>SSL</acronym> connection, and verify that
1748 the server certificate is issued by a trusted
1749 certificate authority (<acronym>CA</acronym>)
1750 </para>
1751 </listitem>
1752 </varlistentry>
1753
1754 <varlistentry>
1755 <term><literal>verify-full</literal></term>
1756 <listitem>
1757 <para>
1758 only try an <acronym>SSL</acronym> connection, verify that the
1759 server certificate is issued by a
1760 trusted <acronym>CA</acronym> and that the requested server host name
1761 matches that in the certificate
1762 </para>
1763 </listitem>
1764 </varlistentry>
1765 </variablelist>
1766
1767 See <xref linkend="libpq-ssl"/> for a detailed description of how
1768 these options work.
1769 </para>
1770
1771 <para>
1772 <literal>sslmode</literal> is ignored for Unix domain socket
1773 communication.
1774 If <productname>PostgreSQL</productname> is compiled without SSL support,
1775 using options <literal>require</literal>, <literal>verify-ca</literal>, or
1776 <literal>verify-full</literal> will cause an error, while
1777 options <literal>allow</literal> and <literal>prefer</literal> will be
1778 accepted but <application>libpq</application> will not actually attempt
1779 an <acronym>SSL</acronym>
1780 connection.<indexterm><primary>SSL</primary><secondary
1781 sortas="libpq">with libpq</secondary></indexterm>
1782 </para>
1783
1784 <para>
1785 Note that if <acronym>GSSAPI</acronym> encryption is possible,
1786 that will be used in preference to <acronym>SSL</acronym>
1787 encryption, regardless of the value of <literal>sslmode</literal>.
1788 To force use of <acronym>SSL</acronym> encryption in an
1789 environment that has working <acronym>GSSAPI</acronym>
1790 infrastructure (such as a Kerberos server), also set
1791 <literal>gssencmode</literal> to <literal>disable</literal>.
1792 </para>
1793 </listitem>
1794 </varlistentry>
1795
1796 <varlistentry id="libpq-connect-requiressl" xreflabel="requiressl">
1797 <term><literal>requiressl</literal></term>
1798 <listitem>
1799 <para>
1800 This option is deprecated in favor of the <literal>sslmode</literal>
1801 setting.
1802 </para>
1803
1804 <para>
1805 If set to 1, an <acronym>SSL</acronym> connection to the server
1806 is required (this is equivalent to <literal>sslmode</literal>
1807 <literal>require</literal>). <application>libpq</application> will then refuse
1808 to connect if the server does not accept an
1809 <acronym>SSL</acronym> connection. If set to 0 (default),
1810 <application>libpq</application> will negotiate the connection type with
1811 the server (equivalent to <literal>sslmode</literal>
1812 <literal>prefer</literal>). This option is only available if
1813 <productname>PostgreSQL</productname> is compiled with SSL support.
1814 </para>
1815 </listitem>
1816 </varlistentry>
1817
1818 <varlistentry id="libpq-connect-sslnegotiation" xreflabel="sslnegotiation">
1819 <term><literal>sslnegotiation</literal></term>
1820 <listitem>
1821 <para>
1822 This option controls how SSL encryption is negotiated with the server,
1823 if SSL is used. In the default <literal>postgres</literal> mode, the
1824 client first asks the server if SSL is supported. In
1825 <literal>direct</literal> mode, the client starts the standard SSL
1826 handshake directly after establishing the TCP/IP connection. Traditional
1827 <productname>PostgreSQL</productname> protocol negotiation is the most
1828 flexible with different server configurations. If the server is known
1829 to support direct <acronym>SSL</acronym> connections then the latter
1830 requires one fewer round trip reducing connection latency and also
1831 allows the use of protocol agnostic SSL network tools. The direct SSL
1832 option was introduced in <productname>PostgreSQL</productname> version
1833 17.
1834 </para>
1835
1836 <variablelist>
1837 <varlistentry>
1838 <term><literal>postgres</literal></term>
1839 <listitem>
1840 <para>
1841 perform <productname>PostgreSQL</productname> protocol
1842 negotiation. This is the default if the option is not provided.
1843 </para>
1844 </listitem>
1845 </varlistentry>
1846
1847 <varlistentry>
1848 <term><literal>direct</literal></term>
1849 <listitem>
1850 <para>
1851 start SSL handshake directly after establishing the TCP/IP
1852 connection. This is only allowed with
1853 <literal>sslmode=require</literal> or higher, because the weaker
1854 settings could lead to unintended fallback to plaintext
1855 authentication when the server does not support direct SSL
1856 handshake.
1857 </para>
1858 </listitem>
1859 </varlistentry>
1860 </variablelist>
1861 </listitem>
1862 </varlistentry>
1863
1864 <varlistentry id="libpq-connect-sslcompression" xreflabel="sslcompression">
1865 <term><literal>sslcompression</literal></term>
1866 <listitem>
1867 <para>
1868 If set to 1, data sent over SSL connections will be compressed. If
1869 set to 0, compression will be disabled. The default is 0. This
1870 parameter is ignored if a connection without SSL is made.
1871 </para>
1872
1873 <para>
1874 SSL compression is nowadays considered insecure and its use is no
1875 longer recommended. <productname>OpenSSL</productname> 1.1.0 disabled
1876 compression by default, and many operating system distributions
1877 disabled it in prior versions as well, so setting this parameter to on
1878 will not have any effect if the server does not accept compression.
1879 <productname>PostgreSQL</productname> 14 disabled compression
1880 completely in the backend.
1881 </para>
1882
1883 <para>
1884 If security is not a primary concern, compression can improve
1885 throughput if the network is the bottleneck. Disabling compression
1886 can improve response time and throughput if CPU performance is the
1887 limiting factor.
1888 </para>
1889 </listitem>
1890 </varlistentry>
1891
1892 <varlistentry id="libpq-connect-sslcert" xreflabel="sslcert">
1893 <term><literal>sslcert</literal></term>
1894 <listitem>
1895 <para>
1896 This parameter specifies the file name of the client SSL
1897 certificate, replacing the default
1898 <filename>~/.postgresql/postgresql.crt</filename>.
1899 This parameter is ignored if an SSL connection is not made.
1900 </para>
1901 </listitem>
1902 </varlistentry>
1903
1904 <varlistentry id="libpq-connect-sslkey" xreflabel="sslkey">
1905 <term><literal>sslkey</literal></term>
1906 <listitem>
1907 <para>
1908 This parameter specifies the location for the secret key used for
1909 the client certificate. It can either specify a file name that will
1910 be used instead of the default
1911 <filename>~/.postgresql/postgresql.key</filename>, or it can specify a key
1912 obtained from an external <quote>engine</quote> (engines are
1913 <productname>OpenSSL</productname> loadable modules). An external engine
1914 specification should consist of a colon-separated engine name and
1915 an engine-specific key identifier. This parameter is ignored if an
1916 SSL connection is not made.
1917 </para>
1918 </listitem>
1919 </varlistentry>
1920
1921 <varlistentry id="libpq-connect-sslkeylogfile" xreflabel="sslkeylogfile">
1922 <term><literal>sslkeylogfile</literal></term>
1923 <listitem>
1924 <para>
1925 This parameter specifies the location where <application>libpq</application>
1926 will log keys used in this SSL context. This is useful for debugging
1927 <productname>PostgreSQL</productname> protocol interactions or client
1928 connections using network inspection tools like
1929 <productname>Wireshark</productname>. This parameter is ignored if an
1930 SSL connection is not made, or if <productname>LibreSSL</productname>
1931 is used (<productname>LibreSSL</productname> does not support key
1932 logging). Keys are logged using the <productname>NSS</productname>
1933 format.
1934 <warning>
1935 <para>
1936 Key logging will expose potentially sensitive information in the
1937 keylog file. Keylog files should be handled with the same care as
1938 <xref linkend="libpq-connect-sslkey" /> files.
1939 </para>
1940 </warning>
1941 </para>
1942 </listitem>
1943 </varlistentry>
1944
1945 <varlistentry id="libpq-connect-sslpassword" xreflabel="sslpassword">
1946 <term><literal>sslpassword</literal></term>
1947 <listitem>
1948 <para>
1949 This parameter specifies the password for the secret key specified in
1950 <literal>sslkey</literal>, allowing client certificate private keys
1951 to be stored in encrypted form on disk even when interactive passphrase
1952 input is not practical.
1953 </para>
1954 <para>
1955 Specifying this parameter with any non-empty value suppresses the
1956 <literal>Enter PEM pass phrase:</literal>
1957 prompt that <productname>OpenSSL</productname> will emit by default
1958 when an encrypted client certificate key is provided to
1959 <application>libpq</application>.
1960 </para>
1961 <para>
1962 If the key is not encrypted this parameter is ignored. The parameter
1963 has no effect on keys specified by <productname>OpenSSL</productname>
1964 engines unless the engine uses the <productname>OpenSSL</productname>
1965 password callback mechanism for prompts.
1966 </para>
1967 <para>
1968 There is no environment variable equivalent to this option, and no
1969 facility for looking it up in <filename>.pgpass</filename>. It can be
1970 used in a service file connection definition. Users with
1971 more sophisticated uses should consider using <productname>OpenSSL</productname> engines and
1972 tools like PKCS#11 or USB crypto offload devices.
1973 </para>
1974 </listitem>
1975 </varlistentry>
1976
1977 <varlistentry id="libpq-connect-sslcertmode" xreflabel="sslcertmode">
1978 <term><literal>sslcertmode</literal></term>
1979 <listitem>
1980 <para>
1981 This option determines whether a client certificate may be sent to the
1982 server, and whether the server is required to request one. There are
1983 three modes:
1984
1985 <variablelist>
1986 <varlistentry>
1987 <term><literal>disable</literal></term>
1988 <listitem>
1989 <para>
1990 A client certificate is never sent, even if one is available
1991 (default location or provided via
1992 <xref linkend="libpq-connect-sslcert" />).
1993 </para>
1994 </listitem>
1995 </varlistentry>
1996
1997 <varlistentry>
1998 <term><literal>allow</literal> (default)</term>
1999 <listitem>
2000 <para>
2001 A certificate may be sent, if the server requests one and the
2002 client has one to send.
2003 </para>
2004 </listitem>
2005 </varlistentry>
2006
2007 <varlistentry>
2008 <term><literal>require</literal></term>
2009 <listitem>
2010 <para>
2011 The server <emphasis>must</emphasis> request a certificate. The
2012 connection will fail if the client does not send a certificate and
2013 the server successfully authenticates the client anyway.
2014 </para>
2015 </listitem>
2016 </varlistentry>
2017 </variablelist>
2018 </para>
2019
2020 <note>
2021 <para>
2022 <literal>sslcertmode=require</literal> doesn't add any additional
2023 security, since there is no guarantee that the server is validating
2024 the certificate correctly; PostgreSQL servers generally request TLS
2025 certificates from clients whether they validate them or not. The
2026 option may be useful when troubleshooting more complicated TLS
2027 setups.
2028 </para>
2029 </note>
2030 </listitem>
2031 </varlistentry>
2032
2033 <varlistentry id="libpq-connect-sslrootcert" xreflabel="sslrootcert">
2034 <term><literal>sslrootcert</literal></term>
2035 <listitem>
2036 <para>
2037 This parameter specifies the name of a file containing SSL
2038 certificate authority (<acronym>CA</acronym>) certificate(s).
2039 If the file exists, the server's certificate will be verified
2040 to be signed by one of these authorities. The default is
2041 <filename>~/.postgresql/root.crt</filename>.
2042 </para>
2043 <para>
2044 The special value <literal>system</literal> may be specified instead, in
2045 which case the trusted CA roots from the SSL implementation will be loaded. The exact
2046 locations of these root certificates differ by SSL implementation and
2047 platform. For <productname>OpenSSL</productname> in particular, the
2048 locations may be further modified by the <envar>SSL_CERT_DIR</envar>
2049 and <envar>SSL_CERT_FILE</envar> environment variables.
2050 </para>
2051 <note>
2052 <para>
2053 When using <literal>sslrootcert=system</literal>, the default
2054 <literal>sslmode</literal> is changed to <literal>verify-full</literal>,
2055 and any weaker setting will result in an error. In most cases it is
2056 trivial for anyone to obtain a certificate trusted by the system for a
2057 hostname they control, rendering <literal>verify-ca</literal> and all
2058 weaker modes useless.
2059 </para>
2060 <para>
2061 The magic <literal>system</literal> value will take precedence over a
2062 local certificate file with the same name. If for some reason you find
2063 yourself in this situation, use an alternative path like
2064 <literal>sslrootcert=./system</literal> instead.
2065 </para>
2066 </note>
2067 </listitem>
2068 </varlistentry>
2069
2070 <varlistentry id="libpq-connect-sslcrl" xreflabel="sslcrl">
2071 <term><literal>sslcrl</literal></term>
2072 <listitem>
2073 <para>
2074 This parameter specifies the file name of the SSL server certificate
2075 revocation list (CRL). Certificates listed in this file, if it
2076 exists, will be rejected while attempting to authenticate the
2077 server's certificate. If neither
2078 <xref linkend="libpq-connect-sslcrl"/> nor
2079 <xref linkend="libpq-connect-sslcrldir"/> is set, this setting is
2080 taken as
2081 <filename>~/.postgresql/root.crl</filename>.
2082 </para>
2083 </listitem>
2084 </varlistentry>
2085
2086 <varlistentry id="libpq-connect-sslcrldir" xreflabel="sslcrldir">
2087 <term><literal>sslcrldir</literal></term>
2088 <listitem>
2089 <para>
2090 This parameter specifies the directory name of the SSL server certificate
2091 revocation list (CRL). Certificates listed in the files in this
2092 directory, if it exists, will be rejected while attempting to
2093 authenticate the server's certificate.
2094 </para>
2095
2096 <para>
2097 The directory needs to be prepared with the
2098 <productname>OpenSSL</productname> command
2099 <literal>openssl rehash</literal> or <literal>c_rehash</literal>. See
2100 its documentation for details.
2101 </para>
2102
2103 <para>
2104 Both <literal>sslcrl</literal> and <literal>sslcrldir</literal> can be
2105 specified together.
2106 </para>
2107 </listitem>
2108 </varlistentry>
2109
2110 <varlistentry id="libpq-connect-sslsni" xreflabel="sslsni">
2111 <term><literal>sslsni</literal><indexterm><primary>Server Name Indication</primary></indexterm></term>
2112 <listitem>
2113 <para>
2114 If set to 1 (default), libpq sets the TLS extension <quote>Server Name
2115 Indication</quote> (<acronym>SNI</acronym>) on SSL-enabled connections.
2116 By setting this parameter to 0, this is turned off.
2117 </para>
2118
2119 <para>
2120 The Server Name Indication can be used by SSL-aware proxies to route
2121 connections without having to decrypt the SSL stream. (Note that
2122 unless the proxy is aware of the PostgreSQL protocol handshake this
2123 would require setting <literal>sslnegotiation</literal>
2124 to <literal>direct</literal>.)
2125 However, <acronym>SNI</acronym> makes the destination host name appear
2126 in cleartext in the network traffic, so it might be undesirable in
2127 some cases.
2128 </para>
2129 </listitem>
2130 </varlistentry>
2131
2132 <varlistentry id="libpq-connect-requirepeer" xreflabel="requirepeer">
2133 <term><literal>requirepeer</literal></term>
2134 <listitem>
2135 <para>
2136 This parameter specifies the operating-system user name of the
2137 server, for example <literal>requirepeer=postgres</literal>.
2138 When making a Unix-domain socket connection, if this
2139 parameter is set, the client checks at the beginning of the
2140 connection that the server process is running under the specified
2141 user name; if it is not, the connection is aborted with an error.
2142 This parameter can be used to provide server authentication similar
2143 to that available with SSL certificates on TCP/IP connections.
2144 (Note that if the Unix-domain socket is in
2145 <filename>/tmp</filename> or another publicly writable location,
2146 any user could start a server listening there. Use this parameter
2147 to ensure that you are connected to a server run by a trusted user.)
2148 This option is only supported on platforms for which the
2149 <literal>peer</literal> authentication method is implemented; see
2150 <xref linkend="auth-peer"/>.
2151 </para>
2152 </listitem>
2153 </varlistentry>
2154
2155 <varlistentry id="libpq-connect-ssl-min-protocol-version" xreflabel="ssl_min_protocol_version">
2156 <term><literal>ssl_min_protocol_version</literal></term>
2157 <listitem>
2158 <para>
2159 This parameter specifies the minimum SSL/TLS protocol version to allow
2160 for the connection. Valid values are <literal>TLSv1</literal>,
2161 <literal>TLSv1.1</literal>, <literal>TLSv1.2</literal> and
2162 <literal>TLSv1.3</literal>. The supported protocols depend on the
2163 version of <productname>OpenSSL</productname> used, older versions
2164 not supporting the most modern protocol versions. If not specified,
2165 the default is <literal>TLSv1.2</literal>, which satisfies industry
2166 best practices as of this writing.
2167 </para>
2168 </listitem>
2169 </varlistentry>
2170
2171 <varlistentry id="libpq-connect-ssl-max-protocol-version" xreflabel="ssl_max_protocol_version">
2172 <term><literal>ssl_max_protocol_version</literal></term>
2173 <listitem>
2174 <para>
2175 This parameter specifies the maximum SSL/TLS protocol version to allow
2176 for the connection. Valid values are <literal>TLSv1</literal>,
2177 <literal>TLSv1.1</literal>, <literal>TLSv1.2</literal> and
2178 <literal>TLSv1.3</literal>. The supported protocols depend on the
2179 version of <productname>OpenSSL</productname> used, older versions
2180 not supporting the most modern protocol versions. If not set, this
2181 parameter is ignored and the connection will use the maximum bound
2182 defined by the backend, if set. Setting the maximum protocol version
2183 is mainly useful for testing or if some component has issues working
2184 with a newer protocol.
2185 </para>
2186 </listitem>
2187 </varlistentry>
2188
2189 <varlistentry id="libpq-connect-min-protocol-version" xreflabel="min_protocol_version">
2190 <term><literal>min_protocol_version</literal></term>
2191 <listitem>
2192 <para>
2193 Specifies the minimum protocol version to allow for the connection.
2194 The default is to allow any version of the
2195 <productname>PostgreSQL</productname> protocol supported by libpq,
2196 which currently means <literal>3.0</literal>. If the server
2197 does not support at least this protocol version the connection will be
2198 closed.
2199 </para>
2200
2201 <para>
2202 The current supported values are
2203 <literal>3.0</literal>, <literal>3.2</literal>,
2204 and <literal>latest</literal>. The <literal>latest</literal> value is
2205 equivalent to the latest protocol version supported by the libpq
2206 version being used, which is currently <literal>3.2</literal>.
2207 </para>
2208 </listitem>
2209 </varlistentry>
2210
2211 <varlistentry id="libpq-connect-max-protocol-version" xreflabel="max_protocol_version">
2212 <term><literal>max_protocol_version</literal></term>
2213 <listitem>
2214 <para>
2215 Specifies the protocol version to request from the server.
2216 The default is to use version <literal>3.0</literal> of the
2217 <productname>PostgreSQL</productname> protocol, unless the connection
2218 string specifies a feature that relies on a higher protocol version,
2219 in which case the latest version supported by libpq is used. If the
2220 server does not support the protocol version requested by the client,
2221 the connection is automatically downgraded to a lower minor protocol
2222 version that the server supports. After the connection attempt has
2223 completed you can use <xref linkend="libpq-PQfullProtocolVersion"/> to
2224 find out which exact protocol version was negotiated.
2225 </para>
2226
2227 <para>
2228 The current supported values are
2229 <literal>3.0</literal>, <literal>3.2</literal>,
2230 and <literal>latest</literal>. The <literal>latest</literal> value is
2231 equivalent to the latest protocol version supported by the libpq
2232 version being used, which is currently <literal>3.2</literal>.
2233 </para>
2234 </listitem>
2235 </varlistentry>
2236
2237 <varlistentry id="libpq-connect-krbsrvname" xreflabel="krbsrvname">
2238 <term><literal>krbsrvname</literal></term>
2239 <listitem>
2240 <para>
2241 Kerberos service name to use when authenticating with GSSAPI.
2242 This must match the service name specified in the server
2243 configuration for Kerberos authentication to succeed. (See also
2244 <xref linkend="gssapi-auth"/>.)
2245 The default value is normally <literal>postgres</literal>,
2246 but that can be changed when
2247 building <productname>PostgreSQL</productname> via
2248 the <option>--with-krb-srvnam</option> option
2249 of <application>configure</application>.
2250 In most environments, this parameter never needs to be changed.
2251 Some Kerberos implementations might require a different service name,
2252 such as Microsoft Active Directory which requires the service name
2253 to be in upper case (<literal>POSTGRES</literal>).
2254 </para>
2255 </listitem>
2256 </varlistentry>
2257
2258 <varlistentry id="libpq-connect-gsslib" xreflabel="gsslib">
2259 <term><literal>gsslib</literal></term>
2260 <listitem>
2261 <para>
2262 GSS library to use for GSSAPI authentication.
2263 Currently this is disregarded except on Windows builds that include
2264 both GSSAPI and SSPI support. In that case, set
2265 this to <literal>gssapi</literal> to cause libpq to use the GSSAPI
2266 library for authentication instead of the default SSPI.
2267 </para>
2268 </listitem>
2269 </varlistentry>
2270
2271 <varlistentry id="libpq-connect-gssdelegation" xreflabel="gssdelegation">
2272 <term><literal>gssdelegation</literal></term>
2273 <listitem>
2274 <para>
2275 Forward (delegate) GSS credentials to the server. The default is
2276 <literal>0</literal> which means credentials will not be forwarded
2277 to the server. Set this to <literal>1</literal> to have credentials
2278 forwarded when possible.
2279 </para>
2280 </listitem>
2281 </varlistentry>
2282
2283 <varlistentry id="libpq-connect-scram-client-key" xreflabel="scram_client_key">
2284 <term><literal>scram_client_key</literal></term>
2285 <listitem>
2286 <para>
2287 The base64-encoded SCRAM client key. This can be used by foreign-data
2288 wrappers or similar middleware to enable pass-through SCRAM
2289 authentication. See <xref
2290 linkend="postgres-fdw-options-connection-management"/> for one such
2291 implementation. It is not meant to be specified directly by users or
2292 client applications.
2293 </para>
2294 </listitem>
2295 </varlistentry>
2296
2297 <varlistentry id="libpq-connect-scram-server-key" xreflabel="scram_server_key">
2298 <term><literal>scram_server_key</literal></term>
2299 <listitem>
2300 <para>
2301 The base64-encoded SCRAM server key. This can be used by foreign-data
2302 wrappers or similar middleware to enable pass-through SCRAM
2303 authentication. See <xref
2304 linkend="postgres-fdw-options-connection-management"/> for one such
2305 implementation. It is not meant to be specified directly by users or
2306 client applications.
2307 </para>
2308 </listitem>
2309 </varlistentry>
2310
2311 <varlistentry id="libpq-connect-service" xreflabel="service">
2312 <term><literal>service</literal></term>
2313 <listitem>
2314 <para>
2315 Service name to use for additional parameters. It specifies a service
2316 name in <filename>pg_service.conf</filename> that holds additional connection parameters.
2317 This allows applications to specify only a service name so connection parameters
2318 can be centrally maintained. See <xref linkend="libpq-pgservice"/>.
2319 </para>
2320 </listitem>
2321 </varlistentry>
2322
2323 <varlistentry id="libpq-connect-target-session-attrs" xreflabel="target_session_attrs">
2324 <term><literal>target_session_attrs</literal></term>
2325 <listitem>
2326 <para>
2327 This option determines whether the session must have certain
2328 properties to be acceptable. It's typically used in combination
2329 with multiple host names to select the first acceptable alternative
2330 among several hosts. There are six modes:
2331
2332 <variablelist>
2333 <varlistentry>
2334 <term><literal>any</literal> (default)</term>
2335 <listitem>
2336 <para>
2337 any successful connection is acceptable
2338 </para>
2339 </listitem>
2340 </varlistentry>
2341
2342 <varlistentry>
2343 <term><literal>read-write</literal></term>
2344 <listitem>
2345 <para>
2346 session must accept read-write transactions by default (that
2347 is, the server must not be in hot standby mode and
2348 the <varname>default_transaction_read_only</varname> parameter
2349 must be <literal>off</literal>)
2350 </para>
2351 </listitem>
2352 </varlistentry>
2353
2354 <varlistentry>
2355 <term><literal>read-only</literal></term>
2356 <listitem>
2357 <para>
2358 session must not accept read-write transactions by default (the
2359 converse)
2360 </para>
2361 </listitem>
2362 </varlistentry>
2363
2364 <varlistentry>
2365 <term><literal>primary</literal></term>
2366 <listitem>
2367 <para>
2368 server must not be in hot standby mode
2369 </para>
2370 </listitem>
2371 </varlistentry>
2372
2373 <varlistentry>
2374 <term><literal>standby</literal></term>
2375 <listitem>
2376 <para>
2377 server must be in hot standby mode
2378 </para>
2379 </listitem>
2380 </varlistentry>
2381
2382 <varlistentry>
2383 <term><literal>prefer-standby</literal></term>
2384 <listitem>
2385 <para>
2386 first try to find a standby server, but if none of the listed
2387 hosts is a standby server, try again in <literal>any</literal>
2388 mode
2389 </para>
2390 </listitem>
2391 </varlistentry>
2392 </variablelist>
2393 </para>
2394 </listitem>
2395 </varlistentry>
2396
2397 <varlistentry id="libpq-connect-load-balance-hosts" xreflabel="load_balance_hosts">
2398 <term><literal>load_balance_hosts</literal></term>
2399 <listitem>
2400 <para>
2401 Controls the order in which the client tries to connect to the available
2402 hosts and addresses. Once a connection attempt is successful no other
2403 hosts and addresses will be tried. This parameter is typically used in
2404 combination with multiple host names or a DNS record that returns
2405 multiple IPs. This parameter can be used in combination with
2406 <xref linkend="libpq-connect-target-session-attrs"/>
2407 to, for example, load balance over standby servers only. Once successfully
2408 connected, subsequent queries on the returned connection will all be
2409 sent to the same server. There are currently two modes:
2410 <variablelist>
2411 <varlistentry>
2412 <term><literal>disable</literal> (default)</term>
2413 <listitem>
2414 <para>
2415 No load balancing across hosts is performed. Hosts are tried in
2416 the order in which they are provided and addresses are tried in
2417 the order they are received from DNS or a hosts file.
2418 </para>
2419 </listitem>
2420 </varlistentry>
2421
2422 <varlistentry>
2423 <term><literal>random</literal></term>
2424 <listitem>
2425 <para>
2426 Hosts and addresses are tried in random order. This value is mostly
2427 useful when opening multiple connections at the same time, possibly
2428 from different machines. This way connections can be load balanced
2429 across multiple <productname>PostgreSQL</productname> servers.
2430 </para>
2431 <para>
2432 While random load balancing, due to its random nature, will almost
2433 never result in a completely uniform distribution, it statistically
2434 gets quite close. One important aspect here is that this algorithm
2435 uses two levels of random choices: First the hosts
2436 will be resolved in random order. Then secondly, before resolving
2437 the next host, all resolved addresses for the current host will be
2438 tried in random order. This behaviour can skew the amount of
2439 connections each node gets greatly in certain cases, for instance
2440 when some hosts resolve to more addresses than others. But such a
2441 skew can also be used on purpose, e.g. to increase the number of
2442 connections a larger server gets by providing its hostname multiple
2443 times in the host string.
2444 </para>
2445 <para>
2446 When using this value it's recommended to also configure a reasonable
2447 value for <xref linkend="libpq-connect-connect-timeout"/>. Because then,
2448 if one of the nodes that are used for load balancing is not responding,
2449 a new node will be tried.
2450 </para>
2451 </listitem>
2452 </varlistentry>
2453 </variablelist>
2454 </para>
2455 </listitem>
2456 </varlistentry>
2457
2458 <varlistentry id="libpq-connect-oauth-issuer" xreflabel="oauth_issuer">
2459 <term><literal>oauth_issuer</literal></term>
2460 <listitem>
2461 <para>
2462 The HTTPS URL of a trusted issuer to contact if the server requests an
2463 OAuth token for the connection. This parameter is required for all OAuth
2464 connections; it should exactly match the <literal>issuer</literal>
2465 setting in <link linkend="auth-oauth">the server's HBA configuration</link>.
2466 </para>
2467 <para>
2468 As part of the standard authentication handshake, <application>libpq</application>
2469 will ask the server for a <emphasis>discovery document:</emphasis> a URL
2470 providing a set of OAuth configuration parameters. The server must
2471 provide a URL that is directly constructed from the components of the
2472 <literal>oauth_issuer</literal>, and this value must exactly match the
2473 issuer identifier that is declared in the discovery document itself, or
2474 the connection will fail. This is required to prevent a class of
2475 <ulink url="https://mailarchive.ietf.org/arch/msg/oauth/JIVxFBGsJBVtm7ljwJhPUm3Fr-w/">
2476 "mix-up attacks"</ulink> on OAuth clients.
2477 </para>
2478 <para>
2479 You may also explicitly set <literal>oauth_issuer</literal> to the
2480 <literal>/.well-known/</literal> URI used for OAuth discovery. In this
2481 case, if the server asks for a different URL, the connection will fail,
2482 but a <link linkend="libpq-oauth-authdata-hooks">custom OAuth flow</link>
2483 may be able to speed up the standard handshake by using previously
2484 cached tokens. (In this case, it is recommended that
2485 <xref linkend="libpq-connect-oauth-scope"/> be set as well, since the
2486 client will not have a chance to ask the server for a correct scope
2487 setting, and the default scopes for a token may not be sufficient to
2488 connect.) <application>libpq</application> currently supports the
2489 following well-known endpoints:
2490 <itemizedlist spacing="compact">
2491 <listitem><para><literal>/.well-known/openid-configuration</literal></para></listitem>
2492 <listitem><para><literal>/.well-known/oauth-authorization-server</literal></para></listitem>
2493 </itemizedlist>
2494 </para>
2495 <warning>
2496 <para>
2497 Issuers are highly privileged during the OAuth connection handshake. As
2498 a rule of thumb, if you would not trust the operator of a URL to handle
2499 access to your servers, or to impersonate you directly, that URL should
2500 not be trusted as an <literal>oauth_issuer</literal>.
2501 </para>
2502 </warning>
2503 </listitem>
2504 </varlistentry>
2505
2506 <varlistentry id="libpq-connect-oauth-client-id" xreflabel="oauth_client_id">
2507 <term><literal>oauth_client_id</literal></term>
2508 <listitem>
2509 <para>
2510 An OAuth 2.0 client identifier, as issued by the authorization server.
2511 If the <productname>PostgreSQL</productname> server
2512 <link linkend="auth-oauth">requests an OAuth token</link> for the
2513 connection (and if no <link linkend="libpq-oauth-authdata-hooks">custom
2514 OAuth hook</link> is installed to provide one), then this parameter must
2515 be set; otherwise, the connection will fail.
2516 </para>
2517 </listitem>
2518 </varlistentry>
2519
2520 <varlistentry id="libpq-connect-oauth-client-secret" xreflabel="oauth_client_secret">
2521 <term><literal>oauth_client_secret</literal></term>
2522 <listitem>
2523 <para>
2524 The client password, if any, to use when contacting the OAuth
2525 authorization server. Whether this parameter is required or not is
2526 determined by the OAuth provider; "public" clients generally do not use
2527 a secret, whereas "confidential" clients generally do.
2528 </para>
2529 </listitem>
2530 </varlistentry>
2531
2532 <varlistentry id="libpq-connect-oauth-scope" xreflabel="oauth_scope">
2533 <term><literal>oauth_scope</literal></term>
2534 <listitem>
2535 <para>
2536 The scope of the access request sent to the authorization server,
2537 specified as a (possibly empty) space-separated list of OAuth scope
2538 identifiers. This parameter is optional and intended for advanced usage.
2539 </para>
2540 <para>
2541 Usually the client will obtain appropriate scope settings from the
2542 <productname>PostgreSQL</productname> server. If this parameter is used,
2543 the server's requested scope list will be ignored. This can prevent a
2544 less-trusted server from requesting inappropriate access scopes from the
2545 end user. However, if the client's scope setting does not contain the
2546 server's required scopes, the server is likely to reject the issued
2547 token, and the connection will fail.
2548 </para>
2549 <para>
2550 The meaning of an empty scope list is provider-dependent. An OAuth
2551 authorization server may choose to issue a token with "default scope",
2552 whatever that happens to be, or it may reject the token request
2553 entirely.
2554 </para>
2555 </listitem>
2556 </varlistentry>
2557
2558 </variablelist>
2559 </para>
2560 </sect2>
2561 </sect1>
2562
2563 <sect1 id="libpq-status">
2564 <title>Connection Status Functions</title>
2565
2566 <para>
2567 These functions can be used to interrogate the status
2568 of an existing database connection object.
2569 </para>
2570
2571 <tip>
2572 <para>
2573 <indexterm><primary>libpq-fe.h</primary></indexterm>
2574 <indexterm><primary>libpq-int.h</primary></indexterm>
2575 <application>libpq</application> application programmers should be careful to
2576 maintain the <structname>PGconn</structname> abstraction. Use the accessor
2577 functions described below to get at the contents of <structname>PGconn</structname>.
2578 Reference to internal <structname>PGconn</structname> fields using
2579 <filename>libpq-int.h</filename> is not recommended because they are subject to change
2580 in the future.
2581 </para>
2582 </tip>
2583
2584 <para>
2585 The following functions return parameter values established at connection.
2586 These values are fixed for the life of the connection. If a multi-host
2587 connection string is used, the values of <xref linkend="libpq-PQhost"/>,
2588 <xref linkend="libpq-PQport"/>, and <xref linkend="libpq-PQpass"/> can change if a new connection
2589 is established using the same <structname>PGconn</structname> object. Other values
2590 are fixed for the lifetime of the <structname>PGconn</structname> object.
2591
2592 <variablelist>
2593 <varlistentry id="libpq-PQdb">
2594 <term><function>PQdb</function><indexterm><primary>PQdb</primary></indexterm></term>
2595
2596 <listitem>
2597 <para>
2598 Returns the database name of the connection.
2599 <synopsis>
2600 char *PQdb(const PGconn *conn);
2601 </synopsis>
2602 </para>
2603 </listitem>
2604 </varlistentry>
2605
2606 <varlistentry id="libpq-PQuser">
2607 <term><function>PQuser</function><indexterm><primary>PQuser</primary></indexterm></term>
2608
2609 <listitem>
2610 <para>
2611 Returns the user name of the connection.
2612 <synopsis>
2613 char *PQuser(const PGconn *conn);
2614 </synopsis>
2615 </para>
2616 </listitem>
2617 </varlistentry>
2618
2619 <varlistentry id="libpq-PQpass">
2620 <term><function>PQpass</function><indexterm><primary>PQpass</primary></indexterm></term>
2621
2622 <listitem>
2623 <para>
2624 Returns the password of the connection.
2625 <synopsis>
2626 char *PQpass(const PGconn *conn);
2627 </synopsis>
2628 </para>
2629
2630 <para>
2631 <xref linkend="libpq-PQpass"/> will return either the password specified
2632 in the connection parameters, or if there was none and the password
2633 was obtained from the <link linkend="libpq-pgpass">password
2634 file</link>, it will return that. In the latter case,
2635 if multiple hosts were specified in the connection parameters, it is
2636 not possible to rely on the result of <xref linkend="libpq-PQpass"/> until
2637 the connection is established. The status of the connection can be
2638 checked using the function <xref linkend="libpq-PQstatus"/>.
2639 </para>
2640 </listitem>
2641 </varlistentry>
2642
2643 <varlistentry id="libpq-PQhost">
2644 <term><function>PQhost</function><indexterm><primary>PQhost</primary></indexterm></term>
2645
2646 <listitem>
2647 <para>
2648 Returns the server host name of the active connection.
2649 This can be a host name, an IP address, or a directory path if the
2650 connection is via Unix socket. (The path case can be distinguished
2651 because it will always be an absolute path, beginning
2652 with <literal>/</literal>.)
2653 <synopsis>
2654 char *PQhost(const PGconn *conn);
2655 </synopsis>
2656 </para>
2657
2658 <para>
2659 If the connection parameters specified both <literal>host</literal> and
2660 <literal>hostaddr</literal>, then <xref linkend="libpq-PQhost"/> will
2661 return the <literal>host</literal> information. If only
2662 <literal>hostaddr</literal> was specified, then that is returned.
2663 If multiple hosts were specified in the connection parameters,
2664 <xref linkend="libpq-PQhost"/> returns the host actually connected to.
2665 </para>
2666
2667 <para>
2668 <xref linkend="libpq-PQhost"/> returns <symbol>NULL</symbol> if the
2669 <parameter>conn</parameter> argument is <symbol>NULL</symbol>.
2670 Otherwise, if there is an error producing the host information (perhaps
2671 if the connection has not been fully established or there was an
2672 error), it returns an empty string.
2673 </para>
2674
2675 <para>
2676 If multiple hosts were specified in the connection parameters, it is
2677 not possible to rely on the result of <xref linkend="libpq-PQhost"/> until
2678 the connection is established. The status of the connection can be
2679 checked using the function <xref linkend="libpq-PQstatus"/>.
2680 </para>
2681 </listitem>
2682 </varlistentry>
2683
2684
2685 <varlistentry id="libpq-PQhostaddr">
2686 <term><function>PQhostaddr</function><indexterm><primary>PQhostaddr</primary></indexterm></term>
2687
2688 <listitem>
2689 <para>
2690 Returns the server IP address of the active connection.
2691 This can be the address that a host name resolved to,
2692 or an IP address provided through the <literal>hostaddr</literal>
2693 parameter.
2694 <synopsis>
2695 char *PQhostaddr(const PGconn *conn);
2696 </synopsis>
2697 </para>
2698
2699 <para>
2700 <xref linkend="libpq-PQhostaddr"/> returns <symbol>NULL</symbol> if the
2701 <parameter>conn</parameter> argument is <symbol>NULL</symbol>.
2702 Otherwise, if there is an error producing the host information
2703 (perhaps if the connection has not been fully established or
2704 there was an error), it returns an empty string.
2705 </para>
2706 </listitem>
2707 </varlistentry>
2708
2709 <varlistentry id="libpq-PQport">
2710 <term><function>PQport</function><indexterm><primary>PQport</primary></indexterm></term>
2711
2712 <listitem>
2713 <para>
2714 Returns the port of the active connection.
2715
2716 <synopsis>
2717 char *PQport(const PGconn *conn);
2718 </synopsis>
2719 </para>
2720
2721 <para>
2722 If multiple ports were specified in the connection parameters,
2723 <xref linkend="libpq-PQport"/> returns the port actually connected to.
2724 </para>
2725
2726 <para>
2727 <xref linkend="libpq-PQport"/> returns <symbol>NULL</symbol> if the
2728 <parameter>conn</parameter> argument is <symbol>NULL</symbol>.
2729 Otherwise, if there is an error producing the port information (perhaps
2730 if the connection has not been fully established or there was an
2731 error), it returns an empty string.
2732 </para>
2733
2734 <para>
2735 If multiple ports were specified in the connection parameters, it is
2736 not possible to rely on the result of <xref linkend="libpq-PQport"/> until
2737 the connection is established. The status of the connection can be
2738 checked using the function <xref linkend="libpq-PQstatus"/>.
2739 </para>
2740 </listitem>
2741 </varlistentry>
2742
2743 <varlistentry id="libpq-PQtty">
2744 <term><function>PQtty</function><indexterm><primary>PQtty</primary></indexterm></term>
2745
2746 <listitem>
2747 <para>
2748 This function no longer does anything, but it remains for backwards
2749 compatibility. The function always return an empty string, or
2750 <symbol>NULL</symbol> if the <parameter>conn</parameter> argument is
2751 <symbol>NULL</symbol>.
2752
2753 <synopsis>
2754 char *PQtty(const PGconn *conn);
2755 </synopsis>
2756 </para>
2757 </listitem>
2758 </varlistentry>
2759
2760 <varlistentry id="libpq-PQoptions">
2761 <term><function>PQoptions</function><indexterm><primary>PQoptions</primary></indexterm></term>
2762
2763 <listitem>
2764 <para>
2765 Returns the command-line options passed in the connection request.
2766 <synopsis>
2767 char *PQoptions(const PGconn *conn);
2768 </synopsis>
2769 </para>
2770 </listitem>
2771 </varlistentry>
2772 </variablelist>
2773 </para>
2774
2775 <para>
2776 The following functions return status data that can change as operations
2777 are executed on the <structname>PGconn</structname> object.
2778
2779 <variablelist>
2780 <varlistentry id="libpq-PQstatus">
2781 <term><function>PQstatus</function><indexterm><primary>PQstatus</primary></indexterm></term>
2782
2783 <listitem>
2784 <para>
2785 Returns the status of the connection.
2786 <synopsis>
2787 ConnStatusType PQstatus(const PGconn *conn);
2788 </synopsis>
2789 </para>
2790
2791 <para>
2792 The status can be one of a number of values. However, only two of
2793 these are seen outside of an asynchronous connection procedure:
2794 <symbol>CONNECTION_OK</symbol> and
2795 <symbol>CONNECTION_BAD</symbol>. A good connection to the database
2796 has the status <symbol>CONNECTION_OK</symbol>. A failed
2797 connection attempt is signaled by status
2798 <symbol>CONNECTION_BAD</symbol>. Ordinarily, an OK status will
2799 remain so until <xref linkend="libpq-PQfinish"/>, but a communications
2800 failure might result in the status changing to
2801 <symbol>CONNECTION_BAD</symbol> prematurely. In that case the
2802 application could try to recover by calling
2803 <xref linkend="libpq-PQreset"/>.
2804 </para>
2805
2806 <para>
2807 See the entry for <xref linkend="libpq-PQconnectStartParams"/>, <function>PQconnectStart</function>
2808 and <function>PQconnectPoll</function> with regards to other status codes that
2809 might be returned.
2810 </para>
2811 </listitem>
2812 </varlistentry>
2813
2814 <varlistentry id="libpq-PQtransactionStatus">
2815 <term><function>PQtransactionStatus</function><indexterm><primary>PQtransactionStatus</primary></indexterm></term>
2816
2817 <listitem>
2818 <para>
2819 Returns the current in-transaction status of the server.
2820
2821 <synopsis>
2822 PGTransactionStatusType PQtransactionStatus(const PGconn *conn);
2823 </synopsis>
2824
2825 The status can be <literal>PQTRANS_IDLE</literal> (currently idle),
2826 <literal>PQTRANS_ACTIVE</literal> (a command is in progress),
2827 <literal>PQTRANS_INTRANS</literal> (idle, in a valid transaction block),
2828 or <literal>PQTRANS_INERROR</literal> (idle, in a failed transaction block).
2829 <literal>PQTRANS_UNKNOWN</literal> is reported if the connection is bad.
2830 <literal>PQTRANS_ACTIVE</literal> is reported only when a query
2831 has been sent to the server and not yet completed.
2832 </para>
2833 </listitem>
2834 </varlistentry>
2835
2836 <varlistentry id="libpq-PQparameterStatus">
2837 <term><function>PQparameterStatus</function><indexterm><primary>PQparameterStatus</primary></indexterm></term>
2838
2839 <listitem>
2840 <para>
2841 Looks up a current parameter setting of the server.
2842
2843 <synopsis>
2844 const char *PQparameterStatus(const PGconn *conn, const char *paramName);
2845 </synopsis>
2846
2847 Certain parameter values are reported by the server automatically at
2848 connection startup or whenever their values change.
2849 <xref linkend="libpq-PQparameterStatus"/> can be used to interrogate these settings.
2850 It returns the current value of a parameter if known, or <symbol>NULL</symbol>
2851 if the parameter is not known.
2852 </para>
2853
2854 <para>
2855 Parameters reported as of the current release include:
2856 <simplelist type="vert" columns="2">
2857 <member><varname>application_name</varname></member>
2858 <member><varname>client_encoding</varname></member>
2859 <member><varname>DateStyle</varname></member>
2860 <member><varname>default_transaction_read_only</varname></member>
2861 <member><varname>in_hot_standby</varname></member>
2862 <member><varname>integer_datetimes</varname></member>
2863 <member><varname>IntervalStyle</varname></member>
2864 <member><varname>is_superuser</varname></member>
2865 <member><varname>scram_iterations</varname></member>
2866 <member><varname>search_path</varname></member>
2867 <member><varname>server_encoding</varname></member>
2868 <member><varname>server_version</varname></member>
2869 <member><varname>session_authorization</varname></member>
2870 <member><varname>standard_conforming_strings</varname></member>
2871 <member><varname>TimeZone</varname></member>
2872 </simplelist>
2873 (<varname>default_transaction_read_only</varname> and
2874 <varname>in_hot_standby</varname> were not reported by releases before
2875 14; <varname>scram_iterations</varname> was not reported by releases
2876 before 16; <varname>search_path</varname> was not reported by releases
2877 before 18.)
2878 Note that
2879 <varname>server_version</varname>,
2880 <varname>server_encoding</varname> and
2881 <varname>integer_datetimes</varname>
2882 cannot change after startup.
2883 </para>
2884
2885 <para>
2886 If no value for <varname>standard_conforming_strings</varname> is reported,
2887 applications can assume it is <literal>off</literal>, that is, backslashes
2888 are treated as escapes in string literals. Also, the presence of
2889 this parameter can be taken as an indication that the escape string
2890 syntax (<literal>E'...'</literal>) is accepted.
2891 </para>
2892
2893 <para>
2894 Although the returned pointer is declared <literal>const</literal>, it in fact
2895 points to mutable storage associated with the <literal>PGconn</literal> structure.
2896 It is unwise to assume the pointer will remain valid across queries.
2897 </para>
2898 </listitem>
2899 </varlistentry>
2900
2901 <varlistentry id="libpq-PQfullProtocolVersion">
2902 <term><function>PQfullProtocolVersion</function><indexterm><primary>PQfullProtocolVersion</primary></indexterm></term>
2903
2904 <listitem>
2905 <para>
2906 Interrogates the frontend/backend protocol being used.
2907 <synopsis>
2908 int PQfullProtocolVersion(const PGconn *conn);
2909 </synopsis>
2910 Applications might wish to use this function to determine whether certain
2911 features are supported. The result is formed by multiplying the server's
2912 major version number by 10000 and adding the minor version number. For
2913 example, version 3.2 would be returned as 30002, and version 4.0 would
2914 be returned as 40000. Zero is returned if the connection is bad. The 3.0
2915 protocol is supported by <productname>PostgreSQL</productname> server
2916 versions 7.4 and above.
2917 </para>
2918 <para>
2919 The protocol version will not change after connection startup is
2920 complete, but it could theoretically change during a connection reset.
2921 </para>
2922 </listitem>
2923 </varlistentry>
2924
2925 <varlistentry id="libpq-PQprotocolVersion">
2926 <term><function>PQprotocolVersion</function><indexterm><primary>PQprotocolVersion</primary></indexterm></term>
2927
2928 <listitem>
2929 <para>
2930 Interrogates the frontend/backend protocol major version.
2931 <synopsis>
2932 int PQprotocolVersion(const PGconn *conn);
2933 </synopsis>
2934 Unlike <xref linkend="libpq-PQfullProtocolVersion"/>, this returns only
2935 the major protocol version in use, but it is supported by a wider range
2936 of libpq releases back to version 7.4. Currently, the possible values are
2937 3 (3.0 protocol), or zero (connection bad). Prior to release version
2938 14.0, libpq could additionally return 2 (2.0 protocol).
2939 </para>
2940 </listitem>
2941 </varlistentry>
2942
2943 <varlistentry id="libpq-PQserverVersion">
2944 <term><function>PQserverVersion</function><indexterm><primary>PQserverVersion</primary></indexterm></term>
2945
2946 <listitem>
2947 <para>
2948 Returns an integer representing the server version.
2949 <synopsis>
2950 int PQserverVersion(const PGconn *conn);
2951 </synopsis>
2952 </para>
2953
2954 <para>
2955 Applications might use this function to determine the version of the
2956 database server they are connected to. The result is formed by
2957 multiplying the server's major version number by 10000 and adding
2958 the minor version number. For example, version 10.1 will be
2959 returned as 100001, and version 11.0 will be returned as 110000.
2960 Zero is returned if the connection is bad.
2961 </para>
2962
2963 <para>
2964 Prior to major version 10, <productname>PostgreSQL</productname> used
2965 three-part version numbers in which the first two parts together
2966 represented the major version. For those
2967 versions, <xref linkend="libpq-PQserverVersion"/> uses two digits for each
2968 part; for example version 9.1.5 will be returned as 90105, and
2969 version 9.2.0 will be returned as 90200.
2970 </para>
2971
2972 <para>
2973 Therefore, for purposes of determining feature compatibility,
2974 applications should divide the result of <xref linkend="libpq-PQserverVersion"/>
2975 by 100 not 10000 to determine a logical major version number.
2976 In all release series, only the last two digits differ between
2977 minor releases (bug-fix releases).
2978 </para>
2979 </listitem>
2980 </varlistentry>
2981
2982 <varlistentry id="libpq-PQerrorMessage">
2983 <term>
2984 <function>PQerrorMessage</function><indexterm><primary>PQerrorMessage</primary></indexterm>
2985 <indexterm><primary>error message</primary><secondary>in <structname>PGconn</structname></secondary></indexterm>
2986 </term>
2987
2988 <listitem>
2989 <para>
2990 Returns the error message most recently generated by
2991 an operation on the connection.
2992
2993 <synopsis>
2994 char *PQerrorMessage(const PGconn *conn);
2995 </synopsis>
2996 </para>
2997
2998 <para>
2999 Nearly all <application>libpq</application> functions will set a message for
3000 <xref linkend="libpq-PQerrorMessage"/> if they fail. Note that by
3001 <application>libpq</application> convention, a nonempty
3002 <xref linkend="libpq-PQerrorMessage"/> result can consist of multiple lines,
3003 and will include a trailing newline. The caller should not free
3004 the result directly. It will be freed when the associated
3005 <structname>PGconn</structname> handle is passed to
3006 <xref linkend="libpq-PQfinish"/>. The result string should not be
3007 expected to remain the same across operations on the
3008 <literal>PGconn</literal> structure.
3009 </para>
3010 </listitem>
3011 </varlistentry>
3012
3013 <varlistentry id="libpq-PQsocket">
3014 <term><function>PQsocket</function><indexterm><primary>PQsocket</primary></indexterm></term>
3015 <listitem>
3016 <para>
3017 Obtains the file descriptor number of the connection socket to
3018 the server. A valid descriptor will be greater than or equal
3019 to 0; a result of -1 indicates that no server connection is
3020 currently open. (This will not change during normal operation,
3021 but could change during connection setup or reset.)
3022
3023 <synopsis>
3024 int PQsocket(const PGconn *conn);
3025 </synopsis>
3026
3027 </para>
3028 </listitem>
3029 </varlistentry>
3030
3031 <varlistentry id="libpq-PQbackendPID">
3032 <term><function>PQbackendPID</function><indexterm><primary>PQbackendPID</primary></indexterm></term>
3033 <listitem>
3034 <para>
3035 Returns the process <acronym>ID</acronym> (PID)<indexterm>
3036 <primary>PID</primary>
3037 <secondary>determining PID of server process</secondary>
3038 <tertiary>in libpq</tertiary>
3039 </indexterm>
3040 of the backend process handling this connection.
3041
3042 <synopsis>
3043 int PQbackendPID(const PGconn *conn);
3044 </synopsis>
3045 </para>
3046
3047 <para>
3048 The backend <acronym>PID</acronym> is useful for debugging
3049 purposes and for comparison to <command>NOTIFY</command>
3050 messages (which include the <acronym>PID</acronym> of the
3051 notifying backend process). Note that the
3052 <acronym>PID</acronym> belongs to a process executing on the
3053 database server host, not the local host!
3054 </para>
3055 </listitem>
3056 </varlistentry>
3057
3058 <varlistentry id="libpq-PQconnectionNeedsPassword">
3059 <term><function>PQconnectionNeedsPassword</function><indexterm><primary>PQconnectionNeedsPassword</primary></indexterm></term>
3060 <listitem>
3061 <para>
3062 Returns true (1) if the connection authentication method
3063 required a password, but none was available.
3064 Returns false (0) if not.
3065
3066 <synopsis>
3067 int PQconnectionNeedsPassword(const PGconn *conn);
3068 </synopsis>
3069 </para>
3070
3071 <para>
3072 This function can be applied after a failed connection attempt
3073 to decide whether to prompt the user for a password.
3074 </para>
3075 </listitem>
3076 </varlistentry>
3077
3078 <varlistentry id="libpq-PQconnectionUsedPassword">
3079 <term><function>PQconnectionUsedPassword</function><indexterm><primary>PQconnectionUsedPassword</primary></indexterm></term>
3080 <listitem>
3081 <para>
3082 Returns true (1) if the connection authentication method
3083 used a password. Returns false (0) if not.
3084
3085 <synopsis>
3086 int PQconnectionUsedPassword(const PGconn *conn);
3087 </synopsis>
3088 </para>
3089
3090 <para>
3091 This function can be applied after either a failed or successful
3092 connection attempt to detect whether the server demanded a password.
3093 </para>
3094 </listitem>
3095 </varlistentry>
3096
3097 <varlistentry id="libpq-PQconnectionUsedGSSAPI">
3098 <term><function>PQconnectionUsedGSSAPI</function><indexterm><primary>PQconnectionUsedGSSAPI</primary></indexterm></term>
3099 <listitem>
3100 <para>
3101 Returns true (1) if the connection authentication method
3102 used GSSAPI. Returns false (0) if not.
3103
3104 <synopsis>
3105 int PQconnectionUsedGSSAPI(const PGconn *conn);
3106 </synopsis>
3107 </para>
3108
3109 <para>
3110 This function can be applied to detect whether the connection was
3111 authenticated with GSSAPI.
3112 </para>
3113 </listitem>
3114 </varlistentry>
3115 </variablelist>
3116 </para>
3117
3118 <para>
3119 The following functions return information related to SSL. This information
3120 usually doesn't change after a connection is established.
3121
3122 <variablelist>
3123 <varlistentry id="libpq-PQsslInUse">
3124 <term><function>PQsslInUse</function><indexterm><primary>PQsslInUse</primary></indexterm></term>
3125 <listitem>
3126 <para>
3127 Returns true (1) if the connection uses SSL, false (0) if not.
3128
3129 <synopsis>
3130 int PQsslInUse(const PGconn *conn);
3131 </synopsis>
3132 </para>
3133
3134 </listitem>
3135 </varlistentry>
3136
3137 <varlistentry id="libpq-PQsslAttribute">
3138 <term><function>PQsslAttribute</function><indexterm><primary>PQsslAttribute</primary></indexterm></term>
3139 <listitem>
3140 <para>
3141 Returns SSL-related information about the connection.
3142
3143 <synopsis>
3144 const char *PQsslAttribute(const PGconn *conn, const char *attribute_name);
3145 </synopsis>
3146 </para>
3147
3148 <para>
3149 The list of available attributes varies depending on the SSL library
3150 being used and the type of connection. Returns NULL if the connection
3151 does not use SSL or the specified attribute name is not defined for the
3152 library in use.
3153 </para>
3154
3155 <para>
3156 The following attributes are commonly available:
3157 <variablelist>
3158 <varlistentry>
3159 <term><literal>library</literal></term>
3160 <listitem>
3161 <para>
3162 Name of the SSL implementation in use. (Currently, only
3163 <literal>"OpenSSL"</literal> is implemented)
3164 </para>
3165 </listitem>
3166 </varlistentry>
3167 <varlistentry>
3168 <term><literal>protocol</literal></term>
3169 <listitem>
3170 <para>
3171 SSL/TLS version in use. Common values
3172 are <literal>"TLSv1"</literal>, <literal>"TLSv1.1"</literal>
3173 and <literal>"TLSv1.2"</literal>, but an implementation may
3174 return other strings if some other protocol is used.
3175 </para>
3176 </listitem>
3177 </varlistentry>
3178 <varlistentry>
3179 <term><literal>key_bits</literal></term>
3180 <listitem>
3181 <para>
3182 Number of key bits used by the encryption algorithm.
3183 </para>
3184 </listitem>
3185 </varlistentry>
3186 <varlistentry>
3187 <term><literal>cipher</literal></term>
3188 <listitem>
3189 <para>
3190 A short name of the ciphersuite used, e.g.,
3191 <literal>"DHE-RSA-DES-CBC3-SHA"</literal>. The names are specific
3192 to each SSL implementation.
3193 </para>
3194 </listitem>
3195 </varlistentry>
3196 <varlistentry>
3197 <term><literal>compression</literal></term>
3198 <listitem>
3199 <para>
3200 Returns "on" if SSL compression is in use, else it returns "off".
3201 </para>
3202 </listitem>
3203 </varlistentry>
3204 <varlistentry>
3205 <term><literal>alpn</literal></term>
3206 <listitem>
3207 <para>
3208 Application protocol selected by the TLS Application-Layer
3209 Protocol Negotiation (ALPN) extension. The only protocol
3210 supported by libpq is <literal>postgresql</literal>, so this is
3211 mainly useful for checking whether the server supported ALPN or
3212 not. Empty string if ALPN was not used.
3213 </para>
3214 </listitem>
3215 </varlistentry>
3216 </variablelist>
3217 </para>
3218
3219 <para>
3220 As a special case, the <literal>library</literal> attribute may be
3221 queried without a connection by passing NULL as
3222 the <literal>conn</literal> argument. The result will be the default
3223 SSL library name, or NULL if <application>libpq</application> was
3224 compiled without any SSL support. (Prior
3225 to <productname>PostgreSQL</productname> version 15, passing NULL as
3226 the <literal>conn</literal> argument always resulted in NULL.
3227 Client programs needing to differentiate between the newer and older
3228 implementations of this case may check the
3229 <literal>LIBPQ_HAS_SSL_LIBRARY_DETECTION</literal> feature macro.)
3230 </para>
3231 </listitem>
3232 </varlistentry>
3233
3234 <varlistentry id="libpq-PQsslAttributeNames">
3235 <term><function>PQsslAttributeNames</function><indexterm><primary>PQsslAttributeNames</primary></indexterm></term>
3236 <listitem>
3237 <para>
3238 Returns an array of SSL attribute names that can be used
3239 in <function>PQsslAttribute()</function>.
3240 The array is terminated by a NULL pointer.
3241 <synopsis>
3242 const char * const * PQsslAttributeNames(const PGconn *conn);
3243 </synopsis>
3244 </para>
3245
3246 <para>
3247 If <literal>conn</literal> is NULL, the attributes available for the
3248 default SSL library are returned, or an empty list
3249 if <application>libpq</application> was compiled without any SSL
3250 support. If <literal>conn</literal> is not NULL, the attributes
3251 available for the SSL library in use for the connection are returned,
3252 or an empty list if the connection is not encrypted.
3253 </para>
3254 </listitem>
3255 </varlistentry>
3256
3257 <varlistentry id="libpq-PQsslStruct">
3258 <term><function>PQsslStruct</function><indexterm><primary>PQsslStruct</primary></indexterm></term>
3259 <listitem>
3260 <para>
3261 Returns a pointer to an SSL-implementation-specific object describing
3262 the connection. Returns NULL if the connection is not encrypted
3263 or the requested type of object is not available from the connection's
3264 SSL implementation.
3265 <synopsis>
3266 void *PQsslStruct(const PGconn *conn, const char *struct_name);
3267 </synopsis>
3268 </para>
3269 <para>
3270 The struct(s) available depend on the SSL implementation in use.
3271 For <productname>OpenSSL</productname>, there is one struct,
3272 available under the name <literal>OpenSSL</literal>,
3273 and it returns a pointer to
3274 <productname>OpenSSL</productname>'s <literal>SSL</literal> struct.
3275 To use this function, code along the following lines could be used:
3276 <programlisting><![CDATA[
3277 #include <libpq-fe.h>
3278 #include <openssl/ssl.h>
3279
3280 ...
3281
3282 SSL *ssl;
3283
3284 dbconn = PQconnectdb(...);
3285 ...
3286
3287 ssl = PQsslStruct(dbconn, "OpenSSL");
3288 if (ssl)
3289 {
3290 /* use OpenSSL functions to access ssl */
3291 }
3292 ]]></programlisting>
3293 </para>
3294 <para>
3295 This structure can be used to verify encryption levels, check server
3296 certificates, and more. Refer to the <productname>OpenSSL</productname>
3297 documentation for information about this structure.
3298 </para>
3299 </listitem>
3300 </varlistentry>
3301
3302 <varlistentry id="libpq-PQgetssl">
3303 <term><function>PQgetssl</function><indexterm><primary>PQgetssl</primary></indexterm></term>
3304 <listitem>
3305 <para>
3306 <indexterm><primary>SSL</primary><secondary sortas="libpq">in libpq</secondary></indexterm>
3307 Returns the SSL structure used in the connection, or NULL
3308 if SSL is not in use.
3309
3310 <synopsis>
3311 void *PQgetssl(const PGconn *conn);
3312 </synopsis>
3313 </para>
3314
3315 <para>
3316 This function is equivalent to <literal>PQsslStruct(conn, "OpenSSL")</literal>. It should
3317 not be used in new applications, because the returned struct is
3318 specific to <productname>OpenSSL</productname> and will not be
3319 available if another <acronym>SSL</acronym> implementation is used.
3320 To check if a connection uses SSL, call
3321 <xref linkend="libpq-PQsslInUse"/> instead, and for more details about the
3322 connection, use <xref linkend="libpq-PQsslAttribute"/>.
3323 </para>
3324 </listitem>
3325 </varlistentry>
3326
3327 </variablelist>
3328 </para>
3329
3330 </sect1>
3331
3332 <sect1 id="libpq-exec">
3333 <title>Command Execution Functions</title>
3334
3335 <para>
3336 Once a connection to a database server has been successfully
3337 established, the functions described here are used to perform
3338 SQL queries and commands.
3339 </para>
3340
3341 <sect2 id="libpq-exec-main">
3342 <title>Main Functions</title>
3343
3344 <para>
3345 <variablelist>
3346 <varlistentry id="libpq-PQexec">
3347 <term><function>PQexec</function><indexterm><primary>PQexec</primary></indexterm></term>
3348
3349 <listitem>
3350 <para>
3351 Submits a command to the server and waits for the result.
3352
3353 <synopsis>
3354 PGresult *PQexec(PGconn *conn, const char *command);
3355 </synopsis>
3356 </para>
3357
3358 <para>
3359 Returns a <structname>PGresult</structname> pointer or possibly a null
3360 pointer. A non-null pointer will generally be returned except in
3361 out-of-memory conditions or serious errors such as inability to send
3362 the command to the server. The <xref linkend="libpq-PQresultStatus"/> function
3363 should be called to check the return value for any errors (including
3364 the value of a null pointer, in which case it will return
3365 <symbol>PGRES_FATAL_ERROR</symbol>). Use
3366 <xref linkend="libpq-PQerrorMessage"/> to get more information about such
3367 errors.
3368 </para>
3369 </listitem>
3370 </varlistentry>
3371 </variablelist>
3372
3373 The command string can include multiple SQL commands
3374 (separated by semicolons). Multiple queries sent in a single
3375 <xref linkend="libpq-PQexec"/> call are processed in a single transaction, unless
3376 there are explicit <command>BEGIN</command>/<command>COMMIT</command>
3377 commands included in the query string to divide it into multiple
3378 transactions. (See <xref linkend="protocol-flow-multi-statement"/>
3379 for more details about how the server handles multi-query strings.)
3380 Note however that the returned
3381 <structname>PGresult</structname> structure describes only the result
3382 of the last command executed from the string. Should one of the
3383 commands fail, processing of the string stops with it and the returned
3384 <structname>PGresult</structname> describes the error condition.
3385 </para>
3386
3387 <para>
3388 <variablelist>
3389 <varlistentry id="libpq-PQexecParams">
3390 <term><function>PQexecParams</function><indexterm><primary>PQexecParams</primary></indexterm></term>
3391
3392 <listitem>
3393 <para>
3394 Submits a command to the server and waits for the result,
3395 with the ability to pass parameters separately from the SQL
3396 command text.
3397
3398 <synopsis>
3399 PGresult *PQexecParams(PGconn *conn,
3400 const char *command,
3401 int nParams,
3402 const Oid *paramTypes,
3403 const char * const *paramValues,
3404 const int *paramLengths,
3405 const int *paramFormats,
3406 int resultFormat);
3407 </synopsis>
3408 </para>
3409
3410 <para>
3411 <xref linkend="libpq-PQexecParams"/> is like <xref linkend="libpq-PQexec"/>, but offers additional
3412 functionality: parameter values can be specified separately from the command
3413 string proper, and query results can be requested in either text or binary
3414 format.
3415 </para>
3416
3417 <para>
3418 The function arguments are:
3419
3420 <variablelist>
3421 <varlistentry>
3422 <term><parameter>conn</parameter></term>
3423
3424 <listitem>
3425 <para>
3426 The connection object to send the command through.
3427 </para>
3428 </listitem>
3429 </varlistentry>
3430
3431 <varlistentry>
3432 <term><parameter>command</parameter></term>
3433 <listitem>
3434 <para>
3435 The SQL command string to be executed. If parameters are used,
3436 they are referred to in the command string as <literal>$1</literal>,
3437 <literal>$2</literal>, etc.
3438 </para>
3439 </listitem>
3440 </varlistentry>
3441
3442 <varlistentry>
3443 <term><parameter>nParams</parameter></term>
3444 <listitem>
3445 <para>
3446 The number of parameters supplied; it is the length of the arrays
3447 <parameter>paramTypes[]</parameter>, <parameter>paramValues[]</parameter>,
3448 <parameter>paramLengths[]</parameter>, and <parameter>paramFormats[]</parameter>. (The
3449 array pointers can be <symbol>NULL</symbol> when <parameter>nParams</parameter>
3450 is zero.)
3451 </para>
3452 </listitem>
3453 </varlistentry>
3454
3455 <varlistentry>
3456 <term><parameter>paramTypes[]</parameter></term>
3457 <listitem>
3458 <para>
3459 Specifies, by OID, the data types to be assigned to the
3460 parameter symbols. If <parameter>paramTypes</parameter> is
3461 <symbol>NULL</symbol>, or any particular element in the array
3462 is zero, the server infers a data type for the parameter symbol
3463 in the same way it would do for an untyped literal string.
3464 </para>
3465 </listitem>
3466 </varlistentry>
3467
3468 <varlistentry>
3469 <term><parameter>paramValues[]</parameter></term>
3470 <listitem>
3471 <para>
3472 Specifies the actual values of the parameters. A null pointer
3473 in this array means the corresponding parameter is null;
3474 otherwise the pointer points to a zero-terminated text string
3475 (for text format) or binary data in the format expected by the
3476 server (for binary format).
3477 </para>
3478 </listitem>
3479 </varlistentry>
3480
3481 <varlistentry>
3482 <term><parameter>paramLengths[]</parameter></term>
3483 <listitem>
3484 <para>
3485 Specifies the actual data lengths of binary-format parameters.
3486 It is ignored for null parameters and text-format parameters.
3487 The array pointer can be null when there are no binary parameters.
3488 </para>
3489 </listitem>
3490 </varlistentry>
3491
3492 <varlistentry>
3493 <term><parameter>paramFormats[]</parameter></term>
3494 <listitem>
3495 <para>
3496 Specifies whether parameters are text (put a zero in the
3497 array entry for the corresponding parameter) or binary (put
3498 a one in the array entry for the corresponding parameter).
3499 If the array pointer is null then all parameters are presumed
3500 to be text strings.
3501 </para>
3502 <para>
3503 Values passed in binary format require knowledge of
3504 the internal representation expected by the backend.
3505 For example, integers must be passed in network byte
3506 order. Passing <type>numeric</type> values requires
3507 knowledge of the server storage format, as implemented
3508 in
3509 <filename>src/backend/utils/adt/numeric.c::numeric_send()</filename> and
3510 <filename>src/backend/utils/adt/numeric.c::numeric_recv()</filename>.
3511 </para>
3512 </listitem>
3513 </varlistentry>
3514
3515 <varlistentry>
3516 <term><parameter>resultFormat</parameter></term>
3517 <listitem>
3518 <para>
3519 Specify zero to obtain results in text format, or one to obtain
3520 results in binary format. (There is not currently a provision
3521 to obtain different result columns in different formats,
3522 although that is possible in the underlying protocol.)
3523 </para>
3524 </listitem>
3525 </varlistentry>
3526 </variablelist>
3527 </para>
3528 </listitem>
3529 </varlistentry>
3530 </variablelist>
3531 </para>
3532
3533 <para>
3534 The primary advantage of <xref linkend="libpq-PQexecParams"/> over
3535 <xref linkend="libpq-PQexec"/> is that parameter values can be separated from the
3536 command string, thus avoiding the need for tedious and error-prone
3537 quoting and escaping.
3538 </para>
3539
3540 <para>
3541 Unlike <xref linkend="libpq-PQexec"/>, <xref linkend="libpq-PQexecParams"/> allows at most
3542 one SQL command in the given string. (There can be semicolons in it,
3543 but not more than one nonempty command.) This is a limitation of the
3544 underlying protocol, but has some usefulness as an extra defense against
3545 SQL-injection attacks.
3546 </para>
3547
3548 <tip>
3549 <para>
3550 Specifying parameter types via OIDs is tedious, particularly if you prefer
3551 not to hard-wire particular OID values into your program. However, you can
3552 avoid doing so even in cases where the server by itself cannot determine the
3553 type of the parameter, or chooses a different type than you want. In the
3554 SQL command text, attach an explicit cast to the parameter symbol to show what
3555 data type you will send. For example:
3556 <programlisting>
3557 SELECT * FROM mytable WHERE x = $1::bigint;
3558 </programlisting>
3559 This forces parameter <literal>$1</literal> to be treated as <type>bigint</type>, whereas
3560 by default it would be assigned the same type as <literal>x</literal>. Forcing the
3561 parameter type decision, either this way or by specifying a numeric type OID,
3562 is strongly recommended when sending parameter values in binary format, because
3563 binary format has less redundancy than text format and so there is less chance
3564 that the server will detect a type mismatch mistake for you.
3565 </para>
3566 </tip>
3567
3568 <para>
3569 <variablelist>
3570 <varlistentry id="libpq-PQprepare">
3571 <term><function>PQprepare</function><indexterm><primary>PQprepare</primary></indexterm></term>
3572
3573 <listitem>
3574 <para>
3575 Submits a request to create a prepared statement with the
3576 given parameters, and waits for completion.
3577 <synopsis>
3578 PGresult *PQprepare(PGconn *conn,
3579 const char *stmtName,
3580 const char *query,
3581 int nParams,
3582 const Oid *paramTypes);
3583 </synopsis>
3584 </para>
3585
3586 <para>
3587 <xref linkend="libpq-PQprepare"/> creates a prepared statement for later
3588 execution with <xref linkend="libpq-PQexecPrepared"/>. This feature allows
3589 commands to be executed repeatedly without being parsed and
3590 planned each time; see <xref linkend="sql-prepare"/> for details.
3591 </para>
3592
3593 <para>
3594 The function creates a prepared statement named
3595 <parameter>stmtName</parameter> from the <parameter>query</parameter> string, which
3596 must contain a single SQL command. <parameter>stmtName</parameter> can be
3597 <literal>""</literal> to create an unnamed statement, in which case any
3598 pre-existing unnamed statement is automatically replaced; otherwise
3599 it is an error if the statement name is already defined in the
3600 current session. If any parameters are used, they are referred
3601 to in the query as <literal>$1</literal>, <literal>$2</literal>, etc.
3602 <parameter>nParams</parameter> is the number of parameters for which types
3603 are pre-specified in the array <parameter>paramTypes[]</parameter>. (The
3604 array pointer can be <symbol>NULL</symbol> when
3605 <parameter>nParams</parameter> is zero.) <parameter>paramTypes[]</parameter>
3606 specifies, by OID, the data types to be assigned to the parameter
3607 symbols. If <parameter>paramTypes</parameter> is <symbol>NULL</symbol>,
3608 or any particular element in the array is zero, the server assigns
3609 a data type to the parameter symbol in the same way it would do
3610 for an untyped literal string. Also, the query can use parameter
3611 symbols with numbers higher than <parameter>nParams</parameter>; data types
3612 will be inferred for these symbols as well. (See
3613 <xref linkend="libpq-PQdescribePrepared"/> for a means to find out
3614 what data types were inferred.)
3615 </para>
3616
3617 <para>
3618 As with <xref linkend="libpq-PQexec"/>, the result is normally a
3619 <structname>PGresult</structname> object whose contents indicate
3620 server-side success or failure. A null result indicates
3621 out-of-memory or inability to send the command at all. Use
3622 <xref linkend="libpq-PQerrorMessage"/> to get more information about
3623 such errors.
3624 </para>
3625 </listitem>
3626 </varlistentry>
3627 </variablelist>
3628
3629 Prepared statements for use with <xref linkend="libpq-PQexecPrepared"/> can also
3630 be created by executing SQL <xref linkend="sql-prepare"/>
3631 statements.
3632 </para>
3633
3634 <para>
3635 <variablelist>
3636 <varlistentry id="libpq-PQexecPrepared">
3637 <term><function>PQexecPrepared</function><indexterm><primary>PQexecPrepared</primary></indexterm></term>
3638
3639 <listitem>
3640 <para>
3641 Sends a request to execute a prepared statement with given
3642 parameters, and waits for the result.
3643 <synopsis>
3644 PGresult *PQexecPrepared(PGconn *conn,
3645 const char *stmtName,
3646 int nParams,
3647 const char * const *paramValues,
3648 const int *paramLengths,
3649 const int *paramFormats,
3650 int resultFormat);
3651 </synopsis>
3652 </para>
3653
3654 <para>
3655 <xref linkend="libpq-PQexecPrepared"/> is like <xref linkend="libpq-PQexecParams"/>,
3656 but the command to be executed is specified by naming a
3657 previously-prepared statement, instead of giving a query string.
3658 This feature allows commands that will be used repeatedly to be
3659 parsed and planned just once, rather than each time they are
3660 executed. The statement must have been prepared previously in
3661 the current session.
3662 </para>
3663
3664 <para>
3665 The parameters are identical to <xref linkend="libpq-PQexecParams"/>, except that the
3666 name of a prepared statement is given instead of a query string, and the
3667 <parameter>paramTypes[]</parameter> parameter is not present (it is not needed since
3668 the prepared statement's parameter types were determined when it was created).
3669 </para>
3670 </listitem>
3671 </varlistentry>
3672
3673 <varlistentry id="libpq-PQdescribePrepared">
3674 <term><function>PQdescribePrepared</function><indexterm><primary>PQdescribePrepared</primary></indexterm></term>
3675
3676 <listitem>
3677 <para>
3678 Submits a request to obtain information about the specified
3679 prepared statement, and waits for completion.
3680 <synopsis>
3681 PGresult *PQdescribePrepared(PGconn *conn, const char *stmtName);
3682 </synopsis>
3683 </para>
3684
3685 <para>
3686 <xref linkend="libpq-PQdescribePrepared"/> allows an application to obtain
3687 information about a previously prepared statement.
3688 </para>
3689
3690 <para>
3691 <parameter>stmtName</parameter> can be <literal>""</literal> or <symbol>NULL</symbol> to reference
3692 the unnamed statement, otherwise it must be the name of an existing
3693 prepared statement. On success, a <structname>PGresult</structname> with
3694 status <literal>PGRES_COMMAND_OK</literal> is returned. The
3695 functions <xref linkend="libpq-PQnparams"/> and
3696 <xref linkend="libpq-PQparamtype"/> can be applied to this
3697 <structname>PGresult</structname> to obtain information about the parameters
3698 of the prepared statement, and the functions
3699 <xref linkend="libpq-PQnfields"/>, <xref linkend="libpq-PQfname"/>,
3700 <xref linkend="libpq-PQftype"/>, etc. provide information about the
3701 result columns (if any) of the statement.
3702 </para>
3703 </listitem>
3704 </varlistentry>
3705
3706 <varlistentry id="libpq-PQdescribePortal">
3707 <term><function>PQdescribePortal</function><indexterm><primary>PQdescribePortal</primary></indexterm></term>
3708
3709 <listitem>
3710 <para>
3711 Submits a request to obtain information about the specified
3712 portal, and waits for completion.
3713 <synopsis>
3714 PGresult *PQdescribePortal(PGconn *conn, const char *portalName);
3715 </synopsis>
3716 </para>
3717
3718 <para>
3719 <xref linkend="libpq-PQdescribePortal"/> allows an application to obtain
3720 information about a previously created portal.
3721 (<application>libpq</application> does not provide any direct access to
3722 portals, but you can use this function to inspect the properties
3723 of a cursor created with a <command>DECLARE CURSOR</command> SQL command.)
3724 </para>
3725
3726 <para>
3727 <parameter>portalName</parameter> can be <literal>""</literal> or <symbol>NULL</symbol> to reference
3728 the unnamed portal, otherwise it must be the name of an existing
3729 portal. On success, a <structname>PGresult</structname> with status
3730 <literal>PGRES_COMMAND_OK</literal> is returned. The functions
3731 <xref linkend="libpq-PQnfields"/>, <xref linkend="libpq-PQfname"/>,
3732 <xref linkend="libpq-PQftype"/>, etc. can be applied to the
3733 <structname>PGresult</structname> to obtain information about the result
3734 columns (if any) of the portal.
3735 </para>
3736 </listitem>
3737 </varlistentry>
3738
3739 <varlistentry id="libpq-PQclosePrepared">
3740 <term><function>PQclosePrepared</function><indexterm><primary>PQclosePrepared</primary></indexterm></term>
3741
3742 <listitem>
3743 <para>
3744 Submits a request to close the specified prepared statement, and waits
3745 for completion.
3746 <synopsis>
3747 PGresult *PQclosePrepared(PGconn *conn, const char *stmtName);
3748 </synopsis>
3749 </para>
3750
3751 <para>
3752 <xref linkend="libpq-PQclosePrepared"/> allows an application to close
3753 a previously prepared statement. Closing a statement releases all
3754 of its associated resources on the server and allows its name to be
3755 reused.
3756 </para>
3757
3758 <para>
3759 <parameter>stmtName</parameter> can be <literal>""</literal> or
3760 <symbol>NULL</symbol> to reference the unnamed statement. It is fine
3761 if no statement exists with this name, in that case the operation is a
3762 no-op. On success, a <structname>PGresult</structname> with
3763 status <literal>PGRES_COMMAND_OK</literal> is returned.
3764 </para>
3765 </listitem>
3766 </varlistentry>
3767
3768 <varlistentry id="libpq-PQclosePortal">
3769 <term><function>PQclosePortal</function><indexterm><primary>PQclosePortal</primary></indexterm></term>
3770
3771 <listitem>
3772 <para>
3773 Submits a request to close the specified portal, and waits for
3774 completion.
3775 <synopsis>
3776 PGresult *PQclosePortal(PGconn *conn, const char *portalName);
3777 </synopsis>
3778 </para>
3779
3780 <para>
3781 <xref linkend="libpq-PQclosePortal"/> allows an application to trigger
3782 a close of a previously created portal. Closing a portal releases all
3783 of its associated resources on the server and allows its name to be
3784 reused. (<application>libpq</application> does not provide any
3785 direct access to portals, but you can use this function to close a
3786 cursor created with a <command>DECLARE CURSOR</command> SQL command.)
3787 </para>
3788
3789 <para>
3790 <parameter>portalName</parameter> can be <literal>""</literal> or
3791 <symbol>NULL</symbol> to reference the unnamed portal. It is fine
3792 if no portal exists with this name, in that case the operation is a
3793 no-op. On success, a <structname>PGresult</structname> with status
3794 <literal>PGRES_COMMAND_OK</literal> is returned.
3795 </para>
3796 </listitem>
3797 </varlistentry>
3798 </variablelist>
3799 </para>
3800
3801 <para>
3802 The <structname>PGresult</structname><indexterm><primary>PGresult</primary></indexterm>
3803 structure encapsulates the result returned by the server.
3804 <application>libpq</application> application programmers should be
3805 careful to maintain the <structname>PGresult</structname> abstraction.
3806 Use the accessor functions below to get at the contents of
3807 <structname>PGresult</structname>. Avoid directly referencing the
3808 fields of the <structname>PGresult</structname> structure because they
3809 are subject to change in the future.
3810
3811 <variablelist>
3812 <varlistentry id="libpq-PQresultStatus">
3813 <term><function>PQresultStatus</function><indexterm><primary>PQresultStatus</primary></indexterm></term>
3814
3815 <listitem>
3816 <para>
3817 Returns the result status of the command.
3818 <synopsis>
3819 ExecStatusType PQresultStatus(const PGresult *res);
3820 </synopsis>
3821 </para>
3822
3823 <para>
3824 <xref linkend="libpq-PQresultStatus"/> can return one of the following values:
3825
3826 <variablelist>
3827 <varlistentry id="libpq-pgres-empty-query">
3828 <term><literal>PGRES_EMPTY_QUERY</literal></term>
3829 <listitem>
3830 <para>
3831 The string sent to the server was empty.
3832 </para>
3833 </listitem>
3834 </varlistentry>
3835
3836 <varlistentry id="libpq-pgres-command-ok">
3837 <term><literal>PGRES_COMMAND_OK</literal></term>
3838 <listitem>
3839 <para>
3840 Successful completion of a command returning no data.
3841 </para>
3842 </listitem>
3843 </varlistentry>
3844
3845 <varlistentry id="libpq-pgres-tuples-ok">
3846 <term><literal>PGRES_TUPLES_OK</literal></term>
3847 <listitem>
3848 <para>
3849 Successful completion of a command returning data (such as
3850 a <command>SELECT</command> or <command>SHOW</command>).
3851 </para>
3852 </listitem>
3853 </varlistentry>
3854
3855 <varlistentry id="libpq-pgres-copy-out">
3856 <term><literal>PGRES_COPY_OUT</literal></term>
3857 <listitem>
3858 <para>
3859 Copy Out (from server) data transfer started.
3860 </para>
3861 </listitem>
3862 </varlistentry>
3863
3864 <varlistentry id="libpq-pgres-copy-in">
3865 <term><literal>PGRES_COPY_IN</literal></term>
3866 <listitem>
3867 <para>
3868 Copy In (to server) data transfer started.
3869 </para>
3870 </listitem>
3871 </varlistentry>
3872
3873 <varlistentry id="libpq-pgres-bad-response">
3874 <term><literal>PGRES_BAD_RESPONSE</literal></term>
3875 <listitem>
3876 <para>
3877 The server's response was not understood.
3878 </para>
3879 </listitem>
3880 </varlistentry>
3881
3882 <varlistentry id="libpq-pgres-nonfatal-error">
3883 <term><literal>PGRES_NONFATAL_ERROR</literal></term>
3884 <listitem>
3885 <para>
3886 A nonfatal error (a notice or warning) occurred.
3887 </para>
3888 </listitem>
3889 </varlistentry>
3890
3891 <varlistentry id="libpq-pgres-fatal-error">
3892 <term><literal>PGRES_FATAL_ERROR</literal></term>
3893 <listitem>
3894 <para>
3895 A fatal error occurred.
3896 </para>
3897 </listitem>
3898 </varlistentry>
3899
3900 <varlistentry id="libpq-pgres-copy-both">
3901 <term><literal>PGRES_COPY_BOTH</literal></term>
3902 <listitem>
3903 <para>
3904 Copy In/Out (to and from server) data transfer started. This
3905 feature is currently used only for streaming replication,
3906 so this status should not occur in ordinary applications.
3907 </para>
3908 </listitem>
3909 </varlistentry>
3910
3911 <varlistentry id="libpq-pgres-single-tuple">
3912 <term><literal>PGRES_SINGLE_TUPLE</literal></term>
3913 <listitem>
3914 <para>
3915 The <structname>PGresult</structname> contains a single result tuple
3916 from the current command. This status occurs only when
3917 single-row mode has been selected for the query
3918 (see <xref linkend="libpq-single-row-mode"/>).
3919 </para>
3920 </listitem>
3921 </varlistentry>
3922
3923 <varlistentry id="libpq-pgres-tuples-chunk">
3924 <term><literal>PGRES_TUPLES_CHUNK</literal></term>
3925 <listitem>
3926 <para>
3927 The <structname>PGresult</structname> contains several result tuples
3928 from the current command. This status occurs only when
3929 chunked mode has been selected for the query
3930 (see <xref linkend="libpq-single-row-mode"/>).
3931 The number of tuples will not exceed the limit passed to
3932 <xref linkend="libpq-PQsetChunkedRowsMode"/>.
3933 </para>
3934 </listitem>
3935 </varlistentry>
3936
3937 <varlistentry id="libpq-pgres-pipeline-sync">
3938 <term><literal>PGRES_PIPELINE_SYNC</literal></term>
3939 <listitem>
3940 <para>
3941 The <structname>PGresult</structname> represents a
3942 synchronization point in pipeline mode, requested by either
3943 <xref linkend="libpq-PQpipelineSync"/> or
3944 <xref linkend="libpq-PQsendPipelineSync"/>.
3945 This status occurs only when pipeline mode has been selected.
3946 </para>
3947 </listitem>
3948 </varlistentry>
3949
3950 <varlistentry id="libpq-pgres-pipeline-aborted">
3951 <term><literal>PGRES_PIPELINE_ABORTED</literal></term>
3952 <listitem>
3953 <para>
3954 The <structname>PGresult</structname> represents a pipeline that has
3955 received an error from the server. <function>PQgetResult</function>
3956 must be called repeatedly, and each time it will return this status code
3957 until the end of the current pipeline, at which point it will return
3958 <literal>PGRES_PIPELINE_SYNC</literal> and normal processing can
3959 resume.
3960 </para>
3961 </listitem>
3962 </varlistentry>
3963
3964 </variablelist>
3965
3966 If the result status is <literal>PGRES_TUPLES_OK</literal>,
3967 <literal>PGRES_SINGLE_TUPLE</literal>, or
3968 <literal>PGRES_TUPLES_CHUNK</literal>, then
3969 the functions described below can be used to retrieve the rows
3970 returned by the query. Note that a <command>SELECT</command>
3971 command that happens to retrieve zero rows still shows
3972 <literal>PGRES_TUPLES_OK</literal>.
3973 <literal>PGRES_COMMAND_OK</literal> is for commands that can never
3974 return rows (<command>INSERT</command> or <command>UPDATE</command>
3975 without a <literal>RETURNING</literal> clause,
3976 etc.). A response of <literal>PGRES_EMPTY_QUERY</literal> might
3977 indicate a bug in the client software.
3978 </para>
3979
3980 <para>
3981 A result of status <symbol>PGRES_NONFATAL_ERROR</symbol> will
3982 never be returned directly by <xref linkend="libpq-PQexec"/> or other
3983 query execution functions; results of this kind are instead passed
3984 to the notice processor (see <xref
3985 linkend="libpq-notice-processing"/>).
3986 </para>
3987 </listitem>
3988 </varlistentry>
3989
3990 <varlistentry id="libpq-PQresStatus">
3991 <term><function>PQresStatus</function><indexterm><primary>PQresStatus</primary></indexterm></term>
3992
3993 <listitem>
3994 <para>
3995 Converts the enumerated type returned by
3996 <xref linkend="libpq-PQresultStatus"/> into a string constant describing the
3997 status code. The caller should not free the result.
3998
3999 <synopsis>
4000 char *PQresStatus(ExecStatusType status);
4001 </synopsis>
4002 </para>
4003 </listitem>
4004 </varlistentry>
4005
4006 <varlistentry id="libpq-PQresultErrorMessage">
4007 <term><function>PQresultErrorMessage</function><indexterm><primary>PQresultErrorMessage</primary></indexterm></term>
4008
4009 <listitem>
4010 <para>
4011 Returns the error message associated with the command, or an empty string
4012 if there was no error.
4013 <synopsis>
4014 char *PQresultErrorMessage(const PGresult *res);
4015 </synopsis>
4016 If there was an error, the returned string will include a trailing
4017 newline. The caller should not free the result directly. It will
4018 be freed when the associated <structname>PGresult</structname> handle is
4019 passed to <xref linkend="libpq-PQclear"/>.
4020 </para>
4021
4022 <para>
4023 Immediately following a <xref linkend="libpq-PQexec"/> or
4024 <xref linkend="libpq-PQgetResult"/> call,
4025 <xref linkend="libpq-PQerrorMessage"/> (on the connection) will return
4026 the same string as <xref linkend="libpq-PQresultErrorMessage"/> (on
4027 the result). However, a <structname>PGresult</structname> will
4028 retain its error message until destroyed, whereas the connection's
4029 error message will change when subsequent operations are done.
4030 Use <xref linkend="libpq-PQresultErrorMessage"/> when you want to
4031 know the status associated with a particular
4032 <structname>PGresult</structname>; use
4033 <xref linkend="libpq-PQerrorMessage"/> when you want to know the
4034 status from the latest operation on the connection.
4035 </para>
4036 </listitem>
4037 </varlistentry>
4038
4039 <varlistentry id="libpq-PQresultVerboseErrorMessage">
4040 <term><function>PQresultVerboseErrorMessage</function><indexterm><primary>PQresultVerboseErrorMessage</primary></indexterm></term>
4041
4042 <listitem>
4043 <para>
4044 Returns a reformatted version of the error message associated with
4045 a <structname>PGresult</structname> object.
4046 <synopsis>
4047 char *PQresultVerboseErrorMessage(const PGresult *res,
4048 PGVerbosity verbosity,
4049 PGContextVisibility show_context);
4050 </synopsis>
4051 In some situations a client might wish to obtain a more detailed
4052 version of a previously-reported error.
4053 <xref linkend="libpq-PQresultVerboseErrorMessage"/> addresses this need
4054 by computing the message that would have been produced
4055 by <xref linkend="libpq-PQresultErrorMessage"/> if the specified
4056 verbosity settings had been in effect for the connection when the
4057 given <structname>PGresult</structname> was generated. If
4058 the <structname>PGresult</structname> is not an error result,
4059 <quote>PGresult is not an error result</quote> is reported instead.
4060 The returned string includes a trailing newline.
4061 </para>
4062
4063 <para>
4064 Unlike most other functions for extracting data from
4065 a <structname>PGresult</structname>, the result of this function is a freshly
4066 allocated string. The caller must free it
4067 using <function>PQfreemem()</function> when the string is no longer needed.
4068 </para>
4069
4070 <para>
4071 A NULL return is possible if there is insufficient memory.
4072 </para>
4073 </listitem>
4074 </varlistentry>
4075
4076 <varlistentry id="libpq-PQresultErrorField">
4077 <term><function>PQresultErrorField</function><indexterm><primary>PQresultErrorField</primary></indexterm></term>
4078 <listitem>
4079 <para>
4080 Returns an individual field of an error report.
4081 <synopsis>
4082 char *PQresultErrorField(const PGresult *res, int fieldcode);
4083 </synopsis>
4084 <parameter>fieldcode</parameter> is an error field identifier; see the symbols
4085 listed below. <symbol>NULL</symbol> is returned if the
4086 <structname>PGresult</structname> is not an error or warning result,
4087 or does not include the specified field. Field values will normally
4088 not include a trailing newline. The caller should not free the
4089 result directly. It will be freed when the
4090 associated <structname>PGresult</structname> handle is passed to
4091 <xref linkend="libpq-PQclear"/>.
4092 </para>
4093
4094 <para>
4095 The following field codes are available:
4096 <variablelist>
4097 <varlistentry id="libpq-pg-diag-severity">
4098 <term><symbol>PG_DIAG_SEVERITY</symbol></term>
4099 <listitem>
4100 <para>
4101 The severity; the field contents are <literal>ERROR</literal>,
4102 <literal>FATAL</literal>, or <literal>PANIC</literal> (in an error message),
4103 or <literal>WARNING</literal>, <literal>NOTICE</literal>, <literal>DEBUG</literal>,
4104 <literal>INFO</literal>, or <literal>LOG</literal> (in a notice message), or
4105 a localized translation of one of these. Always present.
4106 </para>
4107 </listitem>
4108 </varlistentry>
4109
4110 <varlistentry id="libpq-PG-diag-severity-nonlocalized">
4111 <term><symbol>PG_DIAG_SEVERITY_NONLOCALIZED</symbol></term>
4112 <listitem>
4113 <para>
4114 The severity; the field contents are <literal>ERROR</literal>,
4115 <literal>FATAL</literal>, or <literal>PANIC</literal> (in an error message),
4116 or <literal>WARNING</literal>, <literal>NOTICE</literal>, <literal>DEBUG</literal>,
4117 <literal>INFO</literal>, or <literal>LOG</literal> (in a notice message).
4118 This is identical to the <symbol>PG_DIAG_SEVERITY</symbol> field except
4119 that the contents are never localized. This is present only in
4120 reports generated by <productname>PostgreSQL</productname> versions 9.6
4121 and later.
4122 </para>
4123 </listitem>
4124 </varlistentry>
4125
4126 <varlistentry id="libpq-pg-diag-sqlstate">
4127 <term><symbol>PG_DIAG_SQLSTATE</symbol><indexterm
4128 ><primary>error codes</primary><secondary>libpq</secondary></indexterm></term>
4129 <listitem>
4130 <para>
4131 The SQLSTATE code for the error. The SQLSTATE code identifies
4132 the type of error that has occurred; it can be used by
4133 front-end applications to perform specific operations (such
4134 as error handling) in response to a particular database error.
4135 For a list of the possible SQLSTATE codes, see <xref
4136 linkend="errcodes-appendix"/>. This field is not localizable,
4137 and is always present.
4138 </para>
4139 </listitem>
4140 </varlistentry>
4141
4142 <varlistentry id="libpq-pg-diag-message-primary">
4143 <term><symbol>PG_DIAG_MESSAGE_PRIMARY</symbol></term>
4144 <listitem>
4145 <para>
4146 The primary human-readable error message (typically one line).
4147 Always present.
4148 </para>
4149 </listitem>
4150 </varlistentry>
4151
4152 <varlistentry id="libpq-pg-diag-message-detail">
4153 <term><symbol>PG_DIAG_MESSAGE_DETAIL</symbol></term>
4154 <listitem>
4155 <para>
4156 Detail: an optional secondary error message carrying more
4157 detail about the problem. Might run to multiple lines.
4158 </para>
4159 </listitem>
4160 </varlistentry>
4161
4162 <varlistentry id="libpq-pg-diag-message-hint">
4163 <term><symbol>PG_DIAG_MESSAGE_HINT</symbol></term>
4164 <listitem>
4165 <para>
4166 Hint: an optional suggestion what to do about the problem.
4167 This is intended to differ from detail in that it offers advice
4168 (potentially inappropriate) rather than hard facts. Might
4169 run to multiple lines.
4170 </para>
4171 </listitem>
4172 </varlistentry>
4173
4174 <varlistentry id="libpq-pg-diag-statement-position">
4175 <term><symbol>PG_DIAG_STATEMENT_POSITION</symbol></term>
4176 <listitem>
4177 <para>
4178 A string containing a decimal integer indicating an error cursor
4179 position as an index into the original statement string. The
4180 first character has index 1, and positions are measured in
4181 characters not bytes.
4182 </para>
4183 </listitem>
4184 </varlistentry>
4185
4186 <varlistentry id="libpq-pg-diag-internal-position">
4187 <term><symbol>PG_DIAG_INTERNAL_POSITION</symbol></term>
4188 <listitem>
4189 <para>
4190 This is defined the same as the
4191 <symbol>PG_DIAG_STATEMENT_POSITION</symbol> field, but it is used
4192 when the cursor position refers to an internally generated
4193 command rather than the one submitted by the client. The
4194 <symbol>PG_DIAG_INTERNAL_QUERY</symbol> field will always appear when
4195 this field appears.
4196 </para>
4197 </listitem>
4198 </varlistentry>
4199
4200 <varlistentry id="libpq-pg-diag-internal-query">
4201 <term><symbol>PG_DIAG_INTERNAL_QUERY</symbol></term>
4202 <listitem>
4203 <para>
4204 The text of a failed internally-generated command. This could
4205 be, for example, an SQL query issued by a PL/pgSQL function.
4206 </para>
4207 </listitem>
4208 </varlistentry>
4209
4210 <varlistentry id="libpq-pg-diag-context">
4211 <term><symbol>PG_DIAG_CONTEXT</symbol></term>
4212 <listitem>
4213 <para>
4214 An indication of the context in which the error occurred.
4215 Presently this includes a call stack traceback of active
4216 procedural language functions and internally-generated queries.
4217 The trace is one entry per line, most recent first.
4218 </para>
4219 </listitem>
4220 </varlistentry>
4221
4222 <varlistentry id="libpq-pg-diag-schema-name">
4223 <term><symbol>PG_DIAG_SCHEMA_NAME</symbol></term>
4224 <listitem>
4225 <para>
4226 If the error was associated with a specific database object,
4227 the name of the schema containing that object, if any.
4228 </para>
4229 </listitem>
4230 </varlistentry>
4231
4232 <varlistentry id="libpq-pg-diag-table-name">
4233 <term><symbol>PG_DIAG_TABLE_NAME</symbol></term>
4234 <listitem>
4235 <para>
4236 If the error was associated with a specific table, the name of the
4237 table. (Refer to the schema name field for the name of the
4238 table's schema.)
4239 </para>
4240 </listitem>
4241 </varlistentry>
4242
4243 <varlistentry id="libpq-pg-diag-column-name">
4244 <term><symbol>PG_DIAG_COLUMN_NAME</symbol></term>
4245 <listitem>
4246 <para>
4247 If the error was associated with a specific table column, the name
4248 of the column. (Refer to the schema and table name fields to
4249 identify the table.)
4250 </para>
4251 </listitem>
4252 </varlistentry>
4253
4254 <varlistentry id="libpq-pg-diag-datatype-name">
4255 <term><symbol>PG_DIAG_DATATYPE_NAME</symbol></term>
4256 <listitem>
4257 <para>
4258 If the error was associated with a specific data type, the name of
4259 the data type. (Refer to the schema name field for the name of
4260 the data type's schema.)
4261 </para>
4262 </listitem>
4263 </varlistentry>
4264
4265 <varlistentry id="libpq-pg-diag-constraint-name">
4266 <term><symbol>PG_DIAG_CONSTRAINT_NAME</symbol></term>
4267 <listitem>
4268 <para>
4269 If the error was associated with a specific constraint, the name
4270 of the constraint. Refer to fields listed above for the
4271 associated table or domain. (For this purpose, indexes are
4272 treated as constraints, even if they weren't created with
4273 constraint syntax.)
4274 </para>
4275 </listitem>
4276 </varlistentry>
4277
4278 <varlistentry id="libpq-pg-diag-source-file">
4279 <term><symbol>PG_DIAG_SOURCE_FILE</symbol></term>
4280 <listitem>
4281 <para>
4282 The file name of the source-code location where the error was
4283 reported.
4284 </para>
4285 </listitem>
4286 </varlistentry>
4287
4288 <varlistentry id="libpq-pg-diag-source-line">
4289 <term><symbol>PG_DIAG_SOURCE_LINE</symbol></term>
4290 <listitem>
4291 <para>
4292 The line number of the source-code location where the error
4293 was reported.
4294 </para>
4295 </listitem>
4296 </varlistentry>
4297
4298 <varlistentry id="libpq-pg-diag-source-function">
4299 <term><symbol>PG_DIAG_SOURCE_FUNCTION</symbol></term>
4300 <listitem>
4301 <para>
4302 The name of the source-code function reporting the error.
4303 </para>
4304 </listitem>
4305 </varlistentry>
4306 </variablelist>
4307 </para>
4308
4309 <note>
4310 <para>
4311 The fields for schema name, table name, column name, data type name,
4312 and constraint name are supplied only for a limited number of error
4313 types; see <xref linkend="errcodes-appendix"/>. Do not assume that
4314 the presence of any of these fields guarantees the presence of
4315 another field. Core error sources observe the interrelationships
4316 noted above, but user-defined functions may use these fields in other
4317 ways. In the same vein, do not assume that these fields denote
4318 contemporary objects in the current database.
4319 </para>
4320 </note>
4321
4322 <para>
4323 The client is responsible for formatting displayed information to meet
4324 its needs; in particular it should break long lines as needed.
4325 Newline characters appearing in the error message fields should be
4326 treated as paragraph breaks, not line breaks.
4327 </para>
4328
4329 <para>
4330 Errors generated internally by <application>libpq</application> will
4331 have severity and primary message, but typically no other fields.
4332 </para>
4333
4334 <para>
4335 Note that error fields are only available from
4336 <structname>PGresult</structname> objects, not
4337 <structname>PGconn</structname> objects; there is no
4338 <function>PQerrorField</function> function.
4339 </para>
4340 </listitem>
4341 </varlistentry>
4342
4343 <varlistentry id="libpq-PQclear">
4344 <term><function>PQclear</function><indexterm><primary>PQclear</primary></indexterm></term>
4345 <listitem>
4346 <para>
4347 Frees the storage associated with a
4348 <structname>PGresult</structname>. Every command result should be
4349 freed via <xref linkend="libpq-PQclear"/> when it is no longer
4350 needed.
4351
4352 <synopsis>
4353 void PQclear(PGresult *res);
4354 </synopsis>
4355
4356 If the argument is a <symbol>NULL</symbol> pointer, no operation is
4357 performed.
4358 </para>
4359
4360 <para>
4361 You can keep a <structname>PGresult</structname> object around for
4362 as long as you need it; it does not go away when you issue a new
4363 command, nor even if you close the connection. To get rid of it,
4364 you must call <xref linkend="libpq-PQclear"/>. Failure to do this
4365 will result in memory leaks in your application.
4366 </para>
4367 </listitem>
4368 </varlistentry>
4369 </variablelist>
4370 </para>
4371 </sect2>
4372
4373 <sect2 id="libpq-exec-select-info">
4374 <title>Retrieving Query Result Information</title>
4375
4376 <para>
4377 These functions are used to extract information from a
4378 <structname>PGresult</structname> object that represents a successful
4379 query result (that is, one that has status
4380 <literal>PGRES_TUPLES_OK</literal>,
4381 <literal>PGRES_SINGLE_TUPLE</literal>, or
4382 <literal>PGRES_TUPLES_CHUNK</literal>).
4383 They can also be used to extract
4384 information from a successful Describe operation: a Describe's result
4385 has all the same column information that actual execution of the query
4386 would provide, but it has zero rows. For objects with other status values,
4387 these functions will act as though the result has zero rows and zero columns.
4388 </para>
4389
4390 <variablelist>
4391 <varlistentry id="libpq-PQntuples">
4392 <term><function>PQntuples</function><indexterm><primary>PQntuples</primary></indexterm></term>
4393
4394 <listitem>
4395 <para>
4396 Returns the number of rows (tuples) in the query result.
4397 (Note that <structname>PGresult</structname> objects are limited to no more
4398 than <literal>INT_MAX</literal> rows, so an <type>int</type> result is
4399 sufficient.)
4400
4401 <synopsis>
4402 int PQntuples(const PGresult *res);
4403 </synopsis>
4404
4405 </para>
4406 </listitem>
4407 </varlistentry>
4408
4409 <varlistentry id="libpq-PQnfields">
4410 <term><function>PQnfields</function><indexterm><primary>PQnfields</primary></indexterm></term>
4411
4412 <listitem>
4413 <para>
4414 Returns the number of columns (fields) in each row of the query
4415 result.
4416
4417 <synopsis>
4418 int PQnfields(const PGresult *res);
4419 </synopsis>
4420 </para>
4421 </listitem>
4422 </varlistentry>
4423
4424 <varlistentry id="libpq-PQfname">
4425 <term><function>PQfname</function><indexterm><primary>PQfname</primary></indexterm></term>
4426
4427 <listitem>
4428 <para>
4429 Returns the column name associated with the given column number.
4430 Column numbers start at 0. The caller should not free the result
4431 directly. It will be freed when the associated
4432 <structname>PGresult</structname> handle is passed to
4433 <xref linkend="libpq-PQclear"/>.
4434 <synopsis>
4435 char *PQfname(const PGresult *res,
4436 int column_number);
4437 </synopsis>
4438 </para>
4439
4440 <para>
4441 <symbol>NULL</symbol> is returned if the column number is out of range.
4442 </para>
4443 </listitem>
4444 </varlistentry>
4445
4446 <varlistentry id="libpq-PQfnumber">
4447 <term><function>PQfnumber</function><indexterm><primary>PQfnumber</primary></indexterm></term>
4448
4449 <listitem>
4450 <para>
4451 Returns the column number associated with the given column name.
4452 <synopsis>
4453 int PQfnumber(const PGresult *res,
4454 const char *column_name);
4455 </synopsis>
4456 </para>
4457
4458 <para>
4459 -1 is returned if the given name does not match any column.
4460 </para>
4461
4462 <para>
4463 The given name is treated like an identifier in an SQL command,
4464 that is, it is downcased unless double-quoted. For example, given
4465 a query result generated from the SQL command:
4466 <programlisting>
4467 SELECT 1 AS FOO, 2 AS "BAR";
4468 </programlisting>
4469 we would have the results:
4470 <programlisting>
4471 PQfname(res, 0) <lineannotation>foo</lineannotation>
4472 PQfname(res, 1) <lineannotation>BAR</lineannotation>
4473 PQfnumber(res, "FOO") <lineannotation>0</lineannotation>
4474 PQfnumber(res, "foo") <lineannotation>0</lineannotation>
4475 PQfnumber(res, "BAR") <lineannotation>-1</lineannotation>
4476 PQfnumber(res, "\"BAR\"") <lineannotation>1</lineannotation>
4477 </programlisting>
4478 </para>
4479 </listitem>
4480 </varlistentry>
4481
4482 <varlistentry id="libpq-PQftable">
4483 <term><function>PQftable</function><indexterm><primary>PQftable</primary></indexterm></term>
4484
4485 <listitem>
4486 <para>
4487 Returns the OID of the table from which the given column was
4488 fetched. Column numbers start at 0.
4489 <synopsis>
4490 Oid PQftable(const PGresult *res,
4491 int column_number);
4492 </synopsis>
4493 </para>
4494
4495 <para>
4496 <literal>InvalidOid</literal> is returned if the column number is out of range,
4497 or if the specified column is not a simple reference to a table column.
4498 You can query the system table <literal>pg_class</literal> to determine
4499 exactly which table is referenced.
4500 </para>
4501
4502 <para>
4503 The type <type>Oid</type> and the constant
4504 <literal>InvalidOid</literal> will be defined when you include
4505 the <application>libpq</application> header file. They will both
4506 be some integer type.
4507 </para>
4508 </listitem>
4509 </varlistentry>
4510
4511 <varlistentry id="libpq-PQftablecol">
4512 <term><function>PQftablecol</function><indexterm><primary>PQftablecol</primary></indexterm></term>
4513
4514 <listitem>
4515 <para>
4516 Returns the column number (within its table) of the column making
4517 up the specified query result column. Query-result column numbers
4518 start at 0, but table columns have nonzero numbers.
4519 <synopsis>
4520 int PQftablecol(const PGresult *res,
4521 int column_number);
4522 </synopsis>
4523 </para>
4524
4525 <para>
4526 Zero is returned if the column number is out of range, or if the
4527 specified column is not a simple reference to a table column.
4528 </para>
4529 </listitem>
4530 </varlistentry>
4531
4532 <varlistentry id="libpq-PQfformat">
4533 <term><function>PQfformat</function><indexterm><primary>PQfformat</primary></indexterm></term>
4534
4535 <listitem>
4536 <para>
4537 Returns the format code indicating the format of the given
4538 column. Column numbers start at 0.
4539 <synopsis>
4540 int PQfformat(const PGresult *res,
4541 int column_number);
4542 </synopsis>
4543 </para>
4544
4545 <para>
4546 Format code zero indicates textual data representation, while format
4547 code one indicates binary representation. (Other codes are reserved
4548 for future definition.)
4549 </para>
4550 </listitem>
4551 </varlistentry>
4552
4553 <varlistentry id="libpq-PQftype">
4554 <term><function>PQftype</function><indexterm><primary>PQftype</primary></indexterm></term>
4555
4556 <listitem>
4557 <para>
4558 Returns the data type associated with the given column number.
4559 The integer returned is the internal OID number of the type.
4560 Column numbers start at 0.
4561 <synopsis>
4562 Oid PQftype(const PGresult *res,
4563 int column_number);
4564 </synopsis>
4565 </para>
4566
4567 <para>
4568 You can query the system table <literal>pg_type</literal> to
4569 obtain the names and properties of the various data types. The
4570 <acronym>OID</acronym>s of the built-in data types are defined
4571 in the file <filename>catalog/pg_type_d.h</filename>
4572 in the <productname>PostgreSQL</productname>
4573 installation's <filename>include</filename> directory.
4574 </para>
4575 </listitem>
4576 </varlistentry>
4577
4578 <varlistentry id="libpq-PQfmod">
4579 <term><function>PQfmod</function><indexterm><primary>PQfmod</primary></indexterm></term>
4580
4581 <listitem>
4582 <para>
4583 Returns the type modifier of the column associated with the
4584 given column number. Column numbers start at 0.
4585 <synopsis>
4586 int PQfmod(const PGresult *res,
4587 int column_number);
4588 </synopsis>
4589 </para>
4590
4591 <para>
4592 The interpretation of modifier values is type-specific; they
4593 typically indicate precision or size limits. The value -1 is
4594 used to indicate <quote>no information available</quote>. Most data
4595 types do not use modifiers, in which case the value is always
4596 -1.
4597 </para>
4598 </listitem>
4599 </varlistentry>
4600
4601 <varlistentry id="libpq-PQfsize">
4602 <term><function>PQfsize</function><indexterm><primary>PQfsize</primary></indexterm></term>
4603
4604 <listitem>
4605 <para>
4606 Returns the size in bytes of the column associated with the
4607 given column number. Column numbers start at 0.
4608 <synopsis>
4609 int PQfsize(const PGresult *res,
4610 int column_number);
4611 </synopsis>
4612 </para>
4613
4614 <para>
4615 <xref linkend="libpq-PQfsize"/> returns the space allocated for this column
4616 in a database row, in other words the size of the server's
4617 internal representation of the data type. (Accordingly, it is
4618 not really very useful to clients.) A negative value indicates
4619 the data type is variable-length.
4620 </para>
4621 </listitem>
4622 </varlistentry>
4623
4624 <varlistentry id="libpq-PQbinaryTuples">
4625 <term><function>PQbinaryTuples</function><indexterm><primary>PQbinaryTuples</primary></indexterm></term>
4626
4627 <listitem>
4628 <para>
4629 Returns 1 if the <structname>PGresult</structname> contains binary data
4630 and 0 if it contains text data.
4631 <synopsis>
4632 int PQbinaryTuples(const PGresult *res);
4633 </synopsis>
4634 </para>
4635
4636 <para>
4637 This function is deprecated (except for its use in connection with
4638 <command>COPY</command>), because it is possible for a single
4639 <structname>PGresult</structname> to contain text data in some columns and
4640 binary data in others. <xref linkend="libpq-PQfformat"/> is preferred.
4641 <xref linkend="libpq-PQbinaryTuples"/> returns 1 only if all columns of the
4642 result are binary (format 1).
4643 </para>
4644 </listitem>
4645 </varlistentry>
4646
4647 <varlistentry id="libpq-PQgetvalue">
4648 <term><function>PQgetvalue</function><indexterm><primary>PQgetvalue</primary></indexterm></term>
4649
4650 <listitem>
4651 <para>
4652 Returns a single field value of one row of a
4653 <structname>PGresult</structname>. Row and column numbers start
4654 at 0. The caller should not free the result directly. It will
4655 be freed when the associated <structname>PGresult</structname> handle is
4656 passed to <xref linkend="libpq-PQclear"/>.
4657 <synopsis>
4658 char *PQgetvalue(const PGresult *res,
4659 int row_number,
4660 int column_number);
4661 </synopsis>
4662 </para>
4663
4664 <para>
4665 For data in text format, the value returned by
4666 <xref linkend="libpq-PQgetvalue"/> is a null-terminated character
4667 string representation of the field value. For data in binary
4668 format, the value is in the binary representation determined by
4669 the data type's <function>typsend</function> and <function>typreceive</function>
4670 functions. (The value is actually followed by a zero byte in
4671 this case too, but that is not ordinarily useful, since the
4672 value is likely to contain embedded nulls.)
4673 </para>
4674
4675 <para>
4676 An empty string is returned if the field value is null. See
4677 <xref linkend="libpq-PQgetisnull"/> to distinguish null values from
4678 empty-string values.
4679 </para>
4680
4681 <para>
4682 The pointer returned by <xref linkend="libpq-PQgetvalue"/> points
4683 to storage that is part of the <structname>PGresult</structname>
4684 structure. One should not modify the data it points to, and one
4685 must explicitly copy the data into other storage if it is to be
4686 used past the lifetime of the <structname>PGresult</structname>
4687 structure itself.
4688 </para>
4689 </listitem>
4690 </varlistentry>
4691
4692 <varlistentry id="libpq-PQgetisnull">
4693 <term><function>PQgetisnull</function><indexterm
4694 ><primary>PQgetisnull</primary></indexterm><indexterm
4695 ><primary>null value</primary><secondary sortas="libpq">in libpq</secondary></indexterm></term>
4696
4697 <listitem>
4698 <para>
4699 Tests a field for a null value. Row and column numbers start
4700 at 0.
4701 <synopsis>
4702 int PQgetisnull(const PGresult *res,
4703 int row_number,
4704 int column_number);
4705 </synopsis>
4706 </para>
4707
4708 <para>
4709 This function returns 1 if the field is null and 0 if it
4710 contains a non-null value. (Note that
4711 <xref linkend="libpq-PQgetvalue"/> will return an empty string,
4712 not a null pointer, for a null field.)
4713 </para>
4714 </listitem>
4715 </varlistentry>
4716
4717 <varlistentry id="libpq-PQgetlength">
4718 <term><function>PQgetlength</function><indexterm><primary>PQgetlength</primary></indexterm></term>
4719
4720 <listitem>
4721 <para>
4722 Returns the actual length of a field value in bytes. Row and
4723 column numbers start at 0.
4724 <synopsis>
4725 int PQgetlength(const PGresult *res,
4726 int row_number,
4727 int column_number);
4728 </synopsis>
4729 </para>
4730
4731 <para>
4732 This is the actual data length for the particular data value,
4733 that is, the size of the object pointed to by
4734 <xref linkend="libpq-PQgetvalue"/>. For text data format this is
4735 the same as <function>strlen()</function>. For binary format this is
4736 essential information. Note that one should <emphasis>not</emphasis>
4737 rely on <xref linkend="libpq-PQfsize"/> to obtain the actual data
4738 length.
4739 </para>
4740 </listitem>
4741 </varlistentry>
4742
4743 <varlistentry id="libpq-PQnparams">
4744 <term><function>PQnparams</function><indexterm><primary>PQnparams</primary></indexterm></term>
4745
4746 <listitem>
4747 <para>
4748 Returns the number of parameters of a prepared statement.
4749 <synopsis>
4750 int PQnparams(const PGresult *res);
4751 </synopsis>
4752 </para>
4753
4754 <para>
4755 This function is only useful when inspecting the result of
4756 <xref linkend="libpq-PQdescribePrepared"/>. For other types of results it
4757 will return zero.
4758 </para>
4759 </listitem>
4760 </varlistentry>
4761
4762 <varlistentry id="libpq-PQparamtype">
4763 <term><function>PQparamtype</function><indexterm><primary>PQparamtype</primary></indexterm></term>
4764
4765 <listitem>
4766 <para>
4767 Returns the data type of the indicated statement parameter.
4768 Parameter numbers start at 0.
4769 <synopsis>
4770 Oid PQparamtype(const PGresult *res, int param_number);
4771 </synopsis>
4772 </para>
4773
4774 <para>
4775 This function is only useful when inspecting the result of
4776 <xref linkend="libpq-PQdescribePrepared"/>. For other types of results it
4777 will return zero.
4778 </para>
4779 </listitem>
4780 </varlistentry>
4781
4782 <varlistentry id="libpq-PQprint">
4783 <term><function>PQprint</function><indexterm><primary>PQprint</primary></indexterm></term>
4784
4785 <listitem>
4786 <para>
4787 Prints out all the rows and, optionally, the column names to
4788 the specified output stream.
4789 <synopsis>
4790 void PQprint(FILE *fout, /* output stream */
4791 const PGresult *res,
4792 const PQprintOpt *po);
4793 typedef struct
4794 {
4795 pqbool header; /* print output field headings and row count */
4796 pqbool align; /* fill align the fields */
4797 pqbool standard; /* old brain dead format */
4798 pqbool html3; /* output HTML tables */
4799 pqbool expanded; /* expand tables */
4800 pqbool pager; /* use pager for output if needed */
4801 char *fieldSep; /* field separator */
4802 char *tableOpt; /* attributes for HTML table element */
4803 char *caption; /* HTML table caption */
4804 char **fieldName; /* null-terminated array of replacement field names */
4805 } PQprintOpt;
4806 </synopsis>
4807 </para>
4808
4809 <para>
4810 This function was formerly used by <application>psql</application>
4811 to print query results, but this is no longer the case. Note
4812 that it assumes all the data is in text format.
4813 </para>
4814 </listitem>
4815 </varlistentry>
4816 </variablelist>
4817 </sect2>
4818
4819 <sect2 id="libpq-exec-nonselect">
4820 <title>Retrieving Other Result Information</title>
4821
4822 <para>
4823 These functions are used to extract other information from
4824 <structname>PGresult</structname> objects.
4825 </para>
4826
4827 <variablelist>
4828 <varlistentry id="libpq-PQcmdStatus">
4829 <term><function>PQcmdStatus</function><indexterm><primary>PQcmdStatus</primary></indexterm></term>
4830
4831 <listitem>
4832 <para>
4833 Returns the command status tag from the SQL command that generated
4834 the <structname>PGresult</structname>.
4835 <synopsis>
4836 char *PQcmdStatus(PGresult *res);
4837 </synopsis>
4838 </para>
4839
4840 <para>
4841 Commonly this is just the name of the command, but it might include
4842 additional data such as the number of rows processed. The caller
4843 should not free the result directly. It will be freed when the
4844 associated <structname>PGresult</structname> handle is passed to
4845 <xref linkend="libpq-PQclear"/>.
4846 </para>
4847 </listitem>
4848 </varlistentry>
4849
4850 <varlistentry id="libpq-PQcmdTuples">
4851 <term><function>PQcmdTuples</function><indexterm><primary>PQcmdTuples</primary></indexterm></term>
4852
4853 <listitem>
4854 <para>
4855 Returns the number of rows affected by the SQL command.
4856 <synopsis>
4857 char *PQcmdTuples(PGresult *res);
4858 </synopsis>
4859 </para>
4860
4861 <para>
4862 This function returns a string containing the number of rows
4863 affected by the <acronym>SQL</acronym> statement that generated the
4864 <structname>PGresult</structname>. This function can only be used following
4865 the execution of a <command>SELECT</command>, <command>CREATE TABLE AS</command>,
4866 <command>INSERT</command>, <command>UPDATE</command>, <command>DELETE</command>,
4867 <command>MERGE</command>, <command>MOVE</command>, <command>FETCH</command>,
4868 or <command>COPY</command> statement, or an <command>EXECUTE</command> of a
4869 prepared query that contains an <command>INSERT</command>,
4870 <command>UPDATE</command>, <command>DELETE</command>,
4871 or <command>MERGE</command> statement.
4872 If the command that generated the <structname>PGresult</structname> was anything
4873 else, <xref linkend="libpq-PQcmdTuples"/> returns an empty string. The caller
4874 should not free the return value directly. It will be freed when
4875 the associated <structname>PGresult</structname> handle is passed to
4876 <xref linkend="libpq-PQclear"/>.
4877 </para>
4878 </listitem>
4879 </varlistentry>
4880
4881 <varlistentry id="libpq-PQoidValue">
4882 <term><function>PQoidValue</function><indexterm><primary>PQoidValue</primary></indexterm></term>
4883
4884 <listitem>
4885 <para>
4886 Returns the OID<indexterm><primary>OID</primary><secondary>in libpq</secondary></indexterm>
4887 of the inserted row, if the <acronym>SQL</acronym> command was an
4888 <command>INSERT</command> that inserted exactly one row into a table that
4889 has OIDs, or a <command>EXECUTE</command> of a prepared query containing
4890 a suitable <command>INSERT</command> statement. Otherwise, this function
4891 returns <literal>InvalidOid</literal>. This function will also
4892 return <literal>InvalidOid</literal> if the table affected by the
4893 <command>INSERT</command> statement does not contain OIDs.
4894 <synopsis>
4895 Oid PQoidValue(const PGresult *res);
4896 </synopsis>
4897 </para>
4898 </listitem>
4899 </varlistentry>
4900
4901 <varlistentry id="libpq-PQoidStatus">
4902 <term><function>PQoidStatus</function><indexterm><primary>PQoidStatus</primary></indexterm></term>
4903
4904 <listitem>
4905 <para>
4906 This function is deprecated in favor of
4907 <xref linkend="libpq-PQoidValue"/> and is not thread-safe.
4908 It returns a string with the OID of the inserted row, while
4909 <xref linkend="libpq-PQoidValue"/> returns the OID value.
4910 <synopsis>
4911 char *PQoidStatus(const PGresult *res);
4912 </synopsis>
4913 </para>
4914
4915 </listitem>
4916 </varlistentry>
4917 </variablelist>
4918
4919 </sect2>
4920
4921 <sect2 id="libpq-exec-escape-string">
4922 <title>Escaping Strings for Inclusion in SQL Commands</title>
4923
4924 <indexterm zone="libpq-exec-escape-string">
4925 <primary>escaping strings</primary>
4926 <secondary>in libpq</secondary>
4927 </indexterm>
4928
4929 <variablelist>
4930 <varlistentry id="libpq-PQescapeLiteral">
4931 <term><function>PQescapeLiteral</function><indexterm><primary>PQescapeLiteral</primary></indexterm></term>
4932
4933 <listitem>
4934 <para>
4935 <synopsis>
4936 char *PQescapeLiteral(PGconn *conn, const char *str, size_t length);
4937 </synopsis>
4938 </para>
4939
4940 <para>
4941 <xref linkend="libpq-PQescapeLiteral"/> escapes a string for
4942 use within an SQL command. This is useful when inserting data
4943 values as literal constants in SQL commands. Certain characters
4944 (such as quotes and backslashes) must be escaped to prevent them
4945 from being interpreted specially by the SQL parser.
4946 <xref linkend="libpq-PQescapeLiteral"/> performs this operation.
4947 </para>
4948
4949 <para>
4950 <xref linkend="libpq-PQescapeLiteral"/> returns an escaped version of the
4951 <parameter>str</parameter> parameter in memory allocated with
4952 <function>malloc()</function>. This memory should be freed using
4953 <function>PQfreemem()</function> when the result is no longer needed.
4954 A terminating zero byte is not required, and should not be
4955 counted in <parameter>length</parameter>. (If a terminating zero byte is found
4956 before <parameter>length</parameter> bytes are processed,
4957 <xref linkend="libpq-PQescapeLiteral"/> stops at the zero; the behavior is
4958 thus rather like <function>strncpy</function>.) The
4959 return string has all special characters replaced so that they can
4960 be properly processed by the <productname>PostgreSQL</productname>
4961 string literal parser. A terminating zero byte is also added. The
4962 single quotes that must surround <productname>PostgreSQL</productname>
4963 string literals are included in the result string.
4964 </para>
4965
4966 <para>
4967 On error, <xref linkend="libpq-PQescapeLiteral"/> returns <symbol>NULL</symbol> and a suitable
4968 message is stored in the <parameter>conn</parameter> object.
4969 </para>
4970
4971 <tip>
4972 <para>
4973 It is especially important to do proper escaping when handling
4974 strings that were received from an untrustworthy source.
4975 Otherwise there is a security risk: you are vulnerable to
4976 <quote>SQL injection</quote> attacks wherein unwanted SQL commands are
4977 fed to your database.
4978 </para>
4979 </tip>
4980
4981 <para>
4982 Note that it is neither necessary nor correct to do escaping when a data
4983 value is passed as a separate parameter in <xref linkend="libpq-PQexecParams"/> or
4984 its sibling routines.
4985 </para>
4986 </listitem>
4987 </varlistentry>
4988
4989 <varlistentry id="libpq-PQescapeIdentifier">
4990 <term><function>PQescapeIdentifier</function><indexterm><primary>PQescapeIdentifier</primary></indexterm></term>
4991
4992 <listitem>
4993 <para>
4994 <synopsis>
4995 char *PQescapeIdentifier(PGconn *conn, const char *str, size_t length);
4996 </synopsis>
4997 </para>
4998
4999 <para>
5000 <xref linkend="libpq-PQescapeIdentifier"/> escapes a string for
5001 use as an SQL identifier, such as a table, column, or function name.
5002 This is useful when a user-supplied identifier might contain
5003 special characters that would otherwise not be interpreted as part
5004 of the identifier by the SQL parser, or when the identifier might
5005 contain upper case characters whose case should be preserved.
5006 </para>
5007
5008 <para>
5009 <xref linkend="libpq-PQescapeIdentifier"/> returns a version of the
5010 <parameter>str</parameter> parameter escaped as an SQL identifier
5011 in memory allocated with <function>malloc()</function>. This memory must be
5012 freed using <function>PQfreemem()</function> when the result is no longer
5013 needed. A terminating zero byte is not required, and should not be
5014 counted in <parameter>length</parameter>. (If a terminating zero byte is found
5015 before <parameter>length</parameter> bytes are processed,
5016 <xref linkend="libpq-PQescapeIdentifier"/> stops at the zero; the behavior is
5017 thus rather like <function>strncpy</function>.) The
5018 return string has all special characters replaced so that it
5019 will be properly processed as an SQL identifier. A terminating zero byte
5020 is also added. The return string will also be surrounded by double
5021 quotes.
5022 </para>
5023
5024 <para>
5025 On error, <xref linkend="libpq-PQescapeIdentifier"/> returns <symbol>NULL</symbol> and a suitable
5026 message is stored in the <parameter>conn</parameter> object.
5027 </para>
5028
5029 <tip>
5030 <para>
5031 As with string literals, to prevent SQL injection attacks,
5032 SQL identifiers must be escaped when they are received from an
5033 untrustworthy source.
5034 </para>
5035 </tip>
5036 </listitem>
5037 </varlistentry>
5038
5039 <varlistentry id="libpq-PQescapeStringConn">
5040 <term><function>PQescapeStringConn</function><indexterm><primary>PQescapeStringConn</primary></indexterm></term>
5041
5042 <listitem>
5043 <para>
5044 <synopsis>
5045 size_t PQescapeStringConn(PGconn *conn,
5046 char *to, const char *from, size_t length,
5047 int *error);
5048 </synopsis>
5049 </para>
5050
5051 <para>
5052 <xref linkend="libpq-PQescapeStringConn"/> escapes string literals, much like
5053 <xref linkend="libpq-PQescapeLiteral"/>. Unlike <xref linkend="libpq-PQescapeLiteral"/>,
5054 the caller is responsible for providing an appropriately sized buffer.
5055 Furthermore, <xref linkend="libpq-PQescapeStringConn"/> does not generate the
5056 single quotes that must surround <productname>PostgreSQL</productname> string
5057 literals; they should be provided in the SQL command that the
5058 result is inserted into. The parameter <parameter>from</parameter> points to
5059 the first character of the string that is to be escaped, and the
5060 <parameter>length</parameter> parameter gives the number of bytes in this
5061 string. A terminating zero byte is not required, and should not be
5062 counted in <parameter>length</parameter>. (If a terminating zero byte is found
5063 before <parameter>length</parameter> bytes are processed,
5064 <xref linkend="libpq-PQescapeStringConn"/> stops at the zero; the behavior is
5065 thus rather like <function>strncpy</function>.) <parameter>to</parameter> shall point
5066 to a buffer that is able to hold at least one more byte than twice
5067 the value of <parameter>length</parameter>, otherwise the behavior is undefined.
5068 Behavior is likewise undefined if the <parameter>to</parameter> and
5069 <parameter>from</parameter> strings overlap.
5070 </para>
5071
5072 <para>
5073 If the <parameter>error</parameter> parameter is not <symbol>NULL</symbol>, then
5074 <literal>*error</literal> is set to zero on success, nonzero on error.
5075 Presently the only possible error conditions involve invalid multibyte
5076 encoding in the source string. The output string is still generated
5077 on error, but it can be expected that the server will reject it as
5078 malformed. On error, a suitable message is stored in the
5079 <parameter>conn</parameter> object, whether or not <parameter>error</parameter> is <symbol>NULL</symbol>.
5080 </para>
5081
5082 <para>
5083 <xref linkend="libpq-PQescapeStringConn"/> returns the number of bytes written
5084 to <parameter>to</parameter>, not including the terminating zero byte.
5085 </para>
5086 </listitem>
5087 </varlistentry>
5088
5089 <varlistentry id="libpq-PQescapeString">
5090 <term><function>PQescapeString</function><indexterm><primary>PQescapeString</primary></indexterm></term>
5091
5092 <listitem>
5093 <para>
5094 <xref linkend="libpq-PQescapeString"/> is an older, deprecated version of
5095 <xref linkend="libpq-PQescapeStringConn"/>.
5096 <synopsis>
5097 size_t PQescapeString (char *to, const char *from, size_t length);
5098 </synopsis>
5099 </para>
5100
5101 <para>
5102 The only difference from <xref linkend="libpq-PQescapeStringConn"/> is that
5103 <xref linkend="libpq-PQescapeString"/> does not take <structname>PGconn</structname>
5104 or <parameter>error</parameter> parameters.
5105 Because of this, it cannot adjust its behavior depending on the
5106 connection properties (such as character encoding) and therefore
5107 <emphasis>it might give the wrong results</emphasis>. Also, it has no way
5108 to report error conditions.
5109 </para>
5110
5111 <para>
5112 <xref linkend="libpq-PQescapeString"/> can be used safely in
5113 client programs that work with only one <productname>PostgreSQL</productname>
5114 connection at a time (in this case it can find out what it needs to
5115 know <quote>behind the scenes</quote>). In other contexts it is a security
5116 hazard and should be avoided in favor of
5117 <xref linkend="libpq-PQescapeStringConn"/>.
5118 </para>
5119 </listitem>
5120 </varlistentry>
5121
5122 <varlistentry id="libpq-PQescapeByteaConn">
5123 <term><function>PQescapeByteaConn</function><indexterm><primary>PQescapeByteaConn</primary></indexterm></term>
5124
5125 <listitem>
5126 <para>
5127 Escapes binary data for use within an SQL command with the type
5128 <type>bytea</type>. As with <xref linkend="libpq-PQescapeStringConn"/>,
5129 this is only used when inserting data directly into an SQL command string.
5130 <synopsis>
5131 unsigned char *PQescapeByteaConn(PGconn *conn,
5132 const unsigned char *from,
5133 size_t from_length,
5134 size_t *to_length);
5135 </synopsis>
5136 </para>
5137
5138 <para>
5139 Certain byte values must be escaped when used as part of a
5140 <type>bytea</type> literal in an <acronym>SQL</acronym> statement.
5141 <xref linkend="libpq-PQescapeByteaConn"/> escapes bytes using
5142 either hex encoding or backslash escaping. See <xref
5143 linkend="datatype-binary"/> for more information.
5144 </para>
5145
5146 <para>
5147 The <parameter>from</parameter> parameter points to the first
5148 byte of the string that is to be escaped, and the
5149 <parameter>from_length</parameter> parameter gives the number of
5150 bytes in this binary string. (A terminating zero byte is
5151 neither necessary nor counted.) The <parameter>to_length</parameter>
5152 parameter points to a variable that will hold the resultant
5153 escaped string length. This result string length includes the terminating
5154 zero byte of the result.
5155 </para>
5156
5157 <para>
5158 <xref linkend="libpq-PQescapeByteaConn"/> returns an escaped version of the
5159 <parameter>from</parameter> parameter binary string in memory
5160 allocated with <function>malloc()</function>. This memory should be freed using
5161 <function>PQfreemem()</function> when the result is no longer needed. The
5162 return string has all special characters replaced so that they can
5163 be properly processed by the <productname>PostgreSQL</productname>
5164 string literal parser, and the <type>bytea</type> input function. A
5165 terminating zero byte is also added. The single quotes that must
5166 surround <productname>PostgreSQL</productname> string literals are
5167 not part of the result string.
5168 </para>
5169
5170 <para>
5171 On error, a null pointer is returned, and a suitable error message
5172 is stored in the <parameter>conn</parameter> object. Currently, the only
5173 possible error is insufficient memory for the result string.
5174 </para>
5175 </listitem>
5176 </varlistentry>
5177
5178 <varlistentry id="libpq-PQescapeBytea">
5179 <term><function>PQescapeBytea</function><indexterm><primary>PQescapeBytea</primary></indexterm></term>
5180
5181 <listitem>
5182 <para>
5183 <xref linkend="libpq-PQescapeBytea"/> is an older, deprecated version of
5184 <xref linkend="libpq-PQescapeByteaConn"/>.
5185 <synopsis>
5186 unsigned char *PQescapeBytea(const unsigned char *from,
5187 size_t from_length,
5188 size_t *to_length);
5189 </synopsis>
5190 </para>
5191
5192 <para>
5193 The only difference from <xref linkend="libpq-PQescapeByteaConn"/> is that
5194 <xref linkend="libpq-PQescapeBytea"/> does not take a <structname>PGconn</structname>
5195 parameter. Because of this, <xref linkend="libpq-PQescapeBytea"/> can
5196 only be used safely in client programs that use a single
5197 <productname>PostgreSQL</productname> connection at a time (in this case
5198 it can find out what it needs to know <quote>behind the
5199 scenes</quote>). It <emphasis>might give the wrong results</emphasis> if
5200 used in programs that use multiple database connections (use
5201 <xref linkend="libpq-PQescapeByteaConn"/> in such cases).
5202 </para>
5203 </listitem>
5204 </varlistentry>
5205
5206 <varlistentry id="libpq-PQunescapeBytea">
5207 <term><function>PQunescapeBytea</function><indexterm><primary>PQunescapeBytea</primary></indexterm></term>
5208
5209 <listitem>
5210 <para>
5211 Converts a string representation of binary data into binary data
5212 &mdash; the reverse of <xref linkend="libpq-PQescapeBytea"/>. This
5213 is needed when retrieving <type>bytea</type> data in text format,
5214 but not when retrieving it in binary format.
5215
5216 <synopsis>
5217 unsigned char *PQunescapeBytea(const unsigned char *from, size_t *to_length);
5218 </synopsis>
5219 </para>
5220
5221 <para>
5222 The <parameter>from</parameter> parameter points to a string
5223 such as might be returned by <xref linkend="libpq-PQgetvalue"/> when applied
5224 to a <type>bytea</type> column. <xref linkend="libpq-PQunescapeBytea"/>
5225 converts this string representation into its binary representation.
5226 It returns a pointer to a buffer allocated with
5227 <function>malloc()</function>, or <symbol>NULL</symbol> on error, and puts the size of
5228 the buffer in <parameter>to_length</parameter>. The result must be
5229 freed using <xref linkend="libpq-PQfreemem"/> when it is no longer needed.
5230 </para>
5231
5232 <para>
5233 This conversion is not exactly the inverse of
5234 <xref linkend="libpq-PQescapeBytea"/>, because the string is not expected
5235 to be <quote>escaped</quote> when received from <xref linkend="libpq-PQgetvalue"/>.
5236 In particular this means there is no need for string quoting considerations,
5237 and so no need for a <structname>PGconn</structname> parameter.
5238 </para>
5239 </listitem>
5240 </varlistentry>
5241 </variablelist>
5242
5243 </sect2>
5244
5245 </sect1>
5246
5247 <sect1 id="libpq-async">
5248 <title>Asynchronous Command Processing</title>
5249
5250 <indexterm zone="libpq-async">
5251 <primary>nonblocking connection</primary>
5252 </indexterm>
5253
5254 <para>
5255 The <xref linkend="libpq-PQexec"/> function is adequate for submitting
5256 commands in normal, synchronous applications. It has a few
5257 deficiencies, however, that can be of importance to some users:
5258
5259 <itemizedlist>
5260 <listitem>
5261 <para>
5262 <xref linkend="libpq-PQexec"/> waits for the command to be completed.
5263 The application might have other work to do (such as maintaining a
5264 user interface), in which case it won't want to block waiting for
5265 the response.
5266 </para>
5267 </listitem>
5268
5269 <listitem>
5270 <para>
5271 Since the execution of the client application is suspended while it
5272 waits for the result, it is hard for the application to decide that
5273 it would like to try to cancel the ongoing command. (It can be done
5274 from a signal handler, but not otherwise.)
5275 </para>
5276 </listitem>
5277
5278 <listitem>
5279 <para>
5280 <xref linkend="libpq-PQexec"/> can return only one
5281 <structname>PGresult</structname> structure. If the submitted command
5282 string contains multiple <acronym>SQL</acronym> commands, all but
5283 the last <structname>PGresult</structname> are discarded by
5284 <xref linkend="libpq-PQexec"/>.
5285 </para>
5286 </listitem>
5287
5288 <listitem>
5289 <para>
5290 <xref linkend="libpq-PQexec"/> always collects the command's entire result,
5291 buffering it in a single <structname>PGresult</structname>. While
5292 this simplifies error-handling logic for the application, it can be
5293 impractical for results containing many rows.
5294 </para>
5295 </listitem>
5296 </itemizedlist>
5297 </para>
5298
5299 <para>
5300 Applications that do not like these limitations can instead use the
5301 underlying functions that <xref linkend="libpq-PQexec"/> is built from:
5302 <xref linkend="libpq-PQsendQuery"/> and <xref linkend="libpq-PQgetResult"/>.
5303 There are also
5304 <xref linkend="libpq-PQsendQueryParams"/>,
5305 <xref linkend="libpq-PQsendPrepare"/>,
5306 <xref linkend="libpq-PQsendQueryPrepared"/>,
5307 <xref linkend="libpq-PQsendDescribePrepared"/>,
5308 <xref linkend="libpq-PQsendDescribePortal"/>,
5309 <xref linkend="libpq-PQsendClosePrepared"/>, and
5310 <xref linkend="libpq-PQsendClosePortal"/>,
5311 which can be used with <xref linkend="libpq-PQgetResult"/> to duplicate
5312 the functionality of
5313 <xref linkend="libpq-PQexecParams"/>,
5314 <xref linkend="libpq-PQprepare"/>,
5315 <xref linkend="libpq-PQexecPrepared"/>,
5316 <xref linkend="libpq-PQdescribePrepared"/>,
5317 <xref linkend="libpq-PQdescribePortal"/>,
5318 <xref linkend="libpq-PQclosePrepared"/>, and
5319 <xref linkend="libpq-PQclosePortal"/>
5320 respectively.
5321
5322 <variablelist>
5323 <varlistentry id="libpq-PQsendQuery">
5324 <term><function>PQsendQuery</function><indexterm><primary>PQsendQuery</primary></indexterm></term>
5325
5326 <listitem>
5327 <para>
5328 Submits a command to the server without waiting for the result(s).
5329 1 is returned if the command was successfully dispatched and 0 if
5330 not (in which case, use <xref linkend="libpq-PQerrorMessage"/> to get more
5331 information about the failure).
5332 <synopsis>
5333 int PQsendQuery(PGconn *conn, const char *command);
5334 </synopsis>
5335
5336 After successfully calling <xref linkend="libpq-PQsendQuery"/>, call
5337 <xref linkend="libpq-PQgetResult"/> one or more times to obtain the
5338 results. <xref linkend="libpq-PQsendQuery"/> cannot be called again
5339 (on the same connection) until <xref linkend="libpq-PQgetResult"/>
5340 has returned a null pointer, indicating that the command is done.
5341 </para>
5342
5343 <para>
5344 In pipeline mode, this function is disallowed.
5345 </para>
5346 </listitem>
5347 </varlistentry>
5348
5349 <varlistentry id="libpq-PQsendQueryParams">
5350 <term><function>PQsendQueryParams</function><indexterm><primary>PQsendQueryParams</primary></indexterm></term>
5351
5352 <listitem>
5353 <para>
5354 Submits a command and separate parameters to the server without
5355 waiting for the result(s).
5356 <synopsis>
5357 int PQsendQueryParams(PGconn *conn,
5358 const char *command,
5359 int nParams,
5360 const Oid *paramTypes,
5361 const char * const *paramValues,
5362 const int *paramLengths,
5363 const int *paramFormats,
5364 int resultFormat);
5365 </synopsis>
5366
5367 This is equivalent to <xref linkend="libpq-PQsendQuery"/> except that
5368 query parameters can be specified separately from the query string.
5369 The function's parameters are handled identically to
5370 <xref linkend="libpq-PQexecParams"/>. Like
5371 <xref linkend="libpq-PQexecParams"/>, it allows only one command in the
5372 query string.
5373 </para>
5374 </listitem>
5375 </varlistentry>
5376
5377 <varlistentry id="libpq-PQsendPrepare">
5378 <term><function>PQsendPrepare</function><indexterm><primary>PQsendPrepare</primary></indexterm></term>
5379
5380 <listitem>
5381 <para>
5382 Sends a request to create a prepared statement with the given
5383 parameters, without waiting for completion.
5384 <synopsis>
5385 int PQsendPrepare(PGconn *conn,
5386 const char *stmtName,
5387 const char *query,
5388 int nParams,
5389 const Oid *paramTypes);
5390 </synopsis>
5391
5392 This is an asynchronous version of <xref linkend="libpq-PQprepare"/>: it
5393 returns 1 if it was able to dispatch the request, and 0 if not.
5394 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
5395 determine whether the server successfully created the prepared
5396 statement. The function's parameters are handled identically to
5397 <xref linkend="libpq-PQprepare"/>.
5398 </para>
5399 </listitem>
5400 </varlistentry>
5401
5402 <varlistentry id="libpq-PQsendQueryPrepared">
5403 <term><function>PQsendQueryPrepared</function><indexterm><primary>PQsendQueryPrepared</primary></indexterm></term>
5404
5405 <listitem>
5406 <para>
5407 Sends a request to execute a prepared statement with given
5408 parameters, without waiting for the result(s).
5409 <synopsis>
5410 int PQsendQueryPrepared(PGconn *conn,
5411 const char *stmtName,
5412 int nParams,
5413 const char * const *paramValues,
5414 const int *paramLengths,
5415 const int *paramFormats,
5416 int resultFormat);
5417 </synopsis>
5418
5419 This is similar to <xref linkend="libpq-PQsendQueryParams"/>, but
5420 the command to be executed is specified by naming a
5421 previously-prepared statement, instead of giving a query string.
5422 The function's parameters are handled identically to
5423 <xref linkend="libpq-PQexecPrepared"/>.
5424 </para>
5425 </listitem>
5426 </varlistentry>
5427
5428 <varlistentry id="libpq-PQsendDescribePrepared">
5429 <term><function>PQsendDescribePrepared</function><indexterm><primary>PQsendDescribePrepared</primary></indexterm></term>
5430
5431 <listitem>
5432 <para>
5433 Submits a request to obtain information about the specified
5434 prepared statement, without waiting for completion.
5435 <synopsis>
5436 int PQsendDescribePrepared(PGconn *conn, const char *stmtName);
5437 </synopsis>
5438
5439 This is an asynchronous version of <xref linkend="libpq-PQdescribePrepared"/>:
5440 it returns 1 if it was able to dispatch the request, and 0 if not.
5441 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
5442 obtain the results. The function's parameters are handled
5443 identically to <xref linkend="libpq-PQdescribePrepared"/>.
5444 </para>
5445 </listitem>
5446 </varlistentry>
5447
5448 <varlistentry id="libpq-PQsendDescribePortal">
5449 <term><function>PQsendDescribePortal</function><indexterm><primary>PQsendDescribePortal</primary></indexterm></term>
5450
5451 <listitem>
5452 <para>
5453 Submits a request to obtain information about the specified
5454 portal, without waiting for completion.
5455 <synopsis>
5456 int PQsendDescribePortal(PGconn *conn, const char *portalName);
5457 </synopsis>
5458
5459 This is an asynchronous version of <xref linkend="libpq-PQdescribePortal"/>:
5460 it returns 1 if it was able to dispatch the request, and 0 if not.
5461 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
5462 obtain the results. The function's parameters are handled
5463 identically to <xref linkend="libpq-PQdescribePortal"/>.
5464 </para>
5465 </listitem>
5466 </varlistentry>
5467
5468 <varlistentry id="libpq-PQsendClosePrepared">
5469 <term><function>PQsendClosePrepared</function><indexterm><primary>PQsendClosePrepared</primary></indexterm></term>
5470
5471 <listitem>
5472 <para>
5473 Submits a request to close the specified prepared statement, without
5474 waiting for completion.
5475 <synopsis>
5476 int PQsendClosePrepared(PGconn *conn, const char *stmtName);
5477 </synopsis>
5478
5479 This is an asynchronous version of <xref linkend="libpq-PQclosePrepared"/>:
5480 it returns 1 if it was able to dispatch the request, and 0 if not.
5481 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
5482 obtain the results. The function's parameters are handled
5483 identically to <xref linkend="libpq-PQclosePrepared"/>.
5484 </para>
5485 </listitem>
5486 </varlistentry>
5487
5488 <varlistentry id="libpq-PQsendClosePortal">
5489 <term><function>PQsendClosePortal</function><indexterm><primary>PQsendClosePortal</primary></indexterm></term>
5490
5491 <listitem>
5492 <para>
5493 Submits a request to close specified portal, without waiting for
5494 completion.
5495 <synopsis>
5496 int PQsendClosePortal(PGconn *conn, const char *portalName);
5497 </synopsis>
5498
5499 This is an asynchronous version of <xref linkend="libpq-PQclosePortal"/>:
5500 it returns 1 if it was able to dispatch the request, and 0 if not.
5501 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
5502 obtain the results. The function's parameters are handled
5503 identically to <xref linkend="libpq-PQclosePortal"/>.
5504 </para>
5505 </listitem>
5506 </varlistentry>
5507
5508 <varlistentry id="libpq-PQgetResult">
5509 <term><function>PQgetResult</function><indexterm><primary>PQgetResult</primary></indexterm></term>
5510
5511 <listitem>
5512 <para>
5513 Waits for the next result from a prior
5514 <xref linkend="libpq-PQsendQuery"/>,
5515 <xref linkend="libpq-PQsendQueryParams"/>,
5516 <xref linkend="libpq-PQsendPrepare"/>,
5517 <xref linkend="libpq-PQsendQueryPrepared"/>,
5518 <xref linkend="libpq-PQsendDescribePrepared"/>,
5519 <xref linkend="libpq-PQsendDescribePortal"/>,
5520 <xref linkend="libpq-PQsendClosePrepared"/>,
5521 <xref linkend="libpq-PQsendClosePortal"/>,
5522 <xref linkend="libpq-PQsendPipelineSync"/>, or
5523 <xref linkend="libpq-PQpipelineSync"/>
5524 call, and returns it.
5525 A null pointer is returned when the command is complete and there
5526 will be no more results.
5527 <synopsis>
5528 PGresult *PQgetResult(PGconn *conn);
5529 </synopsis>
5530 </para>
5531
5532 <para>
5533 <xref linkend="libpq-PQgetResult"/> must be called repeatedly until
5534 it returns a null pointer, indicating that the command is done.
5535 (If called when no command is active,
5536 <xref linkend="libpq-PQgetResult"/> will just return a null pointer
5537 at once.) Each non-null result from
5538 <xref linkend="libpq-PQgetResult"/> should be processed using the
5539 same <structname>PGresult</structname> accessor functions previously
5540 described. Don't forget to free each result object with
5541 <xref linkend="libpq-PQclear"/> when done with it. Note that
5542 <xref linkend="libpq-PQgetResult"/> will block only if a command is
5543 active and the necessary response data has not yet been read by
5544 <xref linkend="libpq-PQconsumeInput"/>.
5545 </para>
5546
5547 <para>
5548 In pipeline mode, <function>PQgetResult</function> will return normally
5549 unless an error occurs; for any subsequent query sent after the one
5550 that caused the error until (and excluding) the next synchronization point,
5551 a special result of type <literal>PGRES_PIPELINE_ABORTED</literal> will
5552 be returned, and a null pointer will be returned after it.
5553 When the pipeline synchronization point is reached, a result of type
5554 <literal>PGRES_PIPELINE_SYNC</literal> will be returned.
5555 The result of the next query after the synchronization point follows
5556 immediately (that is, no null pointer is returned after
5557 the synchronization point).
5558 </para>
5559
5560 <note>
5561 <para>
5562 Even when <xref linkend="libpq-PQresultStatus"/> indicates a fatal
5563 error, <xref linkend="libpq-PQgetResult"/> should be called until it
5564 returns a null pointer, to allow <application>libpq</application> to
5565 process the error information completely.
5566 </para>
5567 </note>
5568 </listitem>
5569 </varlistentry>
5570 </variablelist>
5571 </para>
5572
5573 <para>
5574 Using <xref linkend="libpq-PQsendQuery"/> and
5575 <xref linkend="libpq-PQgetResult"/> solves one of
5576 <xref linkend="libpq-PQexec"/>'s problems: If a command string contains
5577 multiple <acronym>SQL</acronym> commands, the results of those commands
5578 can be obtained individually. (This allows a simple form of overlapped
5579 processing, by the way: the client can be handling the results of one
5580 command while the server is still working on later queries in the same
5581 command string.)
5582 </para>
5583
5584 <para>
5585 Another frequently-desired feature that can be obtained with
5586 <xref linkend="libpq-PQsendQuery"/> and <xref linkend="libpq-PQgetResult"/>
5587 is retrieving large query results a limited number of rows at a time.
5588 This is discussed
5589 in <xref linkend="libpq-single-row-mode"/>.
5590 </para>
5591
5592 <para>
5593 By itself, calling <xref linkend="libpq-PQgetResult"/>
5594 will still cause the client to block until the server completes the
5595 next <acronym>SQL</acronym> command. This can be avoided by proper
5596 use of two more functions:
5597
5598 <variablelist>
5599 <varlistentry id="libpq-PQconsumeInput">
5600 <term><function>PQconsumeInput</function><indexterm><primary>PQconsumeInput</primary></indexterm>
5601 </term>
5602
5603 <listitem>
5604 <para>
5605 If input is available from the server, consume it.
5606 <synopsis>
5607 int PQconsumeInput(PGconn *conn);
5608 </synopsis>
5609 </para>
5610
5611 <para>
5612 <xref linkend="libpq-PQconsumeInput"/> normally returns 1 indicating
5613 <quote>no error</quote>, but returns 0 if there was some kind of
5614 trouble (in which case <xref linkend="libpq-PQerrorMessage"/> can be
5615 consulted). Note that the result does not say whether any input
5616 data was actually collected. After calling
5617 <xref linkend="libpq-PQconsumeInput"/>, the application can check
5618 <xref linkend="libpq-PQisBusy"/> and/or
5619 <function>PQnotifies</function> to see if their state has changed.
5620 </para>
5621
5622 <para>
5623 <xref linkend="libpq-PQconsumeInput"/> can be called even if the
5624 application is not prepared to deal with a result or notification
5625 just yet. The function will read available data and save it in
5626 a buffer, thereby causing a <function>select()</function>
5627 read-ready indication to go away. The application can thus use
5628 <xref linkend="libpq-PQconsumeInput"/> to clear the
5629 <function>select()</function> condition immediately, and then
5630 examine the results at leisure.
5631 </para>
5632 </listitem>
5633 </varlistentry>
5634
5635 <varlistentry id="libpq-PQisBusy">
5636 <term><function>PQisBusy</function><indexterm><primary>PQisBusy</primary></indexterm></term>
5637
5638 <listitem>
5639 <para>
5640 Returns 1 if a command is busy, that is,
5641 <xref linkend="libpq-PQgetResult"/> would block waiting for input.
5642 A 0 return indicates that <xref linkend="libpq-PQgetResult"/> can be
5643 called with assurance of not blocking.
5644 <synopsis>
5645 int PQisBusy(PGconn *conn);
5646 </synopsis>
5647 </para>
5648
5649 <para>
5650 <xref linkend="libpq-PQisBusy"/> will not itself attempt to read data
5651 from the server; therefore <xref linkend="libpq-PQconsumeInput"/>
5652 must be invoked first, or the busy state will never end.
5653 </para>
5654 </listitem>
5655 </varlistentry>
5656 </variablelist>
5657 </para>
5658
5659 <para>
5660 A typical application using these functions will have a main loop that
5661 uses <function>select()</function> or <function>poll()</function> to wait for
5662 all the conditions that it must respond to. One of the conditions
5663 will be input available from the server, which in terms of
5664 <function>select()</function> means readable data on the file
5665 descriptor identified by <xref linkend="libpq-PQsocket"/>. When the main
5666 loop detects input ready, it should call
5667 <xref linkend="libpq-PQconsumeInput"/> to read the input. It can then
5668 call <xref linkend="libpq-PQisBusy"/>, followed by
5669 <xref linkend="libpq-PQgetResult"/> if <xref linkend="libpq-PQisBusy"/>
5670 returns false (0). It can also call <function>PQnotifies</function>
5671 to detect <command>NOTIFY</command> messages (see <xref
5672 linkend="libpq-notify"/>).
5673 </para>
5674
5675 <para>
5676 A client that uses
5677 <xref linkend="libpq-PQsendQuery"/>/<xref linkend="libpq-PQgetResult"/>
5678 can also attempt to cancel a command that is still being processed
5679 by the server; see <xref linkend="libpq-cancel"/>. But regardless of
5680 the return value of <xref linkend="libpq-PQcancelBlocking"/>, the application
5681 must continue with the normal result-reading sequence using
5682 <xref linkend="libpq-PQgetResult"/>. A successful cancellation will
5683 simply cause the command to terminate sooner than it would have
5684 otherwise.
5685 </para>
5686
5687 <para>
5688 By using the functions described above, it is possible to avoid
5689 blocking while waiting for input from the database server. However,
5690 it is still possible that the application will block waiting to send
5691 output to the server. This is relatively uncommon but can happen if
5692 very long SQL commands or data values are sent. (It is much more
5693 probable if the application sends data via <command>COPY IN</command>,
5694 however.) To prevent this possibility and achieve completely
5695 nonblocking database operation, the following additional functions
5696 can be used.
5697
5698 <variablelist>
5699 <varlistentry id="libpq-PQsetnonblocking">
5700 <term><function>PQsetnonblocking</function><indexterm><primary>PQsetnonblocking</primary></indexterm></term>
5701
5702 <listitem>
5703 <para>
5704 Sets the nonblocking status of the connection.
5705 <synopsis>
5706 int PQsetnonblocking(PGconn *conn, int arg);
5707 </synopsis>
5708 </para>
5709
5710 <para>
5711 Sets the state of the connection to nonblocking if
5712 <parameter>arg</parameter> is 1, or blocking if
5713 <parameter>arg</parameter> is 0. Returns 0 if OK, -1 if error.
5714 </para>
5715
5716 <para>
5717 In the nonblocking state, successful calls to
5718 <xref linkend="libpq-PQsendQuery"/>, <xref linkend="libpq-PQputline"/>,
5719 <xref linkend="libpq-PQputnbytes"/>, <xref linkend="libpq-PQputCopyData"/>,
5720 and <xref linkend="libpq-PQendcopy"/> will not block; their changes
5721 are stored in the local output buffer until they are flushed.
5722 Unsuccessful calls will return an error and must be retried.
5723 </para>
5724
5725 <para>
5726 Note that <xref linkend="libpq-PQexec"/> does not honor nonblocking
5727 mode; if it is called, it will act in blocking fashion anyway.
5728 </para>
5729 </listitem>
5730 </varlistentry>
5731
5732 <varlistentry id="libpq-PQisnonblocking">
5733 <term><function>PQisnonblocking</function><indexterm><primary>PQisnonblocking</primary></indexterm></term>
5734
5735 <listitem>
5736 <para>
5737 Returns the blocking status of the database connection.
5738 <synopsis>
5739 int PQisnonblocking(const PGconn *conn);
5740 </synopsis>
5741 </para>
5742
5743 <para>
5744 Returns 1 if the connection is set to nonblocking mode and 0 if
5745 blocking.
5746 </para>
5747 </listitem>
5748 </varlistentry>
5749
5750 <varlistentry id="libpq-PQflush">
5751 <term><function>PQflush</function><indexterm><primary>PQflush</primary></indexterm></term>
5752
5753 <listitem>
5754 <para>
5755 Attempts to flush any queued output data to the server. Returns
5756 0 if successful (or if the send queue is empty), -1 if it failed
5757 for some reason, or 1 if it was unable to send all the data in
5758 the send queue yet (this case can only occur if the connection
5759 is nonblocking).
5760 <synopsis>
5761 int PQflush(PGconn *conn);
5762 </synopsis>
5763 </para>
5764 </listitem>
5765 </varlistentry>
5766 </variablelist>
5767 </para>
5768
5769 <para>
5770 After sending any command or data on a nonblocking connection, call
5771 <xref linkend="libpq-PQflush"/>. If it returns 1, wait for the socket
5772 to become read- or write-ready. If it becomes write-ready, call
5773 <xref linkend="libpq-PQflush"/> again. If it becomes read-ready, call
5774 <xref linkend="libpq-PQconsumeInput"/>, then call
5775 <xref linkend="libpq-PQflush"/> again. Repeat until
5776 <xref linkend="libpq-PQflush"/> returns 0. (It is necessary to check for
5777 read-ready and drain the input with <xref linkend="libpq-PQconsumeInput"/>,
5778 because the server can block trying to send us data, e.g., NOTICE
5779 messages, and won't read our data until we read its.) Once
5780 <xref linkend="libpq-PQflush"/> returns 0, wait for the socket to be
5781 read-ready and then read the response as described above.
5782 </para>
5783
5784 </sect1>
5785
5786 <sect1 id="libpq-pipeline-mode">
5787 <title>Pipeline Mode</title>
5788
5789 <indexterm zone="libpq-pipeline-mode">
5790 <primary>libpq</primary>
5791 <secondary>pipeline mode</secondary>
5792 </indexterm>
5793
5794 <indexterm zone="libpq-pipeline-mode">
5795 <primary>pipelining</primary>
5796 <secondary>in libpq</secondary>
5797 </indexterm>
5798
5799 <indexterm zone="libpq-pipeline-mode">
5800 <primary>batch mode</primary>
5801 <secondary>in libpq</secondary>
5802 </indexterm>
5803
5804 <para>
5805 <application>libpq</application> pipeline mode allows applications to
5806 send a query without having to read the result of the previously
5807 sent query. Taking advantage of the pipeline mode, a client will wait
5808 less for the server, since multiple queries/results can be
5809 sent/received in a single network transaction.
5810 </para>
5811
5812 <para>
5813 While pipeline mode provides a significant performance boost, writing
5814 clients using the pipeline mode is more complex because it involves
5815 managing a queue of pending queries and finding which result
5816 corresponds to which query in the queue.
5817 </para>
5818
5819 <para>
5820 Pipeline mode also generally consumes more memory on both the client and server,
5821 though careful and aggressive management of the send/receive queue can mitigate
5822 this. This applies whether or not the connection is in blocking or non-blocking
5823 mode.
5824 </para>
5825
5826 <para>
5827 While <application>libpq</application>'s pipeline API was introduced in
5828 <productname>PostgreSQL</productname> 14, it is a client-side feature
5829 which doesn't require special server support and works on any server
5830 that supports the v3 extended query protocol. For more information see
5831 <xref linkend="protocol-flow-pipelining"/>.
5832 </para>
5833
5834 <sect2 id="libpq-pipeline-using">
5835 <title>Using Pipeline Mode</title>
5836
5837 <para>
5838 To issue pipelines, the application must switch the connection
5839 into pipeline mode,
5840 which is done with <xref linkend="libpq-PQenterPipelineMode"/>.
5841 <xref linkend="libpq-PQpipelineStatus"/> can be used
5842 to test whether pipeline mode is active.
5843 In pipeline mode, only <link linkend="libpq-async">asynchronous operations</link>
5844 that utilize the extended query protocol
5845 are permitted, command strings containing multiple SQL commands are
5846 disallowed, and so is <literal>COPY</literal>.
5847 Using synchronous command execution functions
5848 such as <function>PQfn</function>,
5849 <function>PQexec</function>,
5850 <function>PQexecParams</function>,
5851 <function>PQprepare</function>,
5852 <function>PQexecPrepared</function>,
5853 <function>PQdescribePrepared</function>,
5854 <function>PQdescribePortal</function>,
5855 <function>PQclosePrepared</function>,
5856 <function>PQclosePortal</function>,
5857 is an error condition.
5858 <function>PQsendQuery</function> is
5859 also disallowed, because it uses the simple query protocol.
5860 Once all dispatched commands have had their results processed, and
5861 the end pipeline result has been consumed, the application may return
5862 to non-pipelined mode with <xref linkend="libpq-PQexitPipelineMode"/>.
5863 </para>
5864
5865 <note>
5866 <para>
5867 It is best to use pipeline mode with <application>libpq</application> in
5868 <link linkend="libpq-PQsetnonblocking">non-blocking mode</link>. If used
5869 in blocking mode it is possible for a client/server deadlock to occur.
5870 <footnote>
5871 <para>
5872 The client will block trying to send queries to the server, but the
5873 server will block trying to send results to the client from queries
5874 it has already processed. This only occurs when the client sends
5875 enough queries to fill both its output buffer and the server's receive
5876 buffer before it switches to processing input from the server,
5877 but it's hard to predict exactly when that will happen.
5878 </para>
5879 </footnote>
5880 </para>
5881 </note>
5882
5883 <sect3 id="libpq-pipeline-sending">
5884 <title>Issuing Queries</title>
5885
5886 <para>
5887 After entering pipeline mode, the application dispatches requests using
5888 <xref linkend="libpq-PQsendQueryParams"/>
5889 or its prepared-query sibling
5890 <xref linkend="libpq-PQsendQueryPrepared"/>.
5891 These requests are queued on the client-side until flushed to the server;
5892 this occurs when <xref linkend="libpq-PQpipelineSync"/> is used to
5893 establish a synchronization point in the pipeline,
5894 or when <xref linkend="libpq-PQflush"/> is called.
5895 The functions <xref linkend="libpq-PQsendPrepare"/>,
5896 <xref linkend="libpq-PQsendDescribePrepared"/>,
5897 <xref linkend="libpq-PQsendDescribePortal"/>,
5898 <xref linkend="libpq-PQsendClosePrepared"/>, and
5899 <xref linkend="libpq-PQsendClosePortal"/> also work in pipeline mode.
5900 Result processing is described below.
5901 </para>
5902
5903 <para>
5904 The server executes statements, and returns results, in the order the
5905 client sends them. The server will begin executing the commands in the
5906 pipeline immediately, not waiting for the end of the pipeline.
5907 Note that results are buffered on the server side; the server flushes
5908 that buffer when a synchronization point is established with either
5909 <function>PQpipelineSync</function> or
5910 <function>PQsendPipelineSync</function>, or when
5911 <function>PQsendFlushRequest</function> is called.
5912 If any statement encounters an error, the server aborts the current
5913 transaction and does not execute any subsequent command in the queue
5914 until the next synchronization point;
5915 a <literal>PGRES_PIPELINE_ABORTED</literal> result is produced for
5916 each such command.
5917 (This remains true even if the commands in the pipeline would rollback
5918 the transaction.)
5919 Query processing resumes after the synchronization point.
5920 </para>
5921
5922 <para>
5923 It's fine for one operation to depend on the results of a
5924 prior one; for example, one query may define a table that the next
5925 query in the same pipeline uses. Similarly, an application may
5926 create a named prepared statement and execute it with later
5927 statements in the same pipeline.
5928 </para>
5929 </sect3>
5930
5931 <sect3 id="libpq-pipeline-results">
5932 <title>Processing Results</title>
5933
5934 <para>
5935 To process the result of one query in a pipeline, the application calls
5936 <function>PQgetResult</function> repeatedly and handles each result
5937 until <function>PQgetResult</function> returns null.
5938 The result from the next query in the pipeline may then be retrieved using
5939 <function>PQgetResult</function> again and the cycle repeated.
5940 The application handles individual statement results as normal.
5941 When the results of all the queries in the pipeline have been
5942 returned, <function>PQgetResult</function> returns a result
5943 containing the status value <literal>PGRES_PIPELINE_SYNC</literal>
5944 </para>
5945
5946 <para>
5947 The client may choose to defer result processing until the complete
5948 pipeline has been sent, or interleave that with sending further
5949 queries in the pipeline; see <xref linkend="libpq-pipeline-interleave"/>.
5950 </para>
5951
5952 <para>
5953 <function>PQgetResult</function> behaves the same as for normal
5954 asynchronous processing except that it may contain the new
5955 <type>PGresult</type> types <literal>PGRES_PIPELINE_SYNC</literal>
5956 and <literal>PGRES_PIPELINE_ABORTED</literal>.
5957 <literal>PGRES_PIPELINE_SYNC</literal> is reported exactly once for each
5958 <function>PQpipelineSync</function> or
5959 <function>PQsendPipelineSync</function> at the corresponding point
5960 in the pipeline.
5961 <literal>PGRES_PIPELINE_ABORTED</literal> is emitted in place of a normal
5962 query result for the first error and all subsequent results
5963 until the next <literal>PGRES_PIPELINE_SYNC</literal>;
5964 see <xref linkend="libpq-pipeline-errors"/>.
5965 </para>
5966
5967 <para>
5968 <function>PQisBusy</function>, <function>PQconsumeInput</function>, etc
5969 operate as normal when processing pipeline results. In particular,
5970 a call to <function>PQisBusy</function> in the middle of a pipeline
5971 returns 0 if the results for all the queries issued so far have been
5972 consumed.
5973 </para>
5974
5975 <para>
5976 <application>libpq</application> does not provide any information to the
5977 application about the query currently being processed (except that
5978 <function>PQgetResult</function> returns null to indicate that we start
5979 returning the results of next query). The application must keep track
5980 of the order in which it sent queries, to associate them with their
5981 corresponding results.
5982 Applications will typically use a state machine or a FIFO queue for this.
5983 </para>
5984
5985 </sect3>
5986
5987 <sect3 id="libpq-pipeline-errors">
5988 <title>Error Handling</title>
5989
5990 <para>
5991 From the client's perspective, after <function>PQresultStatus</function>
5992 returns <literal>PGRES_FATAL_ERROR</literal>,
5993 the pipeline is flagged as aborted.
5994 <function>PQresultStatus</function> will report a
5995 <literal>PGRES_PIPELINE_ABORTED</literal> result for each remaining queued
5996 operation in an aborted pipeline. The result for
5997 <function>PQpipelineSync</function> or
5998 <function>PQsendPipelineSync</function> is reported as
5999 <literal>PGRES_PIPELINE_SYNC</literal> to signal the end of the aborted pipeline
6000 and resumption of normal result processing.
6001 </para>
6002
6003 <para>
6004 The client <emphasis>must</emphasis> process results with
6005 <function>PQgetResult</function> during error recovery.
6006 </para>
6007
6008 <para>
6009 If the pipeline used an implicit transaction, then operations that have
6010 already executed are rolled back and operations that were queued to follow
6011 the failed operation are skipped entirely. The same behavior holds if the
6012 pipeline starts and commits a single explicit transaction (i.e. the first
6013 statement is <literal>BEGIN</literal> and the last is
6014 <literal>COMMIT</literal>) except that the session remains in an aborted
6015 transaction state at the end of the pipeline. If a pipeline contains
6016 <emphasis>multiple explicit transactions</emphasis>, all transactions that
6017 committed prior to the error remain committed, the currently in-progress
6018 transaction is aborted, and all subsequent operations are skipped completely,
6019 including subsequent transactions. If a pipeline synchronization point
6020 occurs with an explicit transaction block in aborted state, the next pipeline
6021 will become aborted immediately unless the next command puts the transaction
6022 in normal mode with <command>ROLLBACK</command>.
6023 </para>
6024
6025 <note>
6026 <para>
6027 The client must not assume that work is committed when it
6028 <emphasis>sends</emphasis> a <literal>COMMIT</literal> &mdash; only when the
6029 corresponding result is received to confirm the commit is complete.
6030 Because errors arrive asynchronously, the application needs to be able to
6031 restart from the last <emphasis>received</emphasis> committed change and
6032 resend work done after that point if something goes wrong.
6033 </para>
6034 </note>
6035 </sect3>
6036
6037 <sect3 id="libpq-pipeline-interleave">
6038 <title>Interleaving Result Processing and Query Dispatch</title>
6039
6040 <para>
6041 To avoid deadlocks on large pipelines the client should be structured
6042 around a non-blocking event loop using operating system facilities
6043 such as <function>select</function>, <function>poll</function>,
6044 <function>WaitForMultipleObjectEx</function>, etc.
6045 </para>
6046
6047 <para>
6048 The client application should generally maintain a queue of work
6049 remaining to be dispatched and a queue of work that has been dispatched
6050 but not yet had its results processed. When the socket is writable
6051 it should dispatch more work. When the socket is readable it should
6052 read results and process them, matching them up to the next entry in
6053 its corresponding results queue. Based on available memory, results from the
6054 socket should be read frequently: there's no need to wait until the
6055 pipeline end to read the results. Pipelines should be scoped to logical
6056 units of work, usually (but not necessarily) one transaction per pipeline.
6057 There's no need to exit pipeline mode and re-enter it between pipelines,
6058 or to wait for one pipeline to finish before sending the next.
6059 </para>
6060
6061 <para>
6062 An example using <function>select()</function> and a simple state
6063 machine to track sent and received work is in
6064 <filename>src/test/modules/libpq_pipeline/libpq_pipeline.c</filename>
6065 in the PostgreSQL source distribution.
6066 </para>
6067 </sect3>
6068 </sect2>
6069
6070 <sect2 id="libpq-pipeline-functions">
6071 <title>Functions Associated with Pipeline Mode</title>
6072
6073 <variablelist>
6074
6075 <varlistentry id="libpq-PQpipelineStatus">
6076 <term><function>PQpipelineStatus</function><indexterm><primary>PQpipelineStatus</primary></indexterm></term>
6077
6078 <listitem>
6079 <para>
6080 Returns the current pipeline mode status of the
6081 <application>libpq</application> connection.
6082 <synopsis>
6083 PGpipelineStatus PQpipelineStatus(const PGconn *conn);
6084 </synopsis>
6085 </para>
6086
6087 <para>
6088 <function>PQpipelineStatus</function> can return one of the following values:
6089
6090 <variablelist>
6091 <varlistentry>
6092 <term>
6093 <literal>PQ_PIPELINE_ON</literal>
6094 </term>
6095 <listitem>
6096 <para>
6097 The <application>libpq</application> connection is in
6098 pipeline mode.
6099 </para>
6100 </listitem>
6101 </varlistentry>
6102
6103 <varlistentry>
6104 <term>
6105 <literal>PQ_PIPELINE_OFF</literal>
6106 </term>
6107 <listitem>
6108 <para>
6109 The <application>libpq</application> connection is
6110 <emphasis>not</emphasis> in pipeline mode.
6111 </para>
6112 </listitem>
6113 </varlistentry>
6114
6115 <varlistentry>
6116 <term>
6117 <literal>PQ_PIPELINE_ABORTED</literal>
6118 </term>
6119 <listitem>
6120 <para>
6121 The <application>libpq</application> connection is in pipeline
6122 mode and an error occurred while processing the current pipeline.
6123 The aborted flag is cleared when <function>PQgetResult</function>
6124 returns a result of type <literal>PGRES_PIPELINE_SYNC</literal>.
6125 </para>
6126 </listitem>
6127 </varlistentry>
6128
6129 </variablelist>
6130 </para>
6131 </listitem>
6132 </varlistentry>
6133
6134 <varlistentry id="libpq-PQenterPipelineMode">
6135 <term><function>PQenterPipelineMode</function><indexterm><primary>PQenterPipelineMode</primary></indexterm></term>
6136
6137 <listitem>
6138 <para>
6139 Causes a connection to enter pipeline mode if it is currently idle or
6140 already in pipeline mode.
6141
6142 <synopsis>
6143 int PQenterPipelineMode(PGconn *conn);
6144 </synopsis>
6145
6146 </para>
6147 <para>
6148 Returns 1 for success.
6149 Returns 0 and has no effect if the connection is not currently
6150 idle, i.e., it has a result ready, or it is waiting for more
6151 input from the server, etc.
6152 This function does not actually send anything to the server,
6153 it just changes the <application>libpq</application> connection
6154 state.
6155 </para>
6156 </listitem>
6157 </varlistentry>
6158
6159 <varlistentry id="libpq-PQexitPipelineMode">
6160 <term><function>PQexitPipelineMode</function><indexterm><primary>PQexitPipelineMode</primary></indexterm></term>
6161
6162 <listitem>
6163 <para>
6164 Causes a connection to exit pipeline mode if it is currently in pipeline mode
6165 with an empty queue and no pending results.
6166 <synopsis>
6167 int PQexitPipelineMode(PGconn *conn);
6168 </synopsis>
6169 </para>
6170 <para>
6171 Returns 1 for success. Returns 1 and takes no action if not in
6172 pipeline mode. If the current statement isn't finished processing,
6173 or <function>PQgetResult</function> has not been called to collect
6174 results from all previously sent query, returns 0 (in which case,
6175 use <xref linkend="libpq-PQerrorMessage"/> to get more information
6176 about the failure).
6177 </para>
6178 </listitem>
6179 </varlistentry>
6180
6181 <varlistentry id="libpq-PQpipelineSync">
6182 <term><function>PQpipelineSync</function><indexterm><primary>PQpipelineSync</primary></indexterm></term>
6183
6184 <listitem>
6185 <para>
6186 Marks a synchronization point in a pipeline by sending a
6187 <link linkend="protocol-flow-ext-query">sync message</link>
6188 and flushing the send buffer. This serves as
6189 the delimiter of an implicit transaction and an error recovery
6190 point; see <xref linkend="libpq-pipeline-errors"/>.
6191
6192 <synopsis>
6193 int PQpipelineSync(PGconn *conn);
6194 </synopsis>
6195 </para>
6196 <para>
6197 Returns 1 for success. Returns 0 if the connection is not in
6198 pipeline mode or sending a
6199 <link linkend="protocol-flow-ext-query">sync message</link>
6200 failed.
6201 </para>
6202 </listitem>
6203 </varlistentry>
6204
6205 <varlistentry id="libpq-PQsendPipelineSync">
6206 <term><function>PQsendPipelineSync</function><indexterm><primary>PQsendPipelineSync</primary></indexterm></term>
6207
6208 <listitem>
6209 <para>
6210 Marks a synchronization point in a pipeline by sending a
6211 <link linkend="protocol-flow-ext-query">sync message</link>
6212 without flushing the send buffer. This serves as
6213 the delimiter of an implicit transaction and an error recovery
6214 point; see <xref linkend="libpq-pipeline-errors"/>.
6215
6216 <synopsis>
6217 int PQsendPipelineSync(PGconn *conn);
6218 </synopsis>
6219 </para>
6220 <para>
6221 Returns 1 for success. Returns 0 if the connection is not in
6222 pipeline mode or sending a
6223 <link linkend="protocol-flow-ext-query">sync message</link>
6224 failed.
6225 Note that the message is not itself flushed to the server automatically;
6226 use <function>PQflush</function> if necessary.
6227 </para>
6228 </listitem>
6229 </varlistentry>
6230
6231 <varlistentry id="libpq-PQsendFlushRequest">
6232 <term><function>PQsendFlushRequest</function><indexterm><primary>PQsendFlushRequest</primary></indexterm></term>
6233
6234 <listitem>
6235 <para>
6236 Sends a request for the server to flush its output buffer.
6237 <synopsis>
6238 int PQsendFlushRequest(PGconn *conn);
6239 </synopsis>
6240 </para>
6241
6242 <para>
6243 Returns 1 for success. Returns 0 on any failure.
6244 </para>
6245 <para>
6246 The server flushes its output buffer automatically as a result of
6247 <function>PQpipelineSync</function> being called, or
6248 on any request when not in pipeline mode; this function is useful
6249 to cause the server to flush its output buffer in pipeline mode
6250 without establishing a synchronization point.
6251 Note that the request is not itself flushed to the server automatically;
6252 use <function>PQflush</function> if necessary.
6253 </para>
6254 </listitem>
6255 </varlistentry>
6256 </variablelist>
6257 </sect2>
6258
6259 <sect2 id="libpq-pipeline-tips">
6260 <title>When to Use Pipeline Mode</title>
6261
6262 <para>
6263 Much like asynchronous query mode, there is no meaningful performance
6264 overhead when using pipeline mode. It increases client application complexity,
6265 and extra caution is required to prevent client/server deadlocks, but
6266 pipeline mode can offer considerable performance improvements, in exchange for
6267 increased memory usage from leaving state around longer.
6268 </para>
6269
6270 <para>
6271 Pipeline mode is most useful when the server is distant, i.e., network latency
6272 (<quote>ping time</quote>) is high, and also when many small operations
6273 are being performed in rapid succession. There is usually less benefit
6274 in using pipelined commands when each query takes many multiples of the client/server
6275 round-trip time to execute. A 100-statement operation run on a server
6276 300 ms round-trip-time away would take 30 seconds in network latency alone
6277 without pipelining; with pipelining it may spend as little as 0.3 s waiting for
6278 results from the server.
6279 </para>
6280
6281 <para>
6282 Use pipelined commands when your application does lots of small
6283 <literal>INSERT</literal>, <literal>UPDATE</literal> and
6284 <literal>DELETE</literal> operations that can't easily be transformed
6285 into operations on sets, or into a <literal>COPY</literal> operation.
6286 </para>
6287
6288 <para>
6289 Pipeline mode is not useful when information from one operation is required by
6290 the client to produce the next operation. In such cases, the client
6291 would have to introduce a synchronization point and wait for a full client/server
6292 round-trip to get the results it needs. However, it's often possible to
6293 adjust the client design to exchange the required information server-side.
6294 Read-modify-write cycles are especially good candidates; for example:
6295 <programlisting>
6296 BEGIN;
6297 SELECT x FROM mytable WHERE id = 42 FOR UPDATE;
6298 -- result: x=2
6299 -- client adds 1 to x:
6300 UPDATE mytable SET x = 3 WHERE id = 42;
6301 COMMIT;
6302 </programlisting>
6303 could be much more efficiently done with:
6304 <programlisting>
6305 UPDATE mytable SET x = x + 1 WHERE id = 42;
6306 </programlisting>
6307 </para>
6308
6309 <para>
6310 Pipelining is less useful, and more complex, when a single pipeline contains
6311 multiple transactions (see <xref linkend="libpq-pipeline-errors"/>).
6312 </para>
6313 </sect2>
6314 </sect1>
6315
6316 <!-- keep this not-too-apropos sect1 ID for stability of doc URLs -->
6317 <sect1 id="libpq-single-row-mode">
6318 <title>Retrieving Query Results in Chunks</title>
6319
6320 <indexterm zone="libpq-single-row-mode">
6321 <primary>libpq</primary>
6322 <secondary>single-row mode</secondary>
6323 </indexterm>
6324
6325 <indexterm zone="libpq-single-row-mode">
6326 <primary>libpq</primary>
6327 <secondary>chunked mode</secondary>
6328 </indexterm>
6329
6330 <para>
6331 Ordinarily, <application>libpq</application> collects an SQL command's
6332 entire result and returns it to the application as a single
6333 <structname>PGresult</structname>. This can be unworkable for commands
6334 that return a large number of rows. For such cases, applications can use
6335 <xref linkend="libpq-PQsendQuery"/> and <xref linkend="libpq-PQgetResult"/> in
6336 <firstterm>single-row mode</firstterm> or <firstterm>chunked
6337 mode</firstterm>. In these modes, result row(s) are returned to the
6338 application as they are received from the server, one at a time for
6339 single-row mode or in groups for chunked mode.
6340 </para>
6341
6342 <para>
6343 To enter one of these modes, call <xref linkend="libpq-PQsetSingleRowMode"/>
6344 or <xref linkend="libpq-PQsetChunkedRowsMode"/>
6345 immediately after a successful call of <xref linkend="libpq-PQsendQuery"/>
6346 (or a sibling function). This mode selection is effective only for the
6347 currently executing query. Then call <xref linkend="libpq-PQgetResult"/>
6348 repeatedly, until it returns null, as documented in <xref
6349 linkend="libpq-async"/>. If the query returns any rows, they are returned
6350 as one or more <structname>PGresult</structname> objects, which look like
6351 normal query results except for having status code
6352 <literal>PGRES_SINGLE_TUPLE</literal> for single-row mode or
6353 <literal>PGRES_TUPLES_CHUNK</literal> for chunked mode, instead of
6354 <literal>PGRES_TUPLES_OK</literal>. There is exactly one result row in
6355 each <literal>PGRES_SINGLE_TUPLE</literal> object, while
6356 a <literal>PGRES_TUPLES_CHUNK</literal> object contains at least one
6357 row but not more than the specified number of rows per chunk.
6358 After the last row, or immediately if
6359 the query returns zero rows, a zero-row object with status
6360 <literal>PGRES_TUPLES_OK</literal> is returned; this is the signal that no
6361 more rows will arrive. (But note that it is still necessary to continue
6362 calling <xref linkend="libpq-PQgetResult"/> until it returns null.) All of
6363 these <structname>PGresult</structname> objects will contain the same row
6364 description data (column names, types, etc.) that an ordinary
6365 <structname>PGresult</structname> object for the query would have.
6366 Each object should be freed with <xref linkend="libpq-PQclear"/> as usual.
6367 </para>
6368
6369 <para>
6370 When using pipeline mode, single-row or chunked mode needs to be
6371 activated for each query in the pipeline before retrieving results for
6372 that query with <function>PQgetResult</function>.
6373 See <xref linkend="libpq-pipeline-mode"/> for more information.
6374 </para>
6375
6376 <para>
6377 <variablelist>
6378 <varlistentry id="libpq-PQsetSingleRowMode">
6379 <term><function>PQsetSingleRowMode</function><indexterm><primary>PQsetSingleRowMode</primary></indexterm></term>
6380
6381 <listitem>
6382 <para>
6383 Select single-row mode for the currently-executing query.
6384
6385 <synopsis>
6386 int PQsetSingleRowMode(PGconn *conn);
6387 </synopsis>
6388 </para>
6389
6390 <para>
6391 This function can only be called immediately after
6392 <xref linkend="libpq-PQsendQuery"/> or one of its sibling functions,
6393 before any other operation on the connection such as
6394 <xref linkend="libpq-PQconsumeInput"/> or
6395 <xref linkend="libpq-PQgetResult"/>. If called at the correct time,
6396 the function activates single-row mode for the current query and
6397 returns 1. Otherwise the mode stays unchanged and the function
6398 returns 0. In any case, the mode reverts to normal after
6399 completion of the current query.
6400 </para>
6401 </listitem>
6402 </varlistentry>
6403
6404 <varlistentry id="libpq-PQsetChunkedRowsMode">
6405 <term><function>PQsetChunkedRowsMode</function><indexterm><primary>PQsetChunkedRowsMode</primary></indexterm></term>
6406
6407 <listitem>
6408 <para>
6409 Select chunked mode for the currently-executing query.
6410
6411 <synopsis>
6412 int PQsetChunkedRowsMode(PGconn *conn, int chunkSize);
6413 </synopsis>
6414 </para>
6415
6416 <para>
6417 This function is similar to
6418 <xref linkend="libpq-PQsetSingleRowMode"/>, except that it
6419 specifies retrieval of up to <replaceable>chunkSize</replaceable> rows
6420 per <structname>PGresult</structname>, not necessarily just one row.
6421 This function can only be called immediately after
6422 <xref linkend="libpq-PQsendQuery"/> or one of its sibling functions,
6423 before any other operation on the connection such as
6424 <xref linkend="libpq-PQconsumeInput"/> or
6425 <xref linkend="libpq-PQgetResult"/>. If called at the correct time,
6426 the function activates chunked mode for the current query and
6427 returns 1. Otherwise the mode stays unchanged and the function
6428 returns 0. In any case, the mode reverts to normal after
6429 completion of the current query.
6430 </para>
6431 </listitem>
6432 </varlistentry>
6433 </variablelist>
6434 </para>
6435
6436 <caution>
6437 <para>
6438 While processing a query, the server may return some rows and then
6439 encounter an error, causing the query to be aborted. Ordinarily,
6440 <application>libpq</application> discards any such rows and reports only the
6441 error. But in single-row or chunked mode, some rows may have already
6442 been returned to the application. Hence, the application will see some
6443 <literal>PGRES_SINGLE_TUPLE</literal> or <literal>PGRES_TUPLES_CHUNK</literal>
6444 <structname>PGresult</structname>
6445 objects followed by a <literal>PGRES_FATAL_ERROR</literal> object. For
6446 proper transactional behavior, the application must be designed to
6447 discard or undo whatever has been done with the previously-processed
6448 rows, if the query ultimately fails.
6449 </para>
6450 </caution>
6451
6452 </sect1>
6453
6454 <sect1 id="libpq-cancel">
6455 <title>Canceling Queries in Progress</title>
6456
6457 <indexterm zone="libpq-cancel">
6458 <primary>canceling SQL queries</primary>
6459 </indexterm>
6460 <indexterm zone="libpq-cancel">
6461 <primary>query cancellation</primary>
6462 </indexterm>
6463
6464 <sect2 id="libpq-cancel-functions">
6465 <title>Functions for Sending Cancel Requests</title>
6466 <variablelist>
6467 <varlistentry id="libpq-PQcancelCreate">
6468 <term><function>PQcancelCreate</function><indexterm><primary>PQcancelCreate</primary></indexterm></term>
6469
6470 <listitem>
6471 <para>
6472 Prepares a connection over which a cancel request can be sent.
6473 <synopsis>
6474 PGcancelConn *PQcancelCreate(PGconn *conn);
6475 </synopsis>
6476 </para>
6477
6478 <para>
6479 <xref linkend="libpq-PQcancelCreate"/> creates a
6480 <structname>PGcancelConn</structname><indexterm><primary>PGcancelConn</primary></indexterm>
6481 object, but it won't instantly start sending a cancel request over this
6482 connection. A cancel request can be sent over this connection in a
6483 blocking manner using <xref linkend="libpq-PQcancelBlocking"/> and in a
6484 non-blocking manner using <xref linkend="libpq-PQcancelStart"/>.
6485 The return value can be passed to <xref linkend="libpq-PQcancelStatus"/>
6486 to check if the <structname>PGcancelConn</structname> object was
6487 created successfully. The <structname>PGcancelConn</structname> object
6488 is an opaque structure that is not meant to be accessed directly by the
6489 application. This <structname>PGcancelConn</structname> object can be
6490 used to cancel the query that's running on the original connection in a
6491 thread-safe way.
6492 </para>
6493
6494 <para>
6495 Many connection parameters of the original client will be reused when
6496 setting up the connection for the cancel request. Importantly, if the
6497 original connection requires encryption of the connection and/or
6498 verification of the target host (using <literal>sslmode</literal> or
6499 <literal>gssencmode</literal>), then the connection for the cancel
6500 request is made with these same requirements. Any connection options
6501 that are only used during authentication or after authentication of the
6502 client are ignored though, because cancellation requests do not require
6503 authentication and the connection is closed right after the cancellation
6504 request is submitted.
6505 </para>
6506
6507 <para>
6508 Note that when <function>PQcancelCreate</function> returns a non-null
6509 pointer, you must call <xref linkend="libpq-PQcancelFinish"/> when you
6510 are finished with it, in order to dispose of the structure and any
6511 associated memory blocks. This must be done even if the cancel request
6512 failed or was abandoned.
6513 </para>
6514 </listitem>
6515 </varlistentry>
6516
6517 <varlistentry id="libpq-PQcancelBlocking">
6518 <term><function>PQcancelBlocking</function><indexterm><primary>PQcancelBlocking</primary></indexterm></term>
6519
6520 <listitem>
6521 <para>
6522 Requests that the server abandons processing of the current command
6523 in a blocking manner.
6524 <synopsis>
6525 int PQcancelBlocking(PGcancelConn *cancelConn);
6526 </synopsis>
6527 </para>
6528
6529 <para>
6530 The request is made over the given <structname>PGcancelConn</structname>,
6531 which needs to be created with <xref linkend="libpq-PQcancelCreate"/>.
6532 The return value of <xref linkend="libpq-PQcancelBlocking"/>
6533 is 1 if the cancel request was successfully
6534 dispatched and 0 if not. If it was unsuccessful, the error message can be
6535 retrieved using <xref linkend="libpq-PQcancelErrorMessage"/>.
6536 </para>
6537
6538 <para>
6539 Successful dispatch of the cancellation is no guarantee that the request
6540 will have any effect, however. If the cancellation is effective, the
6541 command being canceled will terminate early and return an error result.
6542 If the cancellation fails (say, because the server was already done
6543 processing the command), then there will be no visible result at all.
6544 </para>
6545
6546 </listitem>
6547 </varlistentry>
6548
6549 <varlistentry id="libpq-PQcancelStart">
6550 <term><function>PQcancelStart</function><indexterm><primary>PQcancelStart</primary></indexterm></term>
6551 <term><function>PQcancelPoll</function><indexterm><primary>PQcancelPoll</primary></indexterm></term>
6552
6553 <listitem>
6554 <para>
6555 Requests that the server abandons processing of the current command
6556 in a non-blocking manner.
6557 <synopsis>
6558 int PQcancelStart(PGcancelConn *cancelConn);
6559
6560 PostgresPollingStatusType PQcancelPoll(PGcancelConn *cancelConn);
6561 </synopsis>
6562 </para>
6563
6564 <para>
6565 The request is made over the given <structname>PGcancelConn</structname>,
6566 which needs to be created with <xref linkend="libpq-PQcancelCreate"/>.
6567 The return value of <xref linkend="libpq-PQcancelStart"/>
6568 is 1 if the cancellation request could be started and 0 if not.
6569 If it was unsuccessful, the error message can be
6570 retrieved using <xref linkend="libpq-PQcancelErrorMessage"/>.
6571 </para>
6572
6573 <para>
6574 If <function>PQcancelStart</function> succeeds, the next stage
6575 is to poll <application>libpq</application> so that it can proceed with
6576 the cancel connection sequence.
6577 Use <xref linkend="libpq-PQcancelSocket"/> to obtain the descriptor of the
6578 socket underlying the database connection.
6579 (Caution: do not assume that the socket remains the same
6580 across <function>PQcancelPoll</function> calls.)
6581 Loop thus: If <function>PQcancelPoll(cancelConn)</function> last returned
6582 <symbol>PGRES_POLLING_READING</symbol>, wait until the socket is ready to
6583 read (as indicated by <function>select()</function>,
6584 <function>poll()</function>, or similar system function).
6585 Then call <function>PQcancelPoll(cancelConn)</function> again.
6586 Conversely, if <function>PQcancelPoll(cancelConn)</function> last returned
6587 <symbol>PGRES_POLLING_WRITING</symbol>, wait until the socket is ready
6588 to write, then call <function>PQcancelPoll(cancelConn)</function> again.
6589 On the first iteration, i.e., if you have yet to call
6590 <function>PQcancelPoll(cancelConn)</function>, behave as if it last returned
6591 <symbol>PGRES_POLLING_WRITING</symbol>. Continue this loop until
6592 <function>PQcancelPoll(cancelConn)</function> returns
6593 <symbol>PGRES_POLLING_FAILED</symbol>, indicating the connection procedure
6594 has failed, or <symbol>PGRES_POLLING_OK</symbol>, indicating cancel
6595 request was successfully dispatched.
6596 </para>
6597
6598 <para>
6599 Successful dispatch of the cancellation is no guarantee that the request
6600 will have any effect, however. If the cancellation is effective, the
6601 command being canceled will terminate early and return an error result.
6602 If the cancellation fails (say, because the server was already done
6603 processing the command), then there will be no visible result at all.
6604 </para>
6605
6606 <para>
6607 At any time during connection, the status of the connection can be
6608 checked by calling <xref linkend="libpq-PQcancelStatus"/>.
6609 If this call returns <symbol>CONNECTION_BAD</symbol>, then
6610 the cancel procedure has failed; if the call returns
6611 <symbol>CONNECTION_OK</symbol>, then cancel request was
6612 successfully dispatched.
6613 Both of these states are equally detectable from the return value of
6614 <function>PQcancelPoll</function>, described above.
6615 Other states might also occur during (and only during) an asynchronous
6616 connection procedure.
6617 These indicate the current stage of the connection procedure and might
6618 be useful to provide feedback to the user for example.
6619 These statuses are:
6620
6621 <variablelist>
6622 <varlistentry id="libpq-cancel-connection-allocated">
6623 <term><symbol>CONNECTION_ALLOCATED</symbol></term>
6624 <listitem>
6625 <para>
6626 Waiting for a call to <xref linkend="libpq-PQcancelStart"/> or
6627 <xref linkend="libpq-PQcancelBlocking"/>, to actually open the
6628 socket. This is the connection state right after
6629 calling <xref linkend="libpq-PQcancelCreate"/>
6630 or <xref linkend="libpq-PQcancelReset"/>. No connection to the
6631 server has been initiated yet at this point. To actually start
6632 sending the cancel request use <xref linkend="libpq-PQcancelStart"/> or
6633 <xref linkend="libpq-PQcancelBlocking"/>.
6634 </para>
6635 </listitem>
6636 </varlistentry>
6637
6638 <varlistentry id="libpq-cancel-connection-started">
6639 <term><symbol>CONNECTION_STARTED</symbol></term>
6640 <listitem>
6641 <para>
6642 Waiting for connection to be made.
6643 </para>
6644 </listitem>
6645 </varlistentry>
6646
6647 <varlistentry id="libpq-cancel-connection-made">
6648 <term><symbol>CONNECTION_MADE</symbol></term>
6649 <listitem>
6650 <para>
6651 Connection OK; waiting to send.
6652 </para>
6653 </listitem>
6654 </varlistentry>
6655
6656 <varlistentry id="libpq-cancel-connection-awaiting-response">
6657 <term><symbol>CONNECTION_AWAITING_RESPONSE</symbol></term>
6658 <listitem>
6659 <para>
6660 Waiting for a response from the server.
6661 </para>
6662 </listitem>
6663 </varlistentry>
6664
6665 <varlistentry id="libpq-cancel-connection-ssl-startup">
6666 <term><symbol>CONNECTION_SSL_STARTUP</symbol></term>
6667 <listitem>
6668 <para>
6669 Negotiating SSL encryption.
6670 </para>
6671 </listitem>
6672 </varlistentry>
6673
6674 <varlistentry id="libpq-cancel-connection-gss-startup">
6675 <term><symbol>CONNECTION_GSS_STARTUP</symbol></term>
6676 <listitem>
6677 <para>
6678 Negotiating GSS encryption.
6679 </para>
6680 </listitem>
6681 </varlistentry>
6682 </variablelist>
6683
6684 Note that, although these constants will remain (in order to maintain
6685 compatibility), an application should never rely upon these occurring in a
6686 particular order, or at all, or on the status always being one of these
6687 documented values. An application might do something like this:
6688 <programlisting>
6689 switch(PQcancelStatus(conn))
6690 {
6691 case CONNECTION_STARTED:
6692 feedback = "Connecting...";
6693 break;
6694
6695 case CONNECTION_MADE:
6696 feedback = "Connected to server...";
6697 break;
6698 .
6699 .
6700 .
6701 default:
6702 feedback = "Connecting...";
6703 }
6704 </programlisting>
6705 </para>
6706
6707 <para>
6708 The <literal>connect_timeout</literal> connection parameter is ignored
6709 when using <function>PQcancelPoll</function>; it is the application's
6710 responsibility to decide whether an excessive amount of time has elapsed.
6711 Otherwise, <function>PQcancelStart</function> followed by a
6712 <function>PQcancelPoll</function> loop is equivalent to
6713 <xref linkend="libpq-PQcancelBlocking"/>.
6714 </para>
6715
6716 </listitem>
6717 </varlistentry>
6718
6719 <varlistentry id="libpq-PQcancelStatus">
6720 <term><function>PQcancelStatus</function><indexterm><primary>PQcancelStatus</primary></indexterm></term>
6721
6722 <listitem>
6723 <para>
6724 Returns the status of the cancel connection.
6725 <synopsis>
6726 ConnStatusType PQcancelStatus(const PGcancelConn *cancelConn);
6727 </synopsis>
6728 </para>
6729
6730 <para>
6731 The status can be one of a number of values. However, only three of
6732 these are seen outside of an asynchronous cancel procedure:
6733 <symbol>CONNECTION_ALLOCATED</symbol>,
6734 <symbol>CONNECTION_OK</symbol> and
6735 <symbol>CONNECTION_BAD</symbol>. The initial state of a
6736 <function>PGcancelConn</function> that's successfully created using
6737 <xref linkend="libpq-PQcancelCreate"/> is <symbol>CONNECTION_ALLOCATED</symbol>.
6738 A cancel request that was successfully dispatched
6739 has the status <symbol>CONNECTION_OK</symbol>. A failed
6740 cancel attempt is signaled by status
6741 <symbol>CONNECTION_BAD</symbol>. An OK status will
6742 remain so until <xref linkend="libpq-PQcancelFinish"/> or
6743 <xref linkend="libpq-PQcancelReset"/> is called.
6744 </para>
6745
6746 <para>
6747 See the entry for <xref linkend="libpq-PQcancelStart"/> with regards
6748 to other status codes that might be returned.
6749 </para>
6750
6751 <para>
6752 Successful dispatch of the cancellation is no guarantee that the request
6753 will have any effect, however. If the cancellation is effective, the
6754 command being canceled will terminate early and return an error result.
6755 If the cancellation fails (say, because the server was already done
6756 processing the command), then there will be no visible result at all.
6757 </para>
6758
6759 </listitem>
6760 </varlistentry>
6761
6762 <varlistentry id="libpq-PQcancelSocket">
6763 <term><function>PQcancelSocket</function><indexterm><primary>PQcancelSocket</primary></indexterm></term>
6764
6765 <listitem>
6766 <para>
6767 Obtains the file descriptor number of the cancel connection socket to
6768 the server.
6769 <synopsis>
6770 int PQcancelSocket(const PGcancelConn *cancelConn);
6771 </synopsis>
6772 </para>
6773
6774 <para>
6775 A valid descriptor will be greater than or equal to 0;
6776 a result of -1 indicates that no server connection is currently open.
6777 This might change as a result of calling any of the functions
6778 in this section on the <structname>PGcancelConn</structname>
6779 (except for <xref linkend="libpq-PQcancelErrorMessage"/> and
6780 <function>PQcancelSocket</function> itself).
6781 </para>
6782 </listitem>
6783 </varlistentry>
6784
6785 <varlistentry id="libpq-PQcancelErrorMessage">
6786 <term>
6787 <function>PQcancelErrorMessage</function><indexterm><primary>PQcancelErrorMessage</primary></indexterm>
6788 <indexterm><primary>error message</primary><secondary>in <structname>PGcancelConn</structname></secondary></indexterm>
6789 </term>
6790
6791 <listitem>
6792 <para>
6793 Returns the error message most recently generated by an
6794 operation on the cancel connection.
6795 <synopsis>
6796 char *PQcancelErrorMessage(const PGcancelConn *cancelconn);
6797 </synopsis>
6798 </para>
6799
6800 <para>
6801 Nearly all <application>libpq</application> functions that take a
6802 <structname>PGcancelConn</structname> will set a message for
6803 <xref linkend="libpq-PQcancelErrorMessage"/> if they fail.
6804 Note that by <application>libpq</application> convention,
6805 a nonempty <xref linkend="libpq-PQcancelErrorMessage"/> result
6806 can consist of multiple lines, and will include a trailing newline.
6807 The caller should not free the result directly.
6808 It will be freed when the associated
6809 <structname>PGcancelConn</structname> handle is passed to
6810 <xref linkend="libpq-PQcancelFinish"/>. The result string should not be
6811 expected to remain the same across operations on the
6812 <literal>PGcancelConn</literal> structure.
6813 </para>
6814 </listitem>
6815 </varlistentry>
6816
6817 <varlistentry id="libpq-PQcancelFinish">
6818 <term><function>PQcancelFinish</function><indexterm><primary>PQcancelFinish</primary></indexterm></term>
6819 <listitem>
6820 <para>
6821 Closes the cancel connection (if it did not finish sending the
6822 cancel request yet). Also frees memory used by the
6823 <structname>PGcancelConn</structname> object.
6824 <synopsis>
6825 void PQcancelFinish(PGcancelConn *cancelConn);
6826 </synopsis>
6827 </para>
6828
6829 <para>
6830 Note that even if the cancel attempt fails (as
6831 indicated by <xref linkend="libpq-PQcancelStatus"/>), the
6832 application should call <xref linkend="libpq-PQcancelFinish"/>
6833 to free the memory used by the <structname>PGcancelConn</structname>
6834 object.
6835 The <structname>PGcancelConn</structname> pointer must not be used
6836 again after <xref linkend="libpq-PQcancelFinish"/> has been called.
6837 </para>
6838 </listitem>
6839 </varlistentry>
6840
6841 <varlistentry id="libpq-PQcancelReset">
6842 <term><function>PQcancelReset</function><indexterm><primary>PQcancelReset</primary></indexterm></term>
6843 <listitem>
6844 <para>
6845 Resets the <symbol>PGcancelConn</symbol> so it can be reused for a new
6846 cancel connection.
6847 <synopsis>
6848 void PQcancelReset(PGcancelConn *cancelConn);
6849 </synopsis>
6850 </para>
6851
6852 <para>
6853 If the <symbol>PGcancelConn</symbol> is currently used to send a cancel
6854 request, then this connection is closed. It will then prepare the
6855 <symbol>PGcancelConn</symbol> object such that it can be used to send a
6856 new cancel request.
6857 </para>
6858
6859 <para>
6860 This can be used to create one <structname>PGcancelConn</structname>
6861 for a <structname>PGconn</structname> and reuse it multiple times
6862 throughout the lifetime of the original <structname>PGconn</structname>.
6863 </para>
6864 </listitem>
6865 </varlistentry>
6866 </variablelist>
6867 </sect2>
6868
6869 <sect2 id="libpq-cancel-deprecated">
6870 <title>Obsolete Functions for Sending Cancel Requests</title>
6871
6872 <para>
6873 These functions represent older methods of sending cancel requests.
6874 Although they still work, they are deprecated due to not sending the cancel
6875 requests in an encrypted manner, even when the original connection
6876 specified <literal>sslmode</literal> or <literal>gssencmode</literal> to
6877 require encryption. Thus these older methods are heavily discouraged from
6878 being used in new code, and it is recommended to change existing code to
6879 use the new functions instead.
6880 </para>
6881
6882 <variablelist>
6883 <varlistentry id="libpq-PQgetCancel">
6884 <term><function>PQgetCancel</function><indexterm><primary>PQgetCancel</primary></indexterm></term>
6885
6886 <listitem>
6887 <para>
6888 Creates a data structure containing the information needed to cancel
6889 a command using <xref linkend="libpq-PQcancel"/>.
6890 <synopsis>
6891 PGcancel *PQgetCancel(PGconn *conn);
6892 </synopsis>
6893 </para>
6894
6895 <para>
6896 <xref linkend="libpq-PQgetCancel"/> creates a
6897 <structname>PGcancel</structname><indexterm><primary>PGcancel</primary></indexterm>
6898 object given a <structname>PGconn</structname> connection object.
6899 It will return <symbol>NULL</symbol> if the given <parameter>conn</parameter>
6900 is <symbol>NULL</symbol> or an invalid connection.
6901 The <structname>PGcancel</structname> object is an opaque
6902 structure that is not meant to be accessed directly by the
6903 application; it can only be passed to <xref linkend="libpq-PQcancel"/>
6904 or <xref linkend="libpq-PQfreeCancel"/>.
6905 </para>
6906 </listitem>
6907 </varlistentry>
6908
6909 <varlistentry id="libpq-PQfreeCancel">
6910 <term><function>PQfreeCancel</function><indexterm><primary>PQfreeCancel</primary></indexterm></term>
6911
6912 <listitem>
6913 <para>
6914 Frees a data structure created by <xref linkend="libpq-PQgetCancel"/>.
6915 <synopsis>
6916 void PQfreeCancel(PGcancel *cancel);
6917 </synopsis>
6918 </para>
6919
6920 <para>
6921 <xref linkend="libpq-PQfreeCancel"/> frees a data object previously created
6922 by <xref linkend="libpq-PQgetCancel"/>.
6923 </para>
6924 </listitem>
6925 </varlistentry>
6926
6927 <varlistentry id="libpq-PQcancel">
6928 <term><function>PQcancel</function><indexterm><primary>PQcancel</primary></indexterm></term>
6929
6930 <listitem>
6931 <para>
6932 <xref linkend="libpq-PQcancel"/> is a deprecated and insecure
6933 variant of <xref linkend="libpq-PQcancelBlocking"/>, but one that can be
6934 used safely from within a signal handler.
6935 <synopsis>
6936 int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize);
6937 </synopsis>
6938 </para>
6939
6940 <para>
6941 <xref linkend="libpq-PQcancel"/> only exists because of backwards
6942 compatibility reasons. <xref linkend="libpq-PQcancelBlocking"/> should be
6943 used instead. The only benefit that <xref linkend="libpq-PQcancel"/> has
6944 is that it can be safely invoked from a signal handler, if the
6945 <parameter>errbuf</parameter> is a local variable in the signal handler.
6946 However, this is generally not considered a big enough benefit to be
6947 worth the security issues that this function has.
6948 </para>
6949
6950 <para>
6951 The <structname>PGcancel</structname> object is read-only as far as
6952 <xref linkend="libpq-PQcancel"/> is concerned, so it can also be invoked
6953 from a thread that is separate from the one manipulating the
6954 <structname>PGconn</structname> object.
6955 </para>
6956
6957 <para>
6958 The return value of <xref linkend="libpq-PQcancel"/> is 1 if the
6959 cancel request was successfully dispatched and 0 if not.
6960 If not, <parameter>errbuf</parameter> is filled with an explanatory
6961 error message.
6962 <parameter>errbuf</parameter> must be a char array of size
6963 <parameter>errbufsize</parameter> (the recommended size is 256 bytes).
6964 </para>
6965 </listitem>
6966 </varlistentry>
6967 </variablelist>
6968
6969 <variablelist>
6970 <varlistentry id="libpq-PQrequestCancel">
6971 <term><function>PQrequestCancel</function><indexterm><primary>PQrequestCancel</primary></indexterm></term>
6972
6973 <listitem>
6974 <para>
6975 <xref linkend="libpq-PQrequestCancel"/> is a deprecated and insecure
6976 variant of <xref linkend="libpq-PQcancelBlocking"/>.
6977 <synopsis>
6978 int PQrequestCancel(PGconn *conn);
6979 </synopsis>
6980 </para>
6981
6982 <para>
6983 <xref linkend="libpq-PQrequestCancel"/> only exists because of backwards
6984 compatibility reasons. <xref linkend="libpq-PQcancelBlocking"/> should be
6985 used instead. There is no benefit to using
6986 <xref linkend="libpq-PQrequestCancel"/> over
6987 <xref linkend="libpq-PQcancelBlocking"/>.
6988 </para>
6989
6990 <para>
6991 Requests that the server abandon processing of the current
6992 command. It operates directly on the
6993 <structname>PGconn</structname> object, and in case of failure stores the
6994 error message in the <structname>PGconn</structname> object (whence it can
6995 be retrieved by <xref linkend="libpq-PQerrorMessage"/>). Although
6996 the functionality is the same, this approach is not safe within
6997 multiple-thread programs or signal handlers, since it is possible
6998 that overwriting the <structname>PGconn</structname>'s error message will
6999 mess up the operation currently in progress on the connection.
7000 </para>
7001 </listitem>
7002 </varlistentry>
7003 </variablelist>
7004 </sect2>
7005 </sect1>
7006
7007 <sect1 id="libpq-fastpath">
7008 <title>The Fast-Path Interface</title>
7009
7010 <indexterm zone="libpq-fastpath">
7011 <primary>fast path</primary>
7012 </indexterm>
7013
7014 <para>
7015 <productname>PostgreSQL</productname> provides a fast-path interface
7016 to send simple function calls to the server.
7017 </para>
7018
7019 <warning>
7020 <para>
7021 This interface is unsafe and should not be used. When
7022 <parameter>result_is_int</parameter> is set to <literal>0</literal>,
7023 <function>PQfn</function> may write data beyond the end of
7024 <parameter>result_buf</parameter>, regardless of whether the buffer has
7025 enough space for the requested number of bytes. Furthermore, it is
7026 obsolete, as one can achieve similar
7027 performance and greater functionality by setting up a prepared
7028 statement to define the function call. Then, executing the statement
7029 with binary transmission of parameters and results substitutes for a
7030 fast-path function call.
7031 </para>
7032 </warning>
7033
7034 <para>
7035 The function <function id="libpq-PQfn">PQfn</function><indexterm><primary>PQfn</primary></indexterm>
7036 requests execution of a server function via the fast-path interface:
7037 <synopsis>
7038 PGresult *PQfn(PGconn *conn,
7039 int fnid,
7040 int *result_buf,
7041 int *result_len,
7042 int result_is_int,
7043 const PQArgBlock *args,
7044 int nargs);
7045
7046 typedef struct
7047 {
7048 int len;
7049 int isint;
7050 union
7051 {
7052 int *ptr;
7053 int integer;
7054 } u;
7055 } PQArgBlock;
7056 </synopsis>
7057 </para>
7058
7059 <para>
7060 The <parameter>fnid</parameter> argument is the OID of the function to be
7061 executed. <parameter>args</parameter> and <parameter>nargs</parameter> define the
7062 parameters to be passed to the function; they must match the declared
7063 function argument list. When the <parameter>isint</parameter> field of a
7064 parameter structure is true, the <parameter>u.integer</parameter> value is sent
7065 to the server as an integer of the indicated length (this must be
7066 2 or 4 bytes); proper byte-swapping occurs. When <parameter>isint</parameter>
7067 is false, the indicated number of bytes at <parameter>*u.ptr</parameter> are
7068 sent with no processing; the data must be in the format expected by
7069 the server for binary transmission of the function's argument data
7070 type. (The declaration of <parameter>u.ptr</parameter> as being of
7071 type <type>int *</type> is historical; it would be better to consider
7072 it <type>void *</type>.)
7073 <parameter>result_buf</parameter> points to the buffer in which to place
7074 the function's return value. The caller must have allocated sufficient
7075 space to store the return value. (There is no check!) The actual result
7076 length in bytes will be returned in the integer pointed to by
7077 <parameter>result_len</parameter>. If a 2- or 4-byte integer result
7078 is expected, set <parameter>result_is_int</parameter> to 1, otherwise
7079 set it to 0. Setting <parameter>result_is_int</parameter> to 1 causes
7080 <application>libpq</application> to byte-swap the value if necessary, so that it
7081 is delivered as a proper <type>int</type> value for the client machine;
7082 note that a 4-byte integer is delivered into <parameter>*result_buf</parameter>
7083 for either allowed result size.
7084 When <parameter>result_is_int</parameter> is 0, the binary-format byte string
7085 sent by the server is returned unmodified. (In this case it's better
7086 to consider <parameter>result_buf</parameter> as being of
7087 type <type>void *</type>.)
7088 </para>
7089
7090 <para>
7091 <function>PQfn</function> always returns a valid
7092 <structname>PGresult</structname> pointer, with
7093 status <literal>PGRES_COMMAND_OK</literal> for success
7094 or <literal>PGRES_FATAL_ERROR</literal> if some problem was encountered.
7095 The result status should be
7096 checked before the result is used. The caller is responsible for
7097 freeing the <structname>PGresult</structname> with
7098 <xref linkend="libpq-PQclear"/> when it is no longer needed.
7099 </para>
7100
7101 <para>
7102 To pass a NULL argument to the function, set
7103 the <parameter>len</parameter> field of that parameter structure
7104 to <literal>-1</literal>; the <parameter>isint</parameter>
7105 and <parameter>u</parameter> fields are then irrelevant.
7106 </para>
7107
7108 <para>
7109 If the function returns NULL, <parameter>*result_len</parameter> is set
7110 to <literal>-1</literal>, and <parameter>*result_buf</parameter> is not
7111 modified.
7112 </para>
7113
7114 <para>
7115 Note that it is not possible to handle set-valued results when using
7116 this interface. Also, the function must be a plain function, not an
7117 aggregate, window function, or procedure.
7118 </para>
7119
7120 </sect1>
7121
7122 <sect1 id="libpq-notify">
7123 <title>Asynchronous Notification</title>
7124
7125 <indexterm zone="libpq-notify">
7126 <primary>NOTIFY</primary>
7127 <secondary>in libpq</secondary>
7128 </indexterm>
7129
7130 <para>
7131 <productname>PostgreSQL</productname> offers asynchronous notification
7132 via the <command>LISTEN</command> and <command>NOTIFY</command>
7133 commands. A client session registers its interest in a particular
7134 notification channel with the <command>LISTEN</command> command (and
7135 can stop listening with the <command>UNLISTEN</command> command). All
7136 sessions listening on a particular channel will be notified
7137 asynchronously when a <command>NOTIFY</command> command with that
7138 channel name is executed by any session. A <quote>payload</quote> string can
7139 be passed to communicate additional data to the listeners.
7140 </para>
7141
7142 <para>
7143 <application>libpq</application> applications submit
7144 <command>LISTEN</command>, <command>UNLISTEN</command>,
7145 and <command>NOTIFY</command> commands as
7146 ordinary SQL commands. The arrival of <command>NOTIFY</command>
7147 messages can subsequently be detected by calling
7148 <function id="libpq-PQnotifies">PQnotifies</function>.<indexterm><primary>PQnotifies</primary></indexterm>
7149 </para>
7150
7151 <para>
7152 The function <function>PQnotifies</function> returns the next notification
7153 from a list of unhandled notification messages received from the server.
7154 It returns a null pointer if there are no pending notifications. Once a
7155 notification is returned from <function>PQnotifies</function>, it is considered
7156 handled and will be removed from the list of notifications.
7157
7158 <synopsis>
7159 PGnotify *PQnotifies(PGconn *conn);
7160
7161 typedef struct pgNotify
7162 {
7163 char *relname; /* notification channel name */
7164 int be_pid; /* process ID of notifying server process */
7165 char *extra; /* notification payload string */
7166 } PGnotify;
7167 </synopsis>
7168
7169 After processing a <structname>PGnotify</structname> object returned
7170 by <function>PQnotifies</function>, be sure to free it with
7171 <xref linkend="libpq-PQfreemem"/>. It is sufficient to free the
7172 <structname>PGnotify</structname> pointer; the
7173 <structfield>relname</structfield> and <structfield>extra</structfield>
7174 fields do not represent separate allocations. (The names of these fields
7175 are historical; in particular, channel names need not have anything to
7176 do with relation names.)
7177 </para>
7178
7179 <para>
7180 <xref linkend="libpq-example-2"/> gives a sample program that illustrates
7181 the use of asynchronous notification.
7182 </para>
7183
7184 <para>
7185 <function>PQnotifies</function> does not actually read data from the
7186 server; it just returns messages previously absorbed by another
7187 <application>libpq</application> function. In ancient releases of
7188 <application>libpq</application>, the only way to ensure timely receipt
7189 of <command>NOTIFY</command> messages was to constantly submit commands, even
7190 empty ones, and then check <function>PQnotifies</function> after each
7191 <xref linkend="libpq-PQexec"/>. While this still works, it is deprecated
7192 as a waste of processing power.
7193 </para>
7194
7195 <para>
7196 A better way to check for <command>NOTIFY</command> messages when you have no
7197 useful commands to execute is to call
7198 <xref linkend="libpq-PQconsumeInput"/>, then check
7199 <function>PQnotifies</function>. You can use
7200 <function>select()</function> to wait for data to arrive from the
7201 server, thereby using no <acronym>CPU</acronym> power unless there is
7202 something to do. (See <xref linkend="libpq-PQsocket"/> to obtain the file
7203 descriptor number to use with <function>select()</function>.) Note that
7204 this will work OK whether you submit commands with
7205 <xref linkend="libpq-PQsendQuery"/>/<xref linkend="libpq-PQgetResult"/> or
7206 simply use <xref linkend="libpq-PQexec"/>. You should, however, remember
7207 to check <function>PQnotifies</function> after each
7208 <xref linkend="libpq-PQgetResult"/> or <xref linkend="libpq-PQexec"/>, to
7209 see if any notifications came in during the processing of the command.
7210 </para>
7211
7212 </sect1>
7213
7214 <sect1 id="libpq-copy">
7215 <title>Functions Associated with the <command>COPY</command> Command</title>
7216
7217 <indexterm zone="libpq-copy">
7218 <primary>COPY</primary>
7219 <secondary>with libpq</secondary>
7220 </indexterm>
7221
7222 <para>
7223 The <command>COPY</command> command in
7224 <productname>PostgreSQL</productname> has options to read from or write
7225 to the network connection used by <application>libpq</application>.
7226 The functions described in this section allow applications to take
7227 advantage of this capability by supplying or consuming copied data.
7228 </para>
7229
7230 <para>
7231 The overall process is that the application first issues the SQL
7232 <command>COPY</command> command via <xref linkend="libpq-PQexec"/> or one
7233 of the equivalent functions. The response to this (if there is no
7234 error in the command) will be a <structname>PGresult</structname> object bearing
7235 a status code of <literal>PGRES_COPY_OUT</literal> or
7236 <literal>PGRES_COPY_IN</literal> (depending on the specified copy
7237 direction). The application should then use the functions of this
7238 section to receive or transmit data rows. When the data transfer is
7239 complete, another <structname>PGresult</structname> object is returned to indicate
7240 success or failure of the transfer. Its status will be
7241 <literal>PGRES_COMMAND_OK</literal> for success or
7242 <literal>PGRES_FATAL_ERROR</literal> if some problem was encountered.
7243 At this point further SQL commands can be issued via
7244 <xref linkend="libpq-PQexec"/>. (It is not possible to execute other SQL
7245 commands using the same connection while the <command>COPY</command>
7246 operation is in progress.)
7247 </para>
7248
7249 <para>
7250 If a <command>COPY</command> command is issued via
7251 <xref linkend="libpq-PQexec"/> in a string that could contain additional
7252 commands, the application must continue fetching results via
7253 <xref linkend="libpq-PQgetResult"/> after completing the <command>COPY</command>
7254 sequence. Only when <xref linkend="libpq-PQgetResult"/> returns
7255 <symbol>NULL</symbol> is it certain that the <xref linkend="libpq-PQexec"/>
7256 command string is done and it is safe to issue more commands.
7257 </para>
7258
7259 <para>
7260 The functions of this section should be executed only after obtaining
7261 a result status of <literal>PGRES_COPY_OUT</literal> or
7262 <literal>PGRES_COPY_IN</literal> from <xref linkend="libpq-PQexec"/> or
7263 <xref linkend="libpq-PQgetResult"/>.
7264 </para>
7265
7266 <para>
7267 A <structname>PGresult</structname> object bearing one of these status values
7268 carries some additional data about the <command>COPY</command> operation
7269 that is starting. This additional data is available using functions
7270 that are also used in connection with query results:
7271
7272 <variablelist>
7273 <varlistentry id="libpq-PQnfields-1">
7274 <term><function>PQnfields</function><indexterm
7275 ><primary>PQnfields</primary><secondary>with COPY</secondary></indexterm></term>
7276
7277 <listitem>
7278 <para>
7279 Returns the number of columns (fields) to be copied.
7280 </para>
7281 </listitem>
7282 </varlistentry>
7283
7284 <varlistentry id="libpq-PQbinaryTuples-1">
7285 <term><function>PQbinaryTuples</function><indexterm
7286 ><primary>PQbinaryTuples</primary><secondary>with COPY</secondary></indexterm></term>
7287
7288 <listitem>
7289 <para>
7290 0 indicates the overall copy format is textual (rows separated by
7291 newlines, columns separated by separator characters, etc.). 1
7292 indicates the overall copy format is binary. See <xref
7293 linkend="sql-copy"/> for more information.
7294 </para>
7295 </listitem>
7296 </varlistentry>
7297
7298 <varlistentry id="libpq-PQfformat-1">
7299 <term><function>PQfformat</function><indexterm
7300 ><primary>PQfformat</primary><secondary>with COPY</secondary></indexterm></term>
7301
7302 <listitem>
7303 <para>
7304 Returns the format code (0 for text, 1 for binary) associated with
7305 each column of the copy operation. The per-column format codes
7306 will always be zero when the overall copy format is textual, but
7307 the binary format can support both text and binary columns.
7308 (However, as of the current implementation of <command>COPY</command>,
7309 only binary columns appear in a binary copy; so the per-column
7310 formats always match the overall format at present.)
7311 </para>
7312 </listitem>
7313 </varlistentry>
7314 </variablelist>
7315 </para>
7316
7317 <sect2 id="libpq-copy-send">
7318 <title>Functions for Sending <command>COPY</command> Data</title>
7319
7320 <para>
7321 These functions are used to send data during <literal>COPY FROM
7322 STDIN</literal>. They will fail if called when the connection is not in
7323 <literal>COPY_IN</literal> state.
7324 </para>
7325
7326 <variablelist>
7327 <varlistentry id="libpq-PQputCopyData">
7328 <term><function>PQputCopyData</function><indexterm><primary>PQputCopyData</primary></indexterm></term>
7329
7330 <listitem>
7331 <para>
7332 Sends data to the server during <literal>COPY_IN</literal> state.
7333 <synopsis>
7334 int PQputCopyData(PGconn *conn,
7335 const char *buffer,
7336 int nbytes);
7337 </synopsis>
7338 </para>
7339
7340 <para>
7341 Transmits the <command>COPY</command> data in the specified
7342 <parameter>buffer</parameter>, of length <parameter>nbytes</parameter>, to the server.
7343 The result is 1 if the data was queued, zero if it was not queued
7344 because of full buffers (this will only happen in nonblocking mode),
7345 or -1 if an error occurred.
7346 (Use <xref linkend="libpq-PQerrorMessage"/> to retrieve details if
7347 the return value is -1. If the value is zero, wait for write-ready
7348 and try again.)
7349 </para>
7350
7351 <para>
7352 The application can divide the <command>COPY</command> data stream
7353 into buffer loads of any convenient size. Buffer-load boundaries
7354 have no semantic significance when sending. The contents of the
7355 data stream must match the data format expected by the
7356 <command>COPY</command> command; see <xref linkend="sql-copy"/> for details.
7357 </para>
7358 </listitem>
7359 </varlistentry>
7360
7361 <varlistentry id="libpq-PQputCopyEnd">
7362 <term><function>PQputCopyEnd</function><indexterm><primary>PQputCopyEnd</primary></indexterm></term>
7363
7364 <listitem>
7365 <para>
7366 Sends end-of-data indication to the server during <literal>COPY_IN</literal> state.
7367 <synopsis>
7368 int PQputCopyEnd(PGconn *conn,
7369 const char *errormsg);
7370 </synopsis>
7371 </para>
7372
7373 <para>
7374 Ends the <literal>COPY_IN</literal> operation successfully if
7375 <parameter>errormsg</parameter> is <symbol>NULL</symbol>. If
7376 <parameter>errormsg</parameter> is not <symbol>NULL</symbol> then the
7377 <command>COPY</command> is forced to fail, with the string pointed to by
7378 <parameter>errormsg</parameter> used as the error message. (One should not
7379 assume that this exact error message will come back from the server,
7380 however, as the server might have already failed the
7381 <command>COPY</command> for its own reasons.)
7382 </para>
7383
7384 <para>
7385 The result is 1 if the termination message was sent; or in
7386 nonblocking mode, this may only indicate that the termination
7387 message was successfully queued. (In nonblocking mode, to be
7388 certain that the data has been sent, you should next wait for
7389 write-ready and call <xref linkend="libpq-PQflush"/>, repeating until it
7390 returns zero.) Zero indicates that the function could not queue
7391 the termination message because of full buffers; this will only
7392 happen in nonblocking mode. (In this case, wait for
7393 write-ready and try the <xref linkend="libpq-PQputCopyEnd"/> call
7394 again.) If a hard error occurs, -1 is returned; you can use
7395 <xref linkend="libpq-PQerrorMessage"/> to retrieve details.
7396 </para>
7397
7398 <para>
7399 After successfully calling <xref linkend="libpq-PQputCopyEnd"/>, call
7400 <xref linkend="libpq-PQgetResult"/> to obtain the final result status of the
7401 <command>COPY</command> command. One can wait for this result to be
7402 available in the usual way. Then return to normal operation.
7403 </para>
7404 </listitem>
7405 </varlistentry>
7406 </variablelist>
7407
7408 </sect2>
7409
7410 <sect2 id="libpq-copy-receive">
7411 <title>Functions for Receiving <command>COPY</command> Data</title>
7412
7413 <para>
7414 These functions are used to receive data during <literal>COPY TO
7415 STDOUT</literal>. They will fail if called when the connection is not in
7416 <literal>COPY_OUT</literal> state.
7417 </para>
7418
7419 <variablelist>
7420 <varlistentry id="libpq-PQgetCopyData">
7421 <term><function>PQgetCopyData</function><indexterm><primary>PQgetCopyData</primary></indexterm></term>
7422
7423 <listitem>
7424 <para>
7425 Receives data from the server during <literal>COPY_OUT</literal> state.
7426 <synopsis>
7427 int PQgetCopyData(PGconn *conn,
7428 char **buffer,
7429 int async);
7430 </synopsis>
7431 </para>
7432
7433 <para>
7434 Attempts to obtain another row of data from the server during a
7435 <command>COPY</command>. Data is always returned one data row at
7436 a time; if only a partial row is available, it is not returned.
7437 Successful return of a data row involves allocating a chunk of
7438 memory to hold the data. The <parameter>buffer</parameter> parameter must
7439 be non-<symbol>NULL</symbol>. <parameter>*buffer</parameter> is set to
7440 point to the allocated memory, or to <symbol>NULL</symbol> in cases
7441 where no buffer is returned. A non-<symbol>NULL</symbol> result
7442 buffer should be freed using <xref linkend="libpq-PQfreemem"/> when no longer
7443 needed.
7444 </para>
7445
7446 <para>
7447 When a row is successfully returned, the return value is the number
7448 of data bytes in the row (this will always be greater than zero).
7449 The returned string is always null-terminated, though this is
7450 probably only useful for textual <command>COPY</command>. A result
7451 of zero indicates that the <command>COPY</command> is still in
7452 progress, but no row is yet available (this is only possible when
7453 <parameter>async</parameter> is true). A result of -1 indicates that the
7454 <command>COPY</command> is done. A result of -2 indicates that an
7455 error occurred (consult <xref linkend="libpq-PQerrorMessage"/> for the reason).
7456 </para>
7457
7458 <para>
7459 When <parameter>async</parameter> is true (not zero),
7460 <xref linkend="libpq-PQgetCopyData"/> will not block waiting for input; it
7461 will return zero if the <command>COPY</command> is still in progress
7462 but no complete row is available. (In this case wait for read-ready
7463 and then call <xref linkend="libpq-PQconsumeInput"/> before calling
7464 <xref linkend="libpq-PQgetCopyData"/> again.) When <parameter>async</parameter> is
7465 false (zero), <xref linkend="libpq-PQgetCopyData"/> will block until data is
7466 available or the operation completes.
7467 </para>
7468
7469 <para>
7470 After <xref linkend="libpq-PQgetCopyData"/> returns -1, call
7471 <xref linkend="libpq-PQgetResult"/> to obtain the final result status of the
7472 <command>COPY</command> command. One can wait for this result to be
7473 available in the usual way. Then return to normal operation.
7474 </para>
7475 </listitem>
7476 </varlistentry>
7477 </variablelist>
7478
7479 </sect2>
7480
7481 <sect2 id="libpq-copy-deprecated">
7482 <title>Obsolete Functions for <command>COPY</command></title>
7483
7484 <para>
7485 These functions represent older methods of handling <command>COPY</command>.
7486 Although they still work, they are deprecated due to poor error handling,
7487 inconvenient methods of detecting end-of-data, and lack of support for binary
7488 or nonblocking transfers.
7489 </para>
7490
7491 <variablelist>
7492 <varlistentry id="libpq-PQgetline">
7493 <term><function>PQgetline</function><indexterm><primary>PQgetline</primary></indexterm></term>
7494
7495 <listitem>
7496 <para>
7497 Reads a newline-terminated line of characters (transmitted
7498 by the server) into a buffer string of size <parameter>length</parameter>.
7499 <synopsis>
7500 int PQgetline(PGconn *conn,
7501 char *buffer,
7502 int length);
7503 </synopsis>
7504 </para>
7505
7506 <para>
7507 This function copies up to <parameter>length</parameter>-1 characters into
7508 the buffer and converts the terminating newline into a zero byte.
7509 <xref linkend="libpq-PQgetline"/> returns <symbol>EOF</symbol> at the
7510 end of input, 0 if the entire line has been read, and 1 if the
7511 buffer is full but the terminating newline has not yet been read.
7512 </para>
7513 <para>
7514 Note that the application must check to see if a new line consists
7515 of the two characters <literal>\.</literal>, which indicates
7516 that the server has finished sending the results of the
7517 <command>COPY</command> command. If the application might receive
7518 lines that are more than <parameter>length</parameter>-1 characters long,
7519 care is needed to be sure it recognizes the <literal>\.</literal>
7520 line correctly (and does not, for example, mistake the end of a
7521 long data line for a terminator line).
7522 </para>
7523 </listitem>
7524 </varlistentry>
7525
7526 <varlistentry id="libpq-PQgetlineAsync">
7527 <term><function>PQgetlineAsync</function><indexterm><primary>PQgetlineAsync</primary></indexterm></term>
7528
7529 <listitem>
7530 <para>
7531 Reads a row of <command>COPY</command> data (transmitted by the
7532 server) into a buffer without blocking.
7533 <synopsis>
7534 int PQgetlineAsync(PGconn *conn,
7535 char *buffer,
7536 int bufsize);
7537 </synopsis>
7538 </para>
7539
7540 <para>
7541 This function is similar to <xref linkend="libpq-PQgetline"/>, but it can be used
7542 by applications
7543 that must read <command>COPY</command> data asynchronously, that is, without blocking.
7544 Having issued the <command>COPY</command> command and gotten a <literal>PGRES_COPY_OUT</literal>
7545 response, the
7546 application should call <xref linkend="libpq-PQconsumeInput"/> and
7547 <xref linkend="libpq-PQgetlineAsync"/> until the
7548 end-of-data signal is detected.
7549 </para>
7550 <para>
7551 Unlike <xref linkend="libpq-PQgetline"/>, this function takes
7552 responsibility for detecting end-of-data.
7553 </para>
7554
7555 <para>
7556 On each call, <xref linkend="libpq-PQgetlineAsync"/> will return data if a
7557 complete data row is available in <application>libpq</application>'s input buffer.
7558 Otherwise, no data is returned until the rest of the row arrives.
7559 The function returns -1 if the end-of-copy-data marker has been recognized,
7560 or 0 if no data is available, or a positive number giving the number of
7561 bytes of data returned. If -1 is returned, the caller must next call
7562 <xref linkend="libpq-PQendcopy"/>, and then return to normal processing.
7563 </para>
7564
7565 <para>
7566 The data returned will not extend beyond a data-row boundary. If possible
7567 a whole row will be returned at one time. But if the buffer offered by
7568 the caller is too small to hold a row sent by the server, then a partial
7569 data row will be returned. With textual data this can be detected by testing
7570 whether the last returned byte is <literal>\n</literal> or not. (In a binary
7571 <command>COPY</command>, actual parsing of the <command>COPY</command> data format will be needed to make the
7572 equivalent determination.)
7573 The returned string is not null-terminated. (If you want to add a
7574 terminating null, be sure to pass a <parameter>bufsize</parameter> one smaller
7575 than the room actually available.)
7576 </para>
7577 </listitem>
7578 </varlistentry>
7579
7580 <varlistentry id="libpq-PQputline">
7581 <term><function>PQputline</function><indexterm><primary>PQputline</primary></indexterm></term>
7582
7583 <listitem>
7584 <para>
7585 Sends a null-terminated string to the server. Returns 0 if
7586 OK and <symbol>EOF</symbol> if unable to send the string.
7587 <synopsis>
7588 int PQputline(PGconn *conn,
7589 const char *string);
7590 </synopsis>
7591 </para>
7592
7593 <para>
7594 The <command>COPY</command> data stream sent by a series of calls
7595 to <xref linkend="libpq-PQputline"/> has the same format as that
7596 returned by <xref linkend="libpq-PQgetlineAsync"/>, except that
7597 applications are not obliged to send exactly one data row per
7598 <xref linkend="libpq-PQputline"/> call; it is okay to send a partial
7599 line or multiple lines per call.
7600 </para>
7601
7602 <note>
7603 <para>
7604 Before <productname>PostgreSQL</productname> protocol 3.0, it was necessary
7605 for the application to explicitly send the two characters
7606 <literal>\.</literal> as a final line to indicate to the server that it had
7607 finished sending <command>COPY</command> data. While this still works, it is deprecated and the
7608 special meaning of <literal>\.</literal> can be expected to be removed in a
7609 future release. (It already will misbehave in <literal>CSV</literal>
7610 mode.) It is sufficient to call <xref linkend="libpq-PQendcopy"/>
7611 after having sent the actual data.
7612 </para>
7613 </note>
7614 </listitem>
7615 </varlistentry>
7616
7617 <varlistentry id="libpq-PQputnbytes">
7618 <term><function>PQputnbytes</function><indexterm><primary>PQputnbytes</primary></indexterm></term>
7619
7620 <listitem>
7621 <para>
7622 Sends a non-null-terminated string to the server. Returns
7623 0 if OK and <symbol>EOF</symbol> if unable to send the string.
7624 <synopsis>
7625 int PQputnbytes(PGconn *conn,
7626 const char *buffer,
7627 int nbytes);
7628 </synopsis>
7629 </para>
7630
7631 <para>
7632 This is exactly like <xref linkend="libpq-PQputline"/>, except that the data
7633 buffer need not be null-terminated since the number of bytes to send is
7634 specified directly. Use this procedure when sending binary data.
7635 </para>
7636 </listitem>
7637 </varlistentry>
7638
7639 <varlistentry id="libpq-PQendcopy">
7640 <term><function>PQendcopy</function><indexterm><primary>PQendcopy</primary></indexterm></term>
7641
7642 <listitem>
7643 <para>
7644 Synchronizes with the server.
7645 <synopsis>
7646 int PQendcopy(PGconn *conn);
7647 </synopsis>
7648 This function waits until the server has finished the copying.
7649 It should either be issued when the last string has been sent
7650 to the server using <xref linkend="libpq-PQputline"/> or when the
7651 last string has been received from the server using
7652 <function>PQgetline</function>. It must be issued or the server
7653 will get <quote>out of sync</quote> with the client. Upon return
7654 from this function, the server is ready to receive the next SQL
7655 command. The return value is 0 on successful completion,
7656 nonzero otherwise. (Use <xref linkend="libpq-PQerrorMessage"/> to
7657 retrieve details if the return value is nonzero.)
7658 </para>
7659
7660 <para>
7661 When using <xref linkend="libpq-PQgetResult"/>, the application should
7662 respond to a <literal>PGRES_COPY_OUT</literal> result by executing
7663 <xref linkend="libpq-PQgetline"/> repeatedly, followed by
7664 <xref linkend="libpq-PQendcopy"/> after the terminator line is seen.
7665 It should then return to the <xref linkend="libpq-PQgetResult"/> loop
7666 until <xref linkend="libpq-PQgetResult"/> returns a null pointer.
7667 Similarly a <literal>PGRES_COPY_IN</literal> result is processed
7668 by a series of <xref linkend="libpq-PQputline"/> calls followed by
7669 <xref linkend="libpq-PQendcopy"/>, then return to the
7670 <xref linkend="libpq-PQgetResult"/> loop. This arrangement will
7671 ensure that a <command>COPY</command> command embedded in a series
7672 of <acronym>SQL</acronym> commands will be executed correctly.
7673 </para>
7674
7675 <para>
7676 Older applications are likely to submit a <command>COPY</command>
7677 via <xref linkend="libpq-PQexec"/> and assume that the transaction
7678 is done after <xref linkend="libpq-PQendcopy"/>. This will work
7679 correctly only if the <command>COPY</command> is the only
7680 <acronym>SQL</acronym> command in the command string.
7681 </para>
7682 </listitem>
7683 </varlistentry>
7684 </variablelist>
7685
7686 </sect2>
7687
7688 </sect1>
7689
7690 <sect1 id="libpq-control">
7691 <title>Control Functions</title>
7692
7693 <para>
7694 These functions control miscellaneous details of <application>libpq</application>'s
7695 behavior.
7696 </para>
7697
7698 <variablelist>
7699 <varlistentry id="libpq-PQclientEncoding">
7700 <term><function>PQclientEncoding</function><indexterm><primary>PQclientEncoding</primary></indexterm></term>
7701
7702 <listitem>
7703 <para>
7704 Returns the client encoding.
7705 <synopsis>
7706 int PQclientEncoding(const PGconn *<replaceable>conn</replaceable>);
7707 </synopsis>
7708
7709 Note that it returns the encoding ID, not a symbolic string
7710 such as <literal>EUC_JP</literal>. If unsuccessful, it returns -1.
7711 To convert an encoding ID to an encoding name, you
7712 can use:
7713
7714 <synopsis>
7715 char *pg_encoding_to_char(int <replaceable>encoding_id</replaceable>);
7716 </synopsis>
7717 </para>
7718 </listitem>
7719 </varlistentry>
7720
7721 <varlistentry id="libpq-PQsetClientEncoding">
7722 <term><function>PQsetClientEncoding</function><indexterm><primary>PQsetClientEncoding</primary></indexterm></term>
7723
7724 <listitem>
7725 <para>
7726 Sets the client encoding.
7727 <synopsis>
7728 int PQsetClientEncoding(PGconn *<replaceable>conn</replaceable>, const char *<replaceable>encoding</replaceable>);
7729 </synopsis>
7730
7731 <replaceable>conn</replaceable> is a connection to the server,
7732 and <replaceable>encoding</replaceable> is the encoding you want to
7733 use. If the function successfully sets the encoding, it returns 0,
7734 otherwise -1. The current encoding for this connection can be
7735 determined by using <xref linkend="libpq-PQclientEncoding"/>.
7736 </para>
7737 </listitem>
7738 </varlistentry>
7739
7740 <varlistentry id="libpq-PQsetErrorVerbosity">
7741 <term><function>PQsetErrorVerbosity</function><indexterm><primary>PQsetErrorVerbosity</primary></indexterm></term>
7742
7743 <listitem>
7744 <para>
7745 Determines the verbosity of messages returned by
7746 <xref linkend="libpq-PQerrorMessage"/> and <xref linkend="libpq-PQresultErrorMessage"/>.
7747 <synopsis>
7748 typedef enum
7749 {
7750 PQERRORS_TERSE,
7751 PQERRORS_DEFAULT,
7752 PQERRORS_VERBOSE,
7753 PQERRORS_SQLSTATE
7754 } PGVerbosity;
7755
7756 PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity);
7757 </synopsis>
7758
7759 <xref linkend="libpq-PQsetErrorVerbosity"/> sets the verbosity mode,
7760 returning the connection's previous setting.
7761 In <firstterm>TERSE</firstterm> mode, returned messages include
7762 severity, primary text, and position only; this will normally fit on a
7763 single line. The <firstterm>DEFAULT</firstterm> mode produces messages
7764 that include the above plus any detail, hint, or context fields (these
7765 might span multiple lines). The <firstterm>VERBOSE</firstterm> mode
7766 includes all available fields. The <firstterm>SQLSTATE</firstterm>
7767 mode includes only the error severity and the <symbol>SQLSTATE</symbol>
7768 error code, if one is available (if not, the output is like
7769 <firstterm>TERSE</firstterm> mode).
7770 </para>
7771
7772 <para>
7773 Changing the verbosity setting does not affect the messages available
7774 from already-existing <structname>PGresult</structname> objects, only
7775 subsequently-created ones.
7776 (But see <xref linkend="libpq-PQresultVerboseErrorMessage"/> if you
7777 want to print a previous error with a different verbosity.)
7778 </para>
7779 </listitem>
7780 </varlistentry>
7781
7782 <varlistentry id="libpq-PQsetErrorContextVisibility">
7783 <term><function>PQsetErrorContextVisibility</function><indexterm><primary>PQsetErrorContextVisibility</primary></indexterm></term>
7784
7785 <listitem>
7786 <para>
7787 Determines the handling of <literal>CONTEXT</literal> fields in messages
7788 returned by <xref linkend="libpq-PQerrorMessage"/>
7789 and <xref linkend="libpq-PQresultErrorMessage"/>.
7790 <synopsis>
7791 typedef enum
7792 {
7793 PQSHOW_CONTEXT_NEVER,
7794 PQSHOW_CONTEXT_ERRORS,
7795 PQSHOW_CONTEXT_ALWAYS
7796 } PGContextVisibility;
7797
7798 PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context);
7799 </synopsis>
7800
7801 <xref linkend="libpq-PQsetErrorContextVisibility"/> sets the context display mode,
7802 returning the connection's previous setting. This mode controls
7803 whether the <literal>CONTEXT</literal> field is included in messages.
7804 The <firstterm>NEVER</firstterm> mode
7805 never includes <literal>CONTEXT</literal>, while <firstterm>ALWAYS</firstterm> always
7806 includes it if available. In <firstterm>ERRORS</firstterm> mode (the
7807 default), <literal>CONTEXT</literal> fields are included only in error
7808 messages, not in notices and warnings.
7809 (However, if the verbosity setting is <firstterm>TERSE</firstterm>
7810 or <firstterm>SQLSTATE</firstterm>, <literal>CONTEXT</literal> fields
7811 are omitted regardless of the context display mode.)
7812 </para>
7813
7814 <para>
7815 Changing this mode does not
7816 affect the messages available from
7817 already-existing <structname>PGresult</structname> objects, only
7818 subsequently-created ones.
7819 (But see <xref linkend="libpq-PQresultVerboseErrorMessage"/> if you
7820 want to print a previous error with a different display mode.)
7821 </para>
7822 </listitem>
7823 </varlistentry>
7824
7825 <varlistentry id="libpq-PQtrace">
7826 <term><function>PQtrace</function><indexterm><primary>PQtrace</primary></indexterm></term>
7827
7828 <listitem>
7829 <para>
7830 Enables tracing of the client/server communication to a debugging file
7831 stream.
7832 <synopsis>
7833 void PQtrace(PGconn *conn, FILE *stream);
7834 </synopsis>
7835 </para>
7836
7837 <para>
7838 Each line consists of: an optional timestamp, a direction indicator
7839 (<literal>F</literal> for messages from client to server
7840 or <literal>B</literal> for messages from server to client),
7841 message length, message type, and message contents.
7842 Non-message contents fields (timestamp, direction, length and message type)
7843 are separated by a tab. Message contents are separated by a space.
7844 Protocol strings are enclosed in double quotes, while strings used as data
7845 values are enclosed in single quotes. Non-printable chars are printed as
7846 hexadecimal escapes.
7847 Further message-type-specific detail can be found in
7848 <xref linkend="protocol-message-formats"/>.
7849 </para>
7850
7851 <note>
7852 <para>
7853 On Windows, if the <application>libpq</application> library and an application are
7854 compiled with different flags, this function call will crash the
7855 application because the internal representation of the <literal>FILE</literal>
7856 pointers differ. Specifically, multithreaded/single-threaded,
7857 release/debug, and static/dynamic flags should be the same for the
7858 library and all applications using that library.
7859 </para>
7860 </note>
7861
7862 </listitem>
7863 </varlistentry>
7864
7865 <varlistentry id="libpq-PQsetTraceFlags">
7866 <term><function>PQsetTraceFlags</function><indexterm><primary>PQsetTraceFlags</primary></indexterm></term>
7867
7868 <listitem>
7869 <para>
7870 Controls the tracing behavior of client/server communication.
7871 <synopsis>
7872 void PQsetTraceFlags(PGconn *conn, int flags);
7873 </synopsis>
7874 </para>
7875
7876 <para>
7877 <literal>flags</literal> contains flag bits describing the operating mode
7878 of tracing.
7879 If <literal>flags</literal> contains <literal>PQTRACE_SUPPRESS_TIMESTAMPS</literal>,
7880 then the timestamp is not included when printing each message.
7881 If <literal>flags</literal> contains <literal>PQTRACE_REGRESS_MODE</literal>,
7882 then some fields are redacted when printing each message, such as object
7883 OIDs, to make the output more convenient to use in testing frameworks.
7884 This function must be called after calling <function>PQtrace</function>.
7885 </para>
7886
7887 </listitem>
7888 </varlistentry>
7889
7890 <varlistentry id="libpq-PQuntrace">
7891 <term><function>PQuntrace</function><indexterm><primary>PQuntrace</primary></indexterm></term>
7892
7893 <listitem>
7894 <para>
7895 Disables tracing started by <xref linkend="libpq-PQtrace"/>.
7896 <synopsis>
7897 void PQuntrace(PGconn *conn);
7898 </synopsis>
7899 </para>
7900 </listitem>
7901 </varlistentry>
7902 </variablelist>
7903
7904 </sect1>
7905
7906 <sect1 id="libpq-misc">
7907 <title>Miscellaneous Functions</title>
7908
7909 <para>
7910 As always, there are some functions that just don't fit anywhere.
7911 </para>
7912
7913 <variablelist>
7914 <varlistentry id="libpq-PQfreemem">
7915 <term><function>PQfreemem</function><indexterm><primary>PQfreemem</primary></indexterm></term>
7916
7917 <listitem>
7918 <para>
7919 Frees memory allocated by <application>libpq</application>.
7920 <synopsis>
7921 void PQfreemem(void *ptr);
7922 </synopsis>
7923 </para>
7924
7925 <para>
7926 Frees memory allocated by <application>libpq</application>, particularly
7927 <xref linkend="libpq-PQescapeByteaConn"/>,
7928 <xref linkend="libpq-PQescapeBytea"/>,
7929 <xref linkend="libpq-PQunescapeBytea"/>,
7930 and <function>PQnotifies</function>.
7931 It is particularly important that this function, rather than
7932 <function>free()</function>, be used on Microsoft Windows. This is because
7933 allocating memory in a DLL and releasing it in the application works
7934 only if multithreaded/single-threaded, release/debug, and static/dynamic
7935 flags are the same for the DLL and the application. On non-Microsoft
7936 Windows platforms, this function is the same as the standard library
7937 function <function>free()</function>.
7938 </para>
7939 </listitem>
7940 </varlistentry>
7941
7942 <varlistentry id="libpq-PQconninfoFree">
7943 <term><function>PQconninfoFree</function><indexterm><primary>PQconninfoFree</primary></indexterm></term>
7944
7945 <listitem>
7946 <para>
7947 Frees the data structures allocated by
7948 <xref linkend="libpq-PQconndefaults"/> or <xref linkend="libpq-PQconninfoParse"/>.
7949 <synopsis>
7950 void PQconninfoFree(PQconninfoOption *connOptions);
7951 </synopsis>
7952 If the argument is a <symbol>NULL</symbol> pointer, no operation is
7953 performed.
7954 </para>
7955
7956 <para>
7957 A simple <xref linkend="libpq-PQfreemem"/> will not do for this, since
7958 the array contains references to subsidiary strings.
7959 </para>
7960 </listitem>
7961 </varlistentry>
7962
7963 <varlistentry id="libpq-PQencryptPasswordConn">
7964 <term><function>PQencryptPasswordConn</function><indexterm><primary>PQencryptPasswordConn</primary></indexterm></term>
7965
7966 <listitem>
7967 <para>
7968 Prepares the encrypted form of a <productname>PostgreSQL</productname> password.
7969 <synopsis>
7970 char *PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm);
7971 </synopsis>
7972 This function is intended to be used by client applications that
7973 wish to send commands like <literal>ALTER USER joe PASSWORD
7974 'pwd'</literal>. It is good practice not to send the original cleartext
7975 password in such a command, because it might be exposed in command
7976 logs, activity displays, and so on. Instead, use this function to
7977 convert the password to encrypted form before it is sent.
7978 </para>
7979
7980 <para>
7981 The <parameter>passwd</parameter> and <parameter>user</parameter> arguments
7982 are the cleartext password, and the SQL name of the user it is for.
7983 <parameter>algorithm</parameter> specifies the encryption algorithm
7984 to use to encrypt the password. Currently supported algorithms are
7985 <literal>md5</literal> and <literal>scram-sha-256</literal> (<literal>on</literal> and
7986 <literal>off</literal> are also accepted as aliases for <literal>md5</literal>, for
7987 compatibility with older server versions). Note that support for
7988 <literal>scram-sha-256</literal> was introduced in <productname>PostgreSQL</productname>
7989 version 10, and will not work correctly with older server versions. If
7990 <parameter>algorithm</parameter> is <symbol>NULL</symbol>, this function will query
7991 the server for the current value of the
7992 <xref linkend="guc-password-encryption"/> setting. That can block, and
7993 will fail if the current transaction is aborted, or if the connection
7994 is busy executing another query. If you wish to use the default
7995 algorithm for the server but want to avoid blocking, query
7996 <varname>password_encryption</varname> yourself before calling
7997 <xref linkend="libpq-PQencryptPasswordConn"/>, and pass that value as the
7998 <parameter>algorithm</parameter>.
7999 </para>
8000
8001 <para>
8002 The return value is a string allocated by <function>malloc</function>.
8003 The caller can assume the string doesn't contain any special characters
8004 that would require escaping. Use <xref linkend="libpq-PQfreemem"/> to free the
8005 result when done with it. On error, returns <symbol>NULL</symbol>, and
8006 a suitable message is stored in the connection object.
8007 </para>
8008
8009 </listitem>
8010 </varlistentry>
8011
8012 <varlistentry id="libpq-PQchangePassword">
8013 <term><function>PQchangePassword</function><indexterm><primary>PQchangePassword</primary></indexterm></term>
8014
8015 <listitem>
8016 <para>
8017 Changes a <productname>PostgreSQL</productname> password.
8018 <synopsis>
8019 PGresult *PQchangePassword(PGconn *conn, const char *user, const char *passwd);
8020 </synopsis>
8021 This function uses <function>PQencryptPasswordConn</function>
8022 to build and execute the command <literal>ALTER USER ... PASSWORD
8023 '...'</literal>, thereby changing the user's password. It exists for
8024 the same reason as <function>PQencryptPasswordConn</function>, but
8025 is more convenient as it both builds and runs the command for you.
8026 <xref linkend="libpq-PQencryptPasswordConn"/> is passed a
8027 <symbol>NULL</symbol> for the algorithm argument, hence encryption is
8028 done according to the server's <xref linkend="guc-password-encryption"/>
8029 setting.
8030 </para>
8031
8032 <para>
8033 The <parameter>user</parameter> and <parameter>passwd</parameter> arguments
8034 are the SQL name of the target user, and the new cleartext password.
8035 </para>
8036
8037 <para>
8038 Returns a <structname>PGresult</structname> pointer representing
8039 the result of the <literal>ALTER USER</literal> command, or
8040 a null pointer if the routine failed before issuing any command.
8041 The <xref linkend="libpq-PQresultStatus"/> function should be called
8042 to check the return value for any errors (including the value of a null
8043 pointer, in which case it will return
8044 <symbol>PGRES_FATAL_ERROR</symbol>). Use
8045 <xref linkend="libpq-PQerrorMessage"/> to get more information about
8046 such errors.
8047 </para>
8048 </listitem>
8049 </varlistentry>
8050
8051 <varlistentry id="libpq-PQencryptPassword">
8052 <term><function>PQencryptPassword</function><indexterm><primary>PQencryptPassword</primary></indexterm></term>
8053
8054 <listitem>
8055 <para>
8056 Prepares the md5-encrypted form of a <productname>PostgreSQL</productname> password.
8057 <synopsis>
8058 char *PQencryptPassword(const char *passwd, const char *user);
8059 </synopsis>
8060 <xref linkend="libpq-PQencryptPassword"/> is an older, deprecated version of
8061 <xref linkend="libpq-PQencryptPasswordConn"/>. The difference is that
8062 <xref linkend="libpq-PQencryptPassword"/> does not
8063 require a connection object, and <literal>md5</literal> is always used as the
8064 encryption algorithm.
8065 </para>
8066 </listitem>
8067 </varlistentry>
8068
8069 <varlistentry id="libpq-PQmakeEmptyPGresult">
8070 <term><function>PQmakeEmptyPGresult</function><indexterm><primary>PQmakeEmptyPGresult</primary></indexterm></term>
8071
8072 <listitem>
8073 <para>
8074 Constructs an empty <structname>PGresult</structname> object with the given status.
8075 <synopsis>
8076 PGresult *PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status);
8077 </synopsis>
8078 </para>
8079
8080 <para>
8081 This is <application>libpq</application>'s internal function to allocate and
8082 initialize an empty <structname>PGresult</structname> object. This
8083 function returns <symbol>NULL</symbol> if memory could not be allocated. It is
8084 exported because some applications find it useful to generate result
8085 objects (particularly objects with error status) themselves. If
8086 <parameter>conn</parameter> is not null and <parameter>status</parameter>
8087 indicates an error, the current error message of the specified
8088 connection is copied into the <structname>PGresult</structname>.
8089 Also, if <parameter>conn</parameter> is not null, any event procedures
8090 registered in the connection are copied into the
8091 <structname>PGresult</structname>. (They do not get
8092 <literal>PGEVT_RESULTCREATE</literal> calls, but see
8093 <xref linkend="libpq-PQfireResultCreateEvents"/>.)
8094 Note that <xref linkend="libpq-PQclear"/> should eventually be called
8095 on the object, just as with a <structname>PGresult</structname>
8096 returned by <application>libpq</application> itself.
8097 </para>
8098 </listitem>
8099 </varlistentry>
8100
8101 <varlistentry id="libpq-PQfireResultCreateEvents">
8102 <term><function>PQfireResultCreateEvents</function><indexterm><primary>PQfireResultCreateEvents</primary></indexterm></term>
8103 <listitem>
8104 <para>
8105 Fires a <literal>PGEVT_RESULTCREATE</literal> event (see <xref
8106 linkend="libpq-events"/>) for each event procedure registered in the
8107 <structname>PGresult</structname> object. Returns non-zero for success,
8108 zero if any event procedure fails.
8109
8110 <synopsis>
8111 int PQfireResultCreateEvents(PGconn *conn, PGresult *res);
8112 </synopsis>
8113 </para>
8114
8115 <para>
8116 The <literal>conn</literal> argument is passed through to event procedures
8117 but not used directly. It can be <symbol>NULL</symbol> if the event
8118 procedures won't use it.
8119 </para>
8120
8121 <para>
8122 Event procedures that have already received a
8123 <literal>PGEVT_RESULTCREATE</literal> or <literal>PGEVT_RESULTCOPY</literal> event
8124 for this object are not fired again.
8125 </para>
8126
8127 <para>
8128 The main reason that this function is separate from
8129 <xref linkend="libpq-PQmakeEmptyPGresult"/> is that it is often appropriate
8130 to create a <structname>PGresult</structname> and fill it with data
8131 before invoking the event procedures.
8132 </para>
8133 </listitem>
8134 </varlistentry>
8135
8136 <varlistentry id="libpq-PQcopyResult">
8137 <term><function>PQcopyResult</function><indexterm><primary>PQcopyResult</primary></indexterm></term>
8138
8139 <listitem>
8140 <para>
8141 Makes a copy of a <structname>PGresult</structname> object. The copy is
8142 not linked to the source result in any way and
8143 <xref linkend="libpq-PQclear"/> must be called when the copy is no longer
8144 needed. If the function fails, <symbol>NULL</symbol> is returned.
8145
8146 <synopsis>
8147 PGresult *PQcopyResult(const PGresult *src, int flags);
8148 </synopsis>
8149 </para>
8150
8151 <para>
8152 This is not intended to make an exact copy. The returned result is
8153 always put into <literal>PGRES_TUPLES_OK</literal> status, and does not
8154 copy any error message in the source. (It does copy the command status
8155 string, however.) The <parameter>flags</parameter> argument determines
8156 what else is copied. It is a bitwise OR of several flags.
8157 <literal>PG_COPYRES_ATTRS</literal> specifies copying the source
8158 result's attributes (column definitions).
8159 <literal>PG_COPYRES_TUPLES</literal> specifies copying the source
8160 result's tuples. (This implies copying the attributes, too.)
8161 <literal>PG_COPYRES_NOTICEHOOKS</literal> specifies
8162 copying the source result's notify hooks.
8163 <literal>PG_COPYRES_EVENTS</literal> specifies copying the source
8164 result's events. (But any instance data associated with the source
8165 is not copied.)
8166 The event procedures receive <literal>PGEVT_RESULTCOPY</literal> events.
8167 </para>
8168 </listitem>
8169 </varlistentry>
8170
8171 <varlistentry id="libpq-PQsetResultAttrs">
8172 <term><function>PQsetResultAttrs</function><indexterm><primary>PQsetResultAttrs</primary></indexterm></term>
8173
8174 <listitem>
8175 <para>
8176 Sets the attributes of a <structname>PGresult</structname> object.
8177 <synopsis>
8178 int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs);
8179 </synopsis>
8180 </para>
8181
8182 <para>
8183 The provided <parameter>attDescs</parameter> are copied into the result.
8184 If the <parameter>attDescs</parameter> pointer is <symbol>NULL</symbol> or
8185 <parameter>numAttributes</parameter> is less than one, the request is
8186 ignored and the function succeeds. If <parameter>res</parameter>
8187 already contains attributes, the function will fail. If the function
8188 fails, the return value is zero. If the function succeeds, the return
8189 value is non-zero.
8190 </para>
8191 </listitem>
8192 </varlistentry>
8193
8194 <varlistentry id="libpq-PQsetvalue">
8195 <term><function>PQsetvalue</function><indexterm><primary>PQsetvalue</primary></indexterm></term>
8196
8197 <listitem>
8198 <para>
8199 Sets a tuple field value of a <structname>PGresult</structname> object.
8200 <synopsis>
8201 int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len);
8202 </synopsis>
8203 </para>
8204
8205 <para>
8206 The function will automatically grow the result's internal tuples array
8207 as needed. However, the <parameter>tup_num</parameter> argument must be
8208 less than or equal to <xref linkend="libpq-PQntuples"/>, meaning this
8209 function can only grow the tuples array one tuple at a time. But any
8210 field of any existing tuple can be modified in any order. If a value at
8211 <parameter>field_num</parameter> already exists, it will be overwritten.
8212 If <parameter>len</parameter> is -1 or
8213 <parameter>value</parameter> is <symbol>NULL</symbol>, the field value
8214 will be set to an SQL null value. The
8215 <parameter>value</parameter> is copied into the result's private storage,
8216 thus is no longer needed after the function
8217 returns. If the function fails, the return value is zero. If the
8218 function succeeds, the return value is non-zero.
8219 </para>
8220 </listitem>
8221 </varlistentry>
8222
8223 <varlistentry id="libpq-PQresultAlloc">
8224 <term><function>PQresultAlloc</function><indexterm><primary>PQresultAlloc</primary></indexterm></term>
8225
8226 <listitem>
8227 <para>
8228 Allocate subsidiary storage for a <structname>PGresult</structname> object.
8229 <synopsis>
8230 void *PQresultAlloc(PGresult *res, size_t nBytes);
8231 </synopsis>
8232 </para>
8233
8234 <para>
8235 Any memory allocated with this function will be freed when
8236 <parameter>res</parameter> is cleared. If the function fails,
8237 the return value is <symbol>NULL</symbol>. The result is
8238 guaranteed to be adequately aligned for any type of data,
8239 just as for <function>malloc</function>.
8240 </para>
8241 </listitem>
8242 </varlistentry>
8243
8244 <varlistentry id="libpq-PQresultMemorySize">
8245 <term><function>PQresultMemorySize</function><indexterm><primary>PQresultMemorySize</primary></indexterm></term>
8246
8247 <listitem>
8248 <para>
8249 Retrieves the number of bytes allocated for
8250 a <structname>PGresult</structname> object.
8251 <synopsis>
8252 size_t PQresultMemorySize(const PGresult *res);
8253 </synopsis>
8254 </para>
8255
8256 <para>
8257 This value is the sum of all <function>malloc</function> requests
8258 associated with the <structname>PGresult</structname> object, that is,
8259 all the memory that will be freed by <xref linkend="libpq-PQclear"/>.
8260 This information can be useful for managing memory consumption.
8261 </para>
8262 </listitem>
8263 </varlistentry>
8264
8265 <varlistentry id="libpq-PQlibVersion">
8266 <term><function>PQlibVersion</function><indexterm
8267 ><primary>PQlibVersion</primary><seealso>PQserverVersion</seealso></indexterm></term>
8268
8269 <listitem>
8270 <para>
8271 Return the version of <application>libpq</application> that is being used.
8272 <synopsis>
8273 int PQlibVersion(void);
8274 </synopsis>
8275 </para>
8276
8277 <para>
8278 The result of this function can be used to determine, at
8279 run time, whether specific functionality is available in the currently
8280 loaded version of libpq. The function can be used, for example,
8281 to determine which connection options are available in
8282 <xref linkend="libpq-PQconnectdb"/>.
8283 </para>
8284
8285 <para>
8286 The result is formed by multiplying the library's major version
8287 number by 10000 and adding the minor version number. For example,
8288 version 10.1 will be returned as 100001, and version 11.0 will be
8289 returned as 110000.
8290 </para>
8291
8292 <para>
8293 Prior to major version 10, <productname>PostgreSQL</productname> used
8294 three-part version numbers in which the first two parts together
8295 represented the major version. For those
8296 versions, <xref linkend="libpq-PQlibVersion"/> uses two digits for each
8297 part; for example version 9.1.5 will be returned as 90105, and
8298 version 9.2.0 will be returned as 90200.
8299 </para>
8300
8301 <para>
8302 Therefore, for purposes of determining feature compatibility,
8303 applications should divide the result of <xref linkend="libpq-PQlibVersion"/>
8304 by 100 not 10000 to determine a logical major version number.
8305 In all release series, only the last two digits differ between
8306 minor releases (bug-fix releases).
8307 </para>
8308
8309 <note>
8310 <para>
8311 This function appeared in <productname>PostgreSQL</productname> version 9.1, so
8312 it cannot be used to detect required functionality in earlier
8313 versions, since calling it will create a link dependency
8314 on version 9.1 or later.
8315 </para>
8316 </note>
8317 </listitem>
8318 </varlistentry>
8319
8320 <varlistentry id="libpq-PQgetCurrentTimeUSec">
8321 <term><function>PQgetCurrentTimeUSec</function><indexterm><primary>PQgetCurrentTimeUSec</primary></indexterm></term>
8322
8323 <listitem>
8324 <para>
8325 Retrieves the current time, expressed as the number of microseconds
8326 since the Unix epoch (that is, <type>time_t</type> times 1 million).
8327 <synopsis>
8328 pg_usec_time_t PQgetCurrentTimeUSec(void);
8329 </synopsis>
8330 </para>
8331
8332 <para>
8333 This is primarily useful for calculating timeout values to use with
8334 <xref linkend="libpq-PQsocketPoll"/>.
8335 </para>
8336 </listitem>
8337 </varlistentry>
8338
8339 </variablelist>
8340
8341 </sect1>
8342
8343 <sect1 id="libpq-notice-processing">
8344 <title>Notice Processing</title>
8345
8346 <indexterm zone="libpq-notice-processing">
8347 <primary>notice processing</primary>
8348 <secondary>in libpq</secondary>
8349 </indexterm>
8350
8351 <para>
8352 Notice and warning messages generated by the server are not returned
8353 by the query execution functions, since they do not imply failure of
8354 the query. Instead they are passed to a notice handling function, and
8355 execution continues normally after the handler returns. The default
8356 notice handling function prints the message on
8357 <filename>stderr</filename>, but the application can override this
8358 behavior by supplying its own handling function.
8359 </para>
8360
8361 <para>
8362 For historical reasons, there are two levels of notice handling, called
8363 the notice receiver and notice processor. The default behavior is for
8364 the notice receiver to format the notice and pass a string to the notice
8365 processor for printing. However, an application that chooses to provide
8366 its own notice receiver will typically ignore the notice processor
8367 layer and just do all the work in the notice receiver.
8368 </para>
8369
8370 <para>
8371 The function <function id="libpq-PQsetNoticeReceiver">PQsetNoticeReceiver</function>
8372 <indexterm><primary>notice receiver</primary></indexterm>
8373 <indexterm><primary>PQsetNoticeReceiver</primary></indexterm> sets or
8374 examines the current notice receiver for a connection object.
8375 Similarly, <function id="libpq-PQsetNoticeProcessor">PQsetNoticeProcessor</function>
8376 <indexterm><primary>notice processor</primary></indexterm>
8377 <indexterm><primary>PQsetNoticeProcessor</primary></indexterm> sets or
8378 examines the current notice processor.
8379
8380 <synopsis>
8381 typedef void (*PQnoticeReceiver) (void *arg, const PGresult *res);
8382
8383 PQnoticeReceiver
8384 PQsetNoticeReceiver(PGconn *conn,
8385 PQnoticeReceiver proc,
8386 void *arg);
8387
8388 typedef void (*PQnoticeProcessor) (void *arg, const char *message);
8389
8390 PQnoticeProcessor
8391 PQsetNoticeProcessor(PGconn *conn,
8392 PQnoticeProcessor proc,
8393 void *arg);
8394 </synopsis>
8395
8396 Each of these functions returns the previous notice receiver or
8397 processor function pointer, and sets the new value. If you supply a
8398 null function pointer, no action is taken, but the current pointer is
8399 returned.
8400 </para>
8401
8402 <para>
8403 When a notice or warning message is received from the server, or
8404 generated internally by <application>libpq</application>, the notice
8405 receiver function is called. It is passed the message in the form of
8406 a <symbol>PGRES_NONFATAL_ERROR</symbol>
8407 <structname>PGresult</structname>. (This allows the receiver to extract
8408 individual fields using <xref linkend="libpq-PQresultErrorField"/>, or obtain a
8409 complete preformatted message using <xref linkend="libpq-PQresultErrorMessage"/>
8410 or <xref linkend="libpq-PQresultVerboseErrorMessage"/>.) The same
8411 void pointer passed to <function>PQsetNoticeReceiver</function> is also
8412 passed. (This pointer can be used to access application-specific state
8413 if needed.)
8414 </para>
8415
8416 <para>
8417 The default notice receiver simply extracts the message (using
8418 <xref linkend="libpq-PQresultErrorMessage"/>) and passes it to the notice
8419 processor.
8420 </para>
8421
8422 <para>
8423 The notice processor is responsible for handling a notice or warning
8424 message given in text form. It is passed the string text of the message
8425 (including a trailing newline), plus a void pointer that is the same
8426 one passed to <function>PQsetNoticeProcessor</function>. (This pointer
8427 can be used to access application-specific state if needed.)
8428 </para>
8429
8430 <para>
8431 The default notice processor is simply:
8432 <programlisting>
8433 static void
8434 defaultNoticeProcessor(void *arg, const char *message)
8435 {
8436 fprintf(stderr, "%s", message);
8437 }
8438 </programlisting>
8439 </para>
8440
8441 <para>
8442 Once you have set a notice receiver or processor, you should expect
8443 that that function could be called as long as either the
8444 <structname>PGconn</structname> object or <structname>PGresult</structname> objects made
8445 from it exist. At creation of a <structname>PGresult</structname>, the
8446 <structname>PGconn</structname>'s current notice handling pointers are copied
8447 into the <structname>PGresult</structname> for possible use by functions like
8448 <xref linkend="libpq-PQgetvalue"/>.
8449 </para>
8450
8451 </sect1>
8452
8453 <sect1 id="libpq-events">
8454 <title>Event System</title>
8455
8456 <para>
8457 <application>libpq</application>'s event system is designed to notify
8458 registered event handlers about interesting
8459 <application>libpq</application> events, such as the creation or
8460 destruction of <structname>PGconn</structname> and
8461 <structname>PGresult</structname> objects. A principal use case is that
8462 this allows applications to associate their own data with a
8463 <structname>PGconn</structname> or <structname>PGresult</structname>
8464 and ensure that that data is freed at an appropriate time.
8465 </para>
8466
8467 <para>
8468 Each registered event handler is associated with two pieces of data,
8469 known to <application>libpq</application> only as opaque <literal>void *</literal>
8470 pointers. There is a <firstterm>pass-through</firstterm> pointer that is provided
8471 by the application when the event handler is registered with a
8472 <structname>PGconn</structname>. The pass-through pointer never changes for the
8473 life of the <structname>PGconn</structname> and all <structname>PGresult</structname>s
8474 generated from it; so if used, it must point to long-lived data.
8475 In addition there is an <firstterm>instance data</firstterm> pointer, which starts
8476 out <symbol>NULL</symbol> in every <structname>PGconn</structname> and <structname>PGresult</structname>.
8477 This pointer can be manipulated using the
8478 <xref linkend="libpq-PQinstanceData"/>,
8479 <xref linkend="libpq-PQsetInstanceData"/>,
8480 <xref linkend="libpq-PQresultInstanceData"/> and
8481 <xref linkend="libpq-PQresultSetInstanceData"/> functions. Note that
8482 unlike the pass-through pointer, instance data of a <structname>PGconn</structname>
8483 is not automatically inherited by <structname>PGresult</structname>s created from
8484 it. <application>libpq</application> does not know what pass-through
8485 and instance data pointers point to (if anything) and will never attempt
8486 to free them &mdash; that is the responsibility of the event handler.
8487 </para>
8488
8489 <sect2 id="libpq-events-types">
8490 <title>Event Types</title>
8491
8492 <para>
8493 The enum <literal>PGEventId</literal> names the types of events handled by
8494 the event system. All its values have names beginning with
8495 <literal>PGEVT</literal>. For each event type, there is a corresponding
8496 event info structure that carries the parameters passed to the event
8497 handlers. The event types are:
8498 </para>
8499
8500 <variablelist>
8501 <varlistentry id="libpq-pgevt-register">
8502 <term><literal>PGEVT_REGISTER</literal></term>
8503 <listitem>
8504 <para>
8505 The register event occurs when <xref linkend="libpq-PQregisterEventProc"/>
8506 is called. It is the ideal time to initialize any
8507 <literal>instanceData</literal> an event procedure may need. Only one
8508 register event will be fired per event handler per connection. If the
8509 event procedure fails (returns zero), the registration is canceled.
8510
8511 <synopsis>
8512 typedef struct
8513 {
8514 PGconn *conn;
8515 } PGEventRegister;
8516 </synopsis>
8517
8518 When a <literal>PGEVT_REGISTER</literal> event is received, the
8519 <parameter>evtInfo</parameter> pointer should be cast to a
8520 <structname>PGEventRegister *</structname>. This structure contains a
8521 <structname>PGconn</structname> that should be in the
8522 <symbol>CONNECTION_OK</symbol> status; guaranteed if one calls
8523 <xref linkend="libpq-PQregisterEventProc"/> right after obtaining a good
8524 <structname>PGconn</structname>. When returning a failure code, all
8525 cleanup must be performed as no <literal>PGEVT_CONNDESTROY</literal>
8526 event will be sent.
8527 </para>
8528 </listitem>
8529 </varlistentry>
8530
8531 <varlistentry id="libpq-pgevt-connreset">
8532 <term><literal>PGEVT_CONNRESET</literal></term>
8533 <listitem>
8534 <para>
8535 The connection reset event is fired on completion of
8536 <xref linkend="libpq-PQreset"/> or <function>PQresetPoll</function>. In
8537 both cases, the event is only fired if the reset was successful.
8538 The return value of the event procedure is ignored
8539 in <productname>PostgreSQL</productname> v15 and later.
8540 With earlier versions, however, it's important to return success
8541 (nonzero) or the connection will be aborted.
8542
8543 <synopsis>
8544 typedef struct
8545 {
8546 PGconn *conn;
8547 } PGEventConnReset;
8548 </synopsis>
8549
8550 When a <literal>PGEVT_CONNRESET</literal> event is received, the
8551 <parameter>evtInfo</parameter> pointer should be cast to a
8552 <structname>PGEventConnReset *</structname>. Although the contained
8553 <structname>PGconn</structname> was just reset, all event data remains
8554 unchanged. This event should be used to reset/reload/requery any
8555 associated <literal>instanceData</literal>. Note that even if the
8556 event procedure fails to process <literal>PGEVT_CONNRESET</literal>, it will
8557 still receive a <literal>PGEVT_CONNDESTROY</literal> event when the connection
8558 is closed.
8559 </para>
8560 </listitem>
8561 </varlistentry>
8562
8563 <varlistentry id="libpq-pgevt-conndestroy">
8564 <term><literal>PGEVT_CONNDESTROY</literal></term>
8565 <listitem>
8566 <para>
8567 The connection destroy event is fired in response to
8568 <xref linkend="libpq-PQfinish"/>. It is the event procedure's
8569 responsibility to properly clean up its event data as libpq has no
8570 ability to manage this memory. Failure to clean up will lead
8571 to memory leaks.
8572
8573 <synopsis>
8574 typedef struct
8575 {
8576 PGconn *conn;
8577 } PGEventConnDestroy;
8578 </synopsis>
8579
8580 When a <literal>PGEVT_CONNDESTROY</literal> event is received, the
8581 <parameter>evtInfo</parameter> pointer should be cast to a
8582 <structname>PGEventConnDestroy *</structname>. This event is fired
8583 prior to <xref linkend="libpq-PQfinish"/> performing any other cleanup.
8584 The return value of the event procedure is ignored since there is no
8585 way of indicating a failure from <xref linkend="libpq-PQfinish"/>. Also,
8586 an event procedure failure should not abort the process of cleaning up
8587 unwanted memory.
8588 </para>
8589 </listitem>
8590 </varlistentry>
8591
8592 <varlistentry id="libpq-pgevt-resultcreate">
8593 <term><literal>PGEVT_RESULTCREATE</literal></term>
8594 <listitem>
8595 <para>
8596 The result creation event is fired in response to any query execution
8597 function that generates a result, including
8598 <xref linkend="libpq-PQgetResult"/>. This event will only be fired after
8599 the result has been created successfully.
8600
8601 <synopsis>
8602 typedef struct
8603 {
8604 PGconn *conn;
8605 PGresult *result;
8606 } PGEventResultCreate;
8607 </synopsis>
8608
8609 When a <literal>PGEVT_RESULTCREATE</literal> event is received, the
8610 <parameter>evtInfo</parameter> pointer should be cast to a
8611 <structname>PGEventResultCreate *</structname>. The
8612 <parameter>conn</parameter> is the connection used to generate the
8613 result. This is the ideal place to initialize any
8614 <literal>instanceData</literal> that needs to be associated with the
8615 result. If an event procedure fails (returns zero), that event
8616 procedure will be ignored for the remaining lifetime of the result;
8617 that is, it will not receive <literal>PGEVT_RESULTCOPY</literal>
8618 or <literal>PGEVT_RESULTDESTROY</literal> events for this result or
8619 results copied from it.
8620 </para>
8621 </listitem>
8622 </varlistentry>
8623
8624 <varlistentry id="libpq-pgevt-resultcopy">
8625 <term><literal>PGEVT_RESULTCOPY</literal></term>
8626 <listitem>
8627 <para>
8628 The result copy event is fired in response to
8629 <xref linkend="libpq-PQcopyResult"/>. This event will only be fired after
8630 the copy is complete. Only event procedures that have
8631 successfully handled the <literal>PGEVT_RESULTCREATE</literal>
8632 or <literal>PGEVT_RESULTCOPY</literal> event for the source result
8633 will receive <literal>PGEVT_RESULTCOPY</literal> events.
8634
8635 <synopsis>
8636 typedef struct
8637 {
8638 const PGresult *src;
8639 PGresult *dest;
8640 } PGEventResultCopy;
8641 </synopsis>
8642
8643 When a <literal>PGEVT_RESULTCOPY</literal> event is received, the
8644 <parameter>evtInfo</parameter> pointer should be cast to a
8645 <structname>PGEventResultCopy *</structname>. The
8646 <parameter>src</parameter> result is what was copied while the
8647 <parameter>dest</parameter> result is the copy destination. This event
8648 can be used to provide a deep copy of <literal>instanceData</literal>,
8649 since <literal>PQcopyResult</literal> cannot do that. If an event
8650 procedure fails (returns zero), that event procedure will be
8651 ignored for the remaining lifetime of the new result; that is, it
8652 will not receive <literal>PGEVT_RESULTCOPY</literal>
8653 or <literal>PGEVT_RESULTDESTROY</literal> events for that result or
8654 results copied from it.
8655 </para>
8656 </listitem>
8657 </varlistentry>
8658
8659 <varlistentry id="libpq-pgevt-resultdestroy">
8660 <term><literal>PGEVT_RESULTDESTROY</literal></term>
8661 <listitem>
8662 <para>
8663 The result destroy event is fired in response to a
8664 <xref linkend="libpq-PQclear"/>. It is the event procedure's
8665 responsibility to properly clean up its event data as libpq has no
8666 ability to manage this memory. Failure to clean up will lead
8667 to memory leaks.
8668
8669 <synopsis>
8670 typedef struct
8671 {
8672 PGresult *result;
8673 } PGEventResultDestroy;
8674 </synopsis>
8675
8676 When a <literal>PGEVT_RESULTDESTROY</literal> event is received, the
8677 <parameter>evtInfo</parameter> pointer should be cast to a
8678 <structname>PGEventResultDestroy *</structname>. This event is fired
8679 prior to <xref linkend="libpq-PQclear"/> performing any other cleanup.
8680 The return value of the event procedure is ignored since there is no
8681 way of indicating a failure from <xref linkend="libpq-PQclear"/>. Also,
8682 an event procedure failure should not abort the process of cleaning up
8683 unwanted memory.
8684 </para>
8685 </listitem>
8686 </varlistentry>
8687 </variablelist>
8688 </sect2>
8689
8690 <sect2 id="libpq-events-proc">
8691 <title>Event Callback Procedure</title>
8692
8693 <variablelist>
8694 <varlistentry id="libpq-PGEventProc">
8695 <term><literal>PGEventProc</literal><indexterm><primary>PGEventProc</primary></indexterm></term>
8696
8697 <listitem>
8698 <para>
8699 <literal>PGEventProc</literal> is a typedef for a pointer to an
8700 event procedure, that is, the user callback function that receives
8701 events from libpq. The signature of an event procedure must be
8702
8703 <synopsis>
8704 int eventproc(PGEventId evtId, void *evtInfo, void *passThrough)
8705 </synopsis>
8706
8707 The <parameter>evtId</parameter> parameter indicates which
8708 <literal>PGEVT</literal> event occurred. The
8709 <parameter>evtInfo</parameter> pointer must be cast to the appropriate
8710 structure type to obtain further information about the event.
8711 The <parameter>passThrough</parameter> parameter is the pointer
8712 provided to <xref linkend="libpq-PQregisterEventProc"/> when the event
8713 procedure was registered. The function should return a non-zero value
8714 if it succeeds and zero if it fails.
8715 </para>
8716
8717 <para>
8718 A particular event procedure can be registered only once in any
8719 <structname>PGconn</structname>. This is because the address of the procedure
8720 is used as a lookup key to identify the associated instance data.
8721 </para>
8722
8723 <caution>
8724 <para>
8725 On Windows, functions can have two different addresses: one visible
8726 from outside a DLL and another visible from inside the DLL. One
8727 should be careful that only one of these addresses is used with
8728 <application>libpq</application>'s event-procedure functions, else confusion will
8729 result. The simplest rule for writing code that will work is to
8730 ensure that event procedures are declared <literal>static</literal>. If the
8731 procedure's address must be available outside its own source file,
8732 expose a separate function to return the address.
8733 </para>
8734 </caution>
8735 </listitem>
8736 </varlistentry>
8737 </variablelist>
8738 </sect2>
8739
8740 <sect2 id="libpq-events-funcs">
8741 <title>Event Support Functions</title>
8742
8743 <variablelist>
8744 <varlistentry id="libpq-PQregisterEventProc">
8745 <term><function>PQregisterEventProc</function><indexterm><primary>PQregisterEventProc</primary></indexterm></term>
8746
8747 <listitem>
8748 <para>
8749 Registers an event callback procedure with libpq.
8750
8751 <synopsis>
8752 int PQregisterEventProc(PGconn *conn, PGEventProc proc,
8753 const char *name, void *passThrough);
8754 </synopsis>
8755 </para>
8756
8757 <para>
8758 An event procedure must be registered once on each
8759 <structname>PGconn</structname> you want to receive events about. There is no
8760 limit, other than memory, on the number of event procedures that
8761 can be registered with a connection. The function returns a non-zero
8762 value if it succeeds and zero if it fails.
8763 </para>
8764
8765 <para>
8766 The <parameter>proc</parameter> argument will be called when a libpq
8767 event is fired. Its memory address is also used to lookup
8768 <literal>instanceData</literal>. The <parameter>name</parameter>
8769 argument is used to refer to the event procedure in error messages.
8770 This value cannot be <symbol>NULL</symbol> or a zero-length string. The name string is
8771 copied into the <structname>PGconn</structname>, so what is passed need not be
8772 long-lived. The <parameter>passThrough</parameter> pointer is passed
8773 to the <parameter>proc</parameter> whenever an event occurs. This
8774 argument can be <symbol>NULL</symbol>.
8775 </para>
8776 </listitem>
8777 </varlistentry>
8778
8779 <varlistentry id="libpq-PQsetInstanceData">
8780 <term><function>PQsetInstanceData</function><indexterm><primary>PQsetInstanceData</primary></indexterm></term>
8781 <listitem>
8782 <para>
8783 Sets the connection <parameter>conn</parameter>'s <literal>instanceData</literal>
8784 for procedure <parameter>proc</parameter> to <parameter>data</parameter>. This
8785 returns non-zero for success and zero for failure. (Failure is
8786 only possible if <parameter>proc</parameter> has not been properly
8787 registered in <parameter>conn</parameter>.)
8788
8789 <synopsis>
8790 int PQsetInstanceData(PGconn *conn, PGEventProc proc, void *data);
8791 </synopsis>
8792 </para>
8793 </listitem>
8794 </varlistentry>
8795
8796 <varlistentry id="libpq-PQinstanceData">
8797 <term><function>PQinstanceData</function><indexterm><primary>PQinstanceData</primary></indexterm></term>
8798 <listitem>
8799 <para>
8800 Returns the
8801 connection <parameter>conn</parameter>'s <literal>instanceData</literal>
8802 associated with procedure <parameter>proc</parameter>,
8803 or <symbol>NULL</symbol> if there is none.
8804
8805 <synopsis>
8806 void *PQinstanceData(const PGconn *conn, PGEventProc proc);
8807 </synopsis>
8808 </para>
8809 </listitem>
8810 </varlistentry>
8811
8812 <varlistentry id="libpq-PQresultSetInstanceData">
8813 <term><function>PQresultSetInstanceData</function><indexterm><primary>PQresultSetInstanceData</primary></indexterm></term>
8814 <listitem>
8815 <para>
8816 Sets the result's <literal>instanceData</literal>
8817 for <parameter>proc</parameter> to <parameter>data</parameter>. This returns
8818 non-zero for success and zero for failure. (Failure is only
8819 possible if <parameter>proc</parameter> has not been properly registered
8820 in the result.)
8821
8822 <synopsis>
8823 int PQresultSetInstanceData(PGresult *res, PGEventProc proc, void *data);
8824 </synopsis>
8825 </para>
8826
8827 <para>
8828 Beware that any storage represented by <parameter>data</parameter>
8829 will not be accounted for by <xref linkend="libpq-PQresultMemorySize"/>,
8830 unless it is allocated using <xref linkend="libpq-PQresultAlloc"/>.
8831 (Doing so is recommendable because it eliminates the need to free
8832 such storage explicitly when the result is destroyed.)
8833 </para>
8834 </listitem>
8835 </varlistentry>
8836
8837 <varlistentry id="libpq-PQresultInstanceData">
8838 <term><function>PQresultInstanceData</function><indexterm><primary>PQresultInstanceData</primary></indexterm></term>
8839 <listitem>
8840 <para>
8841 Returns the result's <literal>instanceData</literal> associated with <parameter>proc</parameter>, or <symbol>NULL</symbol>
8842 if there is none.
8843
8844 <synopsis>
8845 void *PQresultInstanceData(const PGresult *res, PGEventProc proc);
8846 </synopsis>
8847 </para>
8848 </listitem>
8849 </varlistentry>
8850 </variablelist>
8851 </sect2>
8852
8853 <sect2 id="libpq-events-example">
8854 <title>Event Example</title>
8855
8856 <para>
8857 Here is a skeleton example of managing private data associated with
8858 libpq connections and results.
8859 </para>
8860
8861 <programlisting>
8862 <![CDATA[
8863 /* required header for libpq events (note: includes libpq-fe.h) */
8864 #include <libpq-events.h>
8865
8866 /* The instanceData */
8867 typedef struct
8868 {
8869 int n;
8870 char *str;
8871 } mydata;
8872
8873 /* PGEventProc */
8874 static int myEventProc(PGEventId evtId, void *evtInfo, void *passThrough);
8875
8876 int
8877 main(void)
8878 {
8879 mydata *data;
8880 PGresult *res;
8881 PGconn *conn =
8882 PQconnectdb("dbname=postgres options=-csearch_path=");
8883
8884 if (PQstatus(conn) != CONNECTION_OK)
8885 {
8886 /* PQerrorMessage's result includes a trailing newline */
8887 fprintf(stderr, "%s", PQerrorMessage(conn));
8888 PQfinish(conn);
8889 return 1;
8890 }
8891
8892 /* called once on any connection that should receive events.
8893 * Sends a PGEVT_REGISTER to myEventProc.
8894 */
8895 if (!PQregisterEventProc(conn, myEventProc, "mydata_proc", NULL))
8896 {
8897 fprintf(stderr, "Cannot register PGEventProc\n");
8898 PQfinish(conn);
8899 return 1;
8900 }
8901
8902 /* conn instanceData is available */
8903 data = PQinstanceData(conn, myEventProc);
8904
8905 /* Sends a PGEVT_RESULTCREATE to myEventProc */
8906 res = PQexec(conn, "SELECT 1 + 1");
8907
8908 /* result instanceData is available */
8909 data = PQresultInstanceData(res, myEventProc);
8910
8911 /* If PG_COPYRES_EVENTS is used, sends a PGEVT_RESULTCOPY to myEventProc */
8912 res_copy = PQcopyResult(res, PG_COPYRES_TUPLES | PG_COPYRES_EVENTS);
8913
8914 /* result instanceData is available if PG_COPYRES_EVENTS was
8915 * used during the PQcopyResult call.
8916 */
8917 data = PQresultInstanceData(res_copy, myEventProc);
8918
8919 /* Both clears send a PGEVT_RESULTDESTROY to myEventProc */
8920 PQclear(res);
8921 PQclear(res_copy);
8922
8923 /* Sends a PGEVT_CONNDESTROY to myEventProc */
8924 PQfinish(conn);
8925
8926 return 0;
8927 }
8928
8929 static int
8930 myEventProc(PGEventId evtId, void *evtInfo, void *passThrough)
8931 {
8932 switch (evtId)
8933 {
8934 case PGEVT_REGISTER:
8935 {
8936 PGEventRegister *e = (PGEventRegister *)evtInfo;
8937 mydata *data = get_mydata(e->conn);
8938
8939 /* associate app specific data with connection */
8940 PQsetInstanceData(e->conn, myEventProc, data);
8941 break;
8942 }
8943
8944 case PGEVT_CONNRESET:
8945 {
8946 PGEventConnReset *e = (PGEventConnReset *)evtInfo;
8947 mydata *data = PQinstanceData(e->conn, myEventProc);
8948
8949 if (data)
8950 memset(data, 0, sizeof(mydata));
8951 break;
8952 }
8953
8954 case PGEVT_CONNDESTROY:
8955 {
8956 PGEventConnDestroy *e = (PGEventConnDestroy *)evtInfo;
8957 mydata *data = PQinstanceData(e->conn, myEventProc);
8958
8959 /* free instance data because the conn is being destroyed */
8960 if (data)
8961 free_mydata(data);
8962 break;
8963 }
8964
8965 case PGEVT_RESULTCREATE:
8966 {
8967 PGEventResultCreate *e = (PGEventResultCreate *)evtInfo;
8968 mydata *conn_data = PQinstanceData(e->conn, myEventProc);
8969 mydata *res_data = dup_mydata(conn_data);
8970
8971 /* associate app specific data with result (copy it from conn) */
8972 PQresultSetInstanceData(e->result, myEventProc, res_data);
8973 break;
8974 }
8975
8976 case PGEVT_RESULTCOPY:
8977 {
8978 PGEventResultCopy *e = (PGEventResultCopy *)evtInfo;
8979 mydata *src_data = PQresultInstanceData(e->src, myEventProc);
8980 mydata *dest_data = dup_mydata(src_data);
8981
8982 /* associate app specific data with result (copy it from a result) */
8983 PQresultSetInstanceData(e->dest, myEventProc, dest_data);
8984 break;
8985 }
8986
8987 case PGEVT_RESULTDESTROY:
8988 {
8989 PGEventResultDestroy *e = (PGEventResultDestroy *)evtInfo;
8990 mydata *data = PQresultInstanceData(e->result, myEventProc);
8991
8992 /* free instance data because the result is being destroyed */
8993 if (data)
8994 free_mydata(data);
8995 break;
8996 }
8997
8998 /* unknown event ID, just return true. */
8999 default:
9000 break;
9001 }
9002
9003 return true; /* event processing succeeded */
9004 }
9005 ]]>
9006 </programlisting>
9007 </sect2>
9008 </sect1>
9009
9010 <sect1 id="libpq-envars">
9011 <title>Environment Variables</title>
9012
9013 <indexterm zone="libpq-envars">
9014 <primary>environment variable</primary>
9015 </indexterm>
9016
9017 <para>
9018 The following environment variables can be used to select default
9019 connection parameter values, which will be used by
9020 <xref linkend="libpq-PQconnectdb"/>, <xref linkend="libpq-PQsetdbLogin"/> and
9021 <xref linkend="libpq-PQsetdb"/> if no value is directly specified by the calling
9022 code. These are useful to avoid hard-coding database connection
9023 information into simple client applications, for example.
9024
9025 <itemizedlist>
9026 <listitem>
9027 <para>
9028 <indexterm>
9029 <primary><envar>PGHOST</envar></primary>
9030 </indexterm>
9031 <envar>PGHOST</envar> behaves the same as the <xref
9032 linkend="libpq-connect-host"/> connection parameter.
9033 </para>
9034 </listitem>
9035
9036 <listitem>
9037 <para>
9038 <indexterm>
9039 <primary><envar>PGSSLNEGOTIATION</envar></primary>
9040 </indexterm>
9041 <envar>PGSSLNEGOTIATION</envar> behaves the same as the <xref
9042 linkend="libpq-connect-sslnegotiation"/> connection parameter.
9043 </para>
9044 </listitem>
9045
9046 <listitem>
9047 <para>
9048 <indexterm>
9049 <primary><envar>PGHOSTADDR</envar></primary>
9050 </indexterm>
9051 <envar>PGHOSTADDR</envar> behaves the same as the <xref
9052 linkend="libpq-connect-hostaddr"/> connection parameter.
9053 This can be set instead of or in addition to <envar>PGHOST</envar>
9054 to avoid DNS lookup overhead.
9055 </para>
9056 </listitem>
9057
9058 <listitem>
9059 <para>
9060 <indexterm>
9061 <primary><envar>PGPORT</envar></primary>
9062 </indexterm>
9063 <envar>PGPORT</envar> behaves the same as the <xref
9064 linkend="libpq-connect-port"/> connection parameter.
9065 </para>
9066 </listitem>
9067
9068 <listitem>
9069 <para>
9070 <indexterm>
9071 <primary><envar>PGDATABASE</envar></primary>
9072 </indexterm>
9073 <envar>PGDATABASE</envar> behaves the same as the <xref
9074 linkend="libpq-connect-dbname"/> connection parameter.
9075 </para>
9076 </listitem>
9077
9078 <listitem>
9079 <para>
9080 <indexterm>
9081 <primary><envar>PGUSER</envar></primary>
9082 </indexterm>
9083 <envar>PGUSER</envar> behaves the same as the <xref
9084 linkend="libpq-connect-user"/> connection parameter.
9085 </para>
9086 </listitem>
9087
9088 <listitem>
9089 <para>
9090 <indexterm>
9091 <primary><envar>PGPASSWORD</envar></primary>
9092 </indexterm>
9093 <envar>PGPASSWORD</envar> behaves the same as the <xref
9094 linkend="libpq-connect-password"/> connection parameter.
9095 Use of this environment variable
9096 is not recommended for security reasons, as some operating systems
9097 allow non-root users to see process environment variables via
9098 <application>ps</application>; instead consider using a password file
9099 (see <xref linkend="libpq-pgpass"/>).
9100 </para>
9101 </listitem>
9102
9103 <listitem>
9104 <para>
9105 <indexterm>
9106 <primary><envar>PGPASSFILE</envar></primary>
9107 </indexterm>
9108 <envar>PGPASSFILE</envar> behaves the same as the <xref
9109 linkend="libpq-connect-passfile"/> connection parameter.
9110 </para>
9111 </listitem>
9112
9113 <listitem>
9114 <para>
9115 <indexterm>
9116 <primary><envar>PGREQUIREAUTH</envar></primary>
9117 </indexterm>
9118 <envar>PGREQUIREAUTH</envar> behaves the same as the <xref
9119 linkend="libpq-connect-require-auth"/> connection parameter.
9120 </para>
9121 </listitem>
9122
9123 <listitem>
9124 <para>
9125 <indexterm>
9126 <primary><envar>PGCHANNELBINDING</envar></primary>
9127 </indexterm>
9128 <envar>PGCHANNELBINDING</envar> behaves the same as the <xref
9129 linkend="libpq-connect-channel-binding"/> connection parameter.
9130 </para>
9131 </listitem>
9132
9133 <listitem>
9134 <para>
9135 <indexterm>
9136 <primary><envar>PGSERVICE</envar></primary>
9137 </indexterm>
9138 <envar>PGSERVICE</envar> behaves the same as the <xref
9139 linkend="libpq-connect-service"/> connection parameter.
9140 </para>
9141 </listitem>
9142
9143 <listitem>
9144 <para>
9145 <indexterm>
9146 <primary><envar>PGSERVICEFILE</envar></primary>
9147 </indexterm>
9148 <envar>PGSERVICEFILE</envar> specifies the name of the per-user
9149 connection service file
9150 (see <xref linkend="libpq-pgservice"/>).
9151 Defaults to <filename>~/.pg_service.conf</filename>, or
9152 <filename>%APPDATA%\postgresql\.pg_service.conf</filename> on
9153 Microsoft Windows.
9154 </para>
9155 </listitem>
9156
9157 <listitem>
9158 <para>
9159 <indexterm>
9160 <primary><envar>PGOPTIONS</envar></primary>
9161 </indexterm>
9162 <envar>PGOPTIONS</envar> behaves the same as the <xref
9163 linkend="libpq-connect-options"/> connection parameter.
9164 </para>
9165 </listitem>
9166
9167 <listitem>
9168 <para>
9169 <indexterm>
9170 <primary><envar>PGAPPNAME</envar></primary>
9171 </indexterm>
9172 <envar>PGAPPNAME</envar> behaves the same as the <xref
9173 linkend="libpq-connect-application-name"/> connection parameter.
9174 </para>
9175 </listitem>
9176
9177 <listitem>
9178 <para>
9179 <indexterm>
9180 <primary><envar>PGSSLMODE</envar></primary>
9181 </indexterm>
9182 <envar>PGSSLMODE</envar> behaves the same as the <xref
9183 linkend="libpq-connect-sslmode"/> connection parameter.
9184 </para>
9185 </listitem>
9186
9187 <listitem>
9188 <para>
9189 <indexterm>
9190 <primary><envar>PGREQUIRESSL</envar></primary>
9191 </indexterm>
9192 <envar>PGREQUIRESSL</envar> behaves the same as the <xref
9193 linkend="libpq-connect-requiressl"/> connection parameter.
9194 This environment variable is deprecated in favor of the
9195 <envar>PGSSLMODE</envar> variable; setting both variables suppresses the
9196 effect of this one.
9197 </para>
9198 </listitem>
9199
9200 <listitem>
9201 <para>
9202 <indexterm>
9203 <primary><envar>PGSSLCOMPRESSION</envar></primary>
9204 </indexterm>
9205 <envar>PGSSLCOMPRESSION</envar> behaves the same as the <xref
9206 linkend="libpq-connect-sslcompression"/> connection parameter.
9207 </para>
9208 </listitem>
9209
9210 <listitem>
9211 <para>
9212 <indexterm>
9213 <primary><envar>PGSSLCERT</envar></primary>
9214 </indexterm>
9215 <envar>PGSSLCERT</envar> behaves the same as the <xref
9216 linkend="libpq-connect-sslcert"/> connection parameter.
9217 </para>
9218 </listitem>
9219
9220 <listitem>
9221 <para>
9222 <indexterm>
9223 <primary><envar>PGSSLKEY</envar></primary>
9224 </indexterm>
9225 <envar>PGSSLKEY</envar> behaves the same as the <xref
9226 linkend="libpq-connect-sslkey"/> connection parameter.
9227 </para>
9228 </listitem>
9229
9230 <listitem>
9231 <para>
9232 <indexterm>
9233 <primary><envar>PGSSLCERTMODE</envar></primary>
9234 </indexterm>
9235 <envar>PGSSLCERTMODE</envar> behaves the same as the <xref
9236 linkend="libpq-connect-sslcertmode"/> connection parameter.
9237 </para>
9238 </listitem>
9239
9240 <listitem>
9241 <para>
9242 <indexterm>
9243 <primary><envar>PGSSLROOTCERT</envar></primary>
9244 </indexterm>
9245 <envar>PGSSLROOTCERT</envar> behaves the same as the <xref
9246 linkend="libpq-connect-sslrootcert"/> connection parameter.
9247 </para>
9248 </listitem>
9249
9250 <listitem>
9251 <para>
9252 <indexterm>
9253 <primary><envar>PGSSLCRL</envar></primary>
9254 </indexterm>
9255 <envar>PGSSLCRL</envar> behaves the same as the <xref
9256 linkend="libpq-connect-sslcrl"/> connection parameter.
9257 </para>
9258 </listitem>
9259
9260 <listitem>
9261 <para>
9262 <indexterm>
9263 <primary><envar>PGSSLCRLDIR</envar></primary>
9264 </indexterm>
9265 <envar>PGSSLCRLDIR</envar> behaves the same as the <xref
9266 linkend="libpq-connect-sslcrldir"/> connection parameter.
9267 </para>
9268 </listitem>
9269
9270 <listitem>
9271 <para>
9272 <indexterm>
9273 <primary><envar>PGSSLSNI</envar></primary>
9274 </indexterm>
9275 <envar>PGSSLSNI</envar> behaves the same as the <xref
9276 linkend="libpq-connect-sslsni"/> connection parameter.
9277 </para>
9278 </listitem>
9279
9280 <listitem>
9281 <para>
9282 <indexterm>
9283 <primary><envar>PGREQUIREPEER</envar></primary>
9284 </indexterm>
9285 <envar>PGREQUIREPEER</envar> behaves the same as the <xref
9286 linkend="libpq-connect-requirepeer"/> connection parameter.
9287 </para>
9288 </listitem>
9289
9290 <listitem>
9291 <para>
9292 <indexterm>
9293 <primary><envar>PGSSLMINPROTOCOLVERSION</envar></primary>
9294 </indexterm>
9295 <envar>PGSSLMINPROTOCOLVERSION</envar> behaves the same as the <xref
9296 linkend="libpq-connect-ssl-min-protocol-version"/> connection parameter.
9297 </para>
9298 </listitem>
9299
9300 <listitem>
9301 <para>
9302 <indexterm>
9303 <primary><envar>PGSSLMAXPROTOCOLVERSION</envar></primary>
9304 </indexterm>
9305 <envar>PGSSLMAXPROTOCOLVERSION</envar> behaves the same as the <xref
9306 linkend="libpq-connect-ssl-max-protocol-version"/> connection parameter.
9307 </para>
9308 </listitem>
9309
9310 <listitem>
9311 <para>
9312 <indexterm>
9313 <primary><envar>PGGSSENCMODE</envar></primary>
9314 </indexterm>
9315 <envar>PGGSSENCMODE</envar> behaves the same as the <xref
9316 linkend="libpq-connect-gssencmode"/> connection parameter.
9317 </para>
9318 </listitem>
9319
9320 <listitem>
9321 <para>
9322 <indexterm>
9323 <primary><envar>PGKRBSRVNAME</envar></primary>
9324 </indexterm>
9325 <envar>PGKRBSRVNAME</envar> behaves the same as the <xref
9326 linkend="libpq-connect-krbsrvname"/> connection parameter.
9327 </para>
9328 </listitem>
9329
9330 <listitem>
9331 <para>
9332 <indexterm>
9333 <primary><envar>PGGSSLIB</envar></primary>
9334 </indexterm>
9335 <envar>PGGSSLIB</envar> behaves the same as the <xref
9336 linkend="libpq-connect-gsslib"/> connection parameter.
9337 </para>
9338 </listitem>
9339
9340 <listitem>
9341 <para>
9342 <indexterm>
9343 <primary><envar>PGGSSDELEGATION</envar></primary>
9344 </indexterm>
9345 <envar>PGGSSDELEGATION</envar> behaves the same as the <xref
9346 linkend="libpq-connect-gssdelegation"/> connection parameter.
9347 </para>
9348 </listitem>
9349
9350 <listitem>
9351 <para>
9352 <indexterm>
9353 <primary><envar>PGCONNECT_TIMEOUT</envar></primary>
9354 </indexterm>
9355 <envar>PGCONNECT_TIMEOUT</envar> behaves the same as the <xref
9356 linkend="libpq-connect-connect-timeout"/> connection parameter.
9357 </para>
9358 </listitem>
9359
9360 <listitem>
9361 <para>
9362 <indexterm>
9363 <primary><envar>PGCLIENTENCODING</envar></primary>
9364 </indexterm>
9365 <envar>PGCLIENTENCODING</envar> behaves the same as the <xref
9366 linkend="libpq-connect-client-encoding"/> connection parameter.
9367 </para>
9368 </listitem>
9369
9370 <listitem>
9371 <para>
9372 <indexterm>
9373 <primary><envar>PGTARGETSESSIONATTRS</envar></primary>
9374 </indexterm>
9375 <envar>PGTARGETSESSIONATTRS</envar> behaves the same as the <xref
9376 linkend="libpq-connect-target-session-attrs"/> connection parameter.
9377 </para>
9378 </listitem>
9379
9380 <listitem>
9381 <para>
9382 <indexterm>
9383 <primary><envar>PGLOADBALANCEHOSTS</envar></primary>
9384 </indexterm>
9385 <envar>PGLOADBALANCEHOSTS</envar> behaves the same as the <xref
9386 linkend="libpq-connect-load-balance-hosts"/> connection parameter.
9387 </para>
9388 </listitem>
9389
9390 <listitem>
9391 <para>
9392 <indexterm>
9393 <primary><envar>PGMINPROTOCOLVERSION</envar></primary>
9394 </indexterm>
9395 <envar>PGMINPROTOCOLVERSION</envar> behaves the same as the <xref
9396 linkend="libpq-connect-min-protocol-version"/> connection parameter.
9397 </para>
9398 </listitem>
9399
9400 <listitem>
9401 <para>
9402 <indexterm>
9403 <primary><envar>PGMAXPROTOCOLVERSION</envar></primary>
9404 </indexterm>
9405 <envar>PGMAXPROTOCOLVERSION</envar> behaves the same as the <xref
9406 linkend="libpq-connect-max-protocol-version"/> connection parameter.
9407 </para>
9408 </listitem>
9409 </itemizedlist>
9410 </para>
9411
9412 <para>
9413 The following environment variables can be used to specify default
9414 behavior for each <productname>PostgreSQL</productname> session. (See
9415 also the <xref linkend="sql-alterrole"/>
9416 and <xref linkend="sql-alterdatabase"/>
9417 commands for ways to set default behavior on a per-user or per-database
9418 basis.)
9419
9420 <itemizedlist>
9421 <listitem>
9422 <para>
9423 <indexterm>
9424 <primary><envar>PGDATESTYLE</envar></primary>
9425 </indexterm>
9426 <envar>PGDATESTYLE</envar> sets the default style of date/time
9427 representation. (Equivalent to <literal>SET datestyle TO
9428 ...</literal>.)
9429 </para>
9430 </listitem>
9431
9432 <listitem>
9433 <para>
9434 <indexterm>
9435 <primary><envar>PGTZ</envar></primary>
9436 </indexterm>
9437 <envar>PGTZ</envar> sets the default time zone. (Equivalent to
9438 <literal>SET timezone TO ...</literal>.)
9439 </para>
9440 </listitem>
9441
9442 <listitem>
9443 <para>
9444 <indexterm>
9445 <primary><envar>PGGEQO</envar></primary>
9446 </indexterm>
9447 <envar>PGGEQO</envar> sets the default mode for the genetic query
9448 optimizer. (Equivalent to <literal>SET geqo TO ...</literal>.)
9449 </para>
9450 </listitem>
9451 </itemizedlist>
9452
9453 Refer to the <acronym>SQL</acronym> command <xref linkend="sql-set"/>
9454 for information on correct values for these
9455 environment variables.
9456 </para>
9457
9458 <para>
9459 The following environment variables determine internal behavior of
9460 <application>libpq</application>; they override compiled-in defaults.
9461
9462 <itemizedlist>
9463 <listitem>
9464 <para>
9465 <indexterm>
9466 <primary><envar>PGSYSCONFDIR</envar></primary>
9467 </indexterm>
9468 <envar>PGSYSCONFDIR</envar> sets the directory containing the
9469 <filename>pg_service.conf</filename> file and in a future version
9470 possibly other system-wide configuration files.
9471 </para>
9472 </listitem>
9473
9474 <listitem>
9475 <para>
9476 <indexterm>
9477 <primary><envar>PGLOCALEDIR</envar></primary>
9478 </indexterm>
9479 <envar>PGLOCALEDIR</envar> sets the directory containing the
9480 <literal>locale</literal> files for message localization.
9481 </para>
9482 </listitem>
9483 </itemizedlist>
9484 </para>
9485
9486 </sect1>
9487
9488
9489 <sect1 id="libpq-pgpass">
9490 <title>The Password File</title>
9491
9492 <indexterm zone="libpq-pgpass">
9493 <primary>password file</primary>
9494 </indexterm>
9495 <indexterm zone="libpq-pgpass">
9496 <primary>.pgpass</primary>
9497 </indexterm>
9498
9499 <para>
9500 The file <filename>.pgpass</filename> in a user's home directory can
9501 contain passwords to
9502 be used if the connection requires a password (and no password has been
9503 specified otherwise). On Unix systems, the directory can be specified by
9504 the <envar>HOME</envar> environment variable, or if undefined, the home
9505 directory of the effective user. On Microsoft Windows the file is named
9506 <filename>%APPDATA%\postgresql\pgpass.conf</filename> (where
9507 <filename>%APPDATA%</filename> refers to the Application Data subdirectory in
9508 the user's profile).
9509 Alternatively, the password file to use can be specified
9510 using the connection parameter <xref linkend="libpq-connect-passfile"/>
9511 or the environment variable <envar>PGPASSFILE</envar>.
9512 </para>
9513
9514 <para>
9515 This file should contain lines of the following format:
9516 <synopsis>
9517 <replaceable>hostname</replaceable>:<replaceable>port</replaceable>:<replaceable>database</replaceable>:<replaceable>username</replaceable>:<replaceable>password</replaceable>
9518 </synopsis>
9519 (You can add a reminder comment to the file by copying the line above and
9520 preceding it with <literal>#</literal>.)
9521 Each of the first four fields can be a literal value, or
9522 <literal>*</literal>, which matches anything. The password field from
9523 the first line that matches the current connection parameters will be
9524 used. (Therefore, put more-specific entries first when you are using
9525 wildcards.) If an entry needs to contain <literal>:</literal> or
9526 <literal>\</literal>, escape this character with <literal>\</literal>.
9527 The host name field is matched to the <literal>host</literal> connection
9528 parameter if that is specified, otherwise to
9529 the <literal>hostaddr</literal> parameter if that is specified; if neither
9530 are given then the host name <literal>localhost</literal> is searched for.
9531 The host name <literal>localhost</literal> is also searched for when
9532 the connection is a Unix-domain socket connection and
9533 the <literal>host</literal> parameter
9534 matches <application>libpq</application>'s default socket directory path.
9535 In a standby server, a database field of <literal>replication</literal>
9536 matches streaming replication connections made to the primary server.
9537 The database field is of limited usefulness otherwise, because users have
9538 the same password for all databases in the same cluster.
9539 </para>
9540
9541 <para>
9542 On Unix systems, the permissions on a password file must
9543 disallow any access to world or group; achieve this by a command such as
9544 <command>chmod 0600 ~/.pgpass</command>. If the permissions are less
9545 strict than this, the file will be ignored. On Microsoft Windows, it
9546 is assumed that the file is stored in a directory that is secure, so
9547 no special permissions check is made.
9548 </para>
9549 </sect1>
9550
9551
9552 <sect1 id="libpq-pgservice">
9553 <title>The Connection Service File</title>
9554
9555 <indexterm zone="libpq-pgservice">
9556 <primary>connection service file</primary>
9557 </indexterm>
9558 <indexterm zone="libpq-pgservice">
9559 <primary>pg_service.conf</primary>
9560 </indexterm>
9561 <indexterm zone="libpq-pgservice">
9562 <primary>.pg_service.conf</primary>
9563 </indexterm>
9564
9565 <para>
9566 The connection service file allows libpq connection parameters to be
9567 associated with a single service name. That service name can then be
9568 specified using the <literal>service</literal> key word
9569 in a libpq connection string, and the associated settings will be
9570 used. This allows connection parameters to be modified without requiring
9571 a recompile of the libpq-using application. The service name can also be
9572 specified using the <envar>PGSERVICE</envar> environment variable.
9573 </para>
9574
9575 <para>
9576 Service names can be defined in either a per-user service file or a
9577 system-wide file. If the same service name exists in both the user
9578 and the system file, the user file takes precedence.
9579 By default, the per-user service file is named
9580 <filename>~/.pg_service.conf</filename>.
9581 On Microsoft Windows, it is named
9582 <filename>%APPDATA%\postgresql\.pg_service.conf</filename> (where
9583 <filename>%APPDATA%</filename> refers to the Application Data subdirectory
9584 in the user's profile). A different file name can be specified by
9585 setting the environment variable <envar>PGSERVICEFILE</envar>.
9586 The system-wide file is named <filename>pg_service.conf</filename>.
9587 By default it is sought in the <filename>etc</filename> directory
9588 of the <productname>PostgreSQL</productname> installation
9589 (use <literal>pg_config --sysconfdir</literal> to identify this
9590 directory precisely). Another directory, but not a different file
9591 name, can be specified by setting the environment variable
9592 <envar>PGSYSCONFDIR</envar>.
9593 </para>
9594
9595 <para>
9596 Either service file uses an <quote>INI file</quote> format where the section
9597 name is the service name and the parameters are connection
9598 parameters; see <xref linkend="libpq-paramkeywords"/> for a list. For
9599 example:
9600 <programlisting>
9601 # comment
9602 [mydb]
9603 host=somehost
9604 port=5433
9605 user=admin
9606 </programlisting>
9607 An example file is provided in
9608 the <productname>PostgreSQL</productname> installation at
9609 <filename>share/pg_service.conf.sample</filename>.
9610 </para>
9611
9612 <para>
9613 Connection parameters obtained from a service file are combined with
9614 parameters obtained from other sources. A service file setting
9615 overrides the corresponding environment variable, and in turn can be
9616 overridden by a value given directly in the connection string.
9617 For example, using the above service file, a connection string
9618 <literal>service=mydb port=5434</literal> will use
9619 host <literal>somehost</literal>, port <literal>5434</literal>,
9620 user <literal>admin</literal>, and other parameters as set by
9621 environment variables or built-in defaults.
9622 </para>
9623 </sect1>
9624
9625
9626 <sect1 id="libpq-ldap">
9627 <title>LDAP Lookup of Connection Parameters</title>
9628
9629 <indexterm zone="libpq-ldap">
9630 <primary>LDAP connection parameter lookup</primary>
9631 </indexterm>
9632
9633 <para>
9634 If <application>libpq</application> has been compiled with LDAP support (option
9635 <literal><option>--with-ldap</option></literal> for <command>configure</command>)
9636 it is possible to retrieve connection options like <literal>host</literal>
9637 or <literal>dbname</literal> via LDAP from a central server.
9638 The advantage is that if the connection parameters for a database change,
9639 the connection information doesn't have to be updated on all client machines.
9640 </para>
9641
9642 <para>
9643 LDAP connection parameter lookup uses the connection service file
9644 <filename>pg_service.conf</filename> (see <xref
9645 linkend="libpq-pgservice"/>). A line in a
9646 <filename>pg_service.conf</filename> stanza that starts with
9647 <literal>ldap://</literal> will be recognized as an LDAP URL and an
9648 LDAP query will be performed. The result must be a list of
9649 <literal>keyword = value</literal> pairs which will be used to set
9650 connection options. The URL must conform to
9651 <ulink url="https://datatracker.ietf.org/doc/html/rfc1959">RFC 1959</ulink>
9652 and be of the form
9653 <synopsis>
9654 ldap://[<replaceable>hostname</replaceable>[:<replaceable>port</replaceable>]]/<replaceable>search_base</replaceable>?<replaceable>attribute</replaceable>?<replaceable>search_scope</replaceable>?<replaceable>filter</replaceable>
9655 </synopsis>
9656 where <replaceable>hostname</replaceable> defaults to
9657 <literal>localhost</literal> and <replaceable>port</replaceable>
9658 defaults to 389.
9659 </para>
9660
9661 <para>
9662 Processing of <filename>pg_service.conf</filename> is terminated after
9663 a successful LDAP lookup, but is continued if the LDAP server cannot
9664 be contacted. This is to provide a fallback with further LDAP URL
9665 lines that point to different LDAP servers, classical <literal>keyword
9666 = value</literal> pairs, or default connection options. If you would
9667 rather get an error message in this case, add a syntactically incorrect
9668 line after the LDAP URL.
9669 </para>
9670
9671 <para>
9672 A sample LDAP entry that has been created with the LDIF file
9673 <programlisting>
9674 version:1
9675 dn:cn=mydatabase,dc=mycompany,dc=com
9676 changetype:add
9677 objectclass:top
9678 objectclass:device
9679 cn:mydatabase
9680 description:host=dbserver.mycompany.com
9681 description:port=5439
9682 description:dbname=mydb
9683 description:user=mydb_user
9684 description:sslmode=require
9685 </programlisting>
9686 might be queried with the following LDAP URL:
9687 <programlisting>
9688 ldap://ldap.mycompany.com/dc=mycompany,dc=com?description?one?(cn=mydatabase)
9689 </programlisting>
9690 </para>
9691
9692 <para>
9693 You can also mix regular service file entries with LDAP lookups.
9694 A complete example for a stanza in <filename>pg_service.conf</filename>
9695 would be:
9696 <programlisting>
9697 # only host and port are stored in LDAP, specify dbname and user explicitly
9698 [customerdb]
9699 dbname=customer
9700 user=appuser
9701 ldap://ldap.acme.com/cn=dbserver,cn=hosts?pgconnectinfo?base?(objectclass=*)
9702 </programlisting>
9703 </para>
9704
9705 </sect1>
9706
9707
9708 <sect1 id="libpq-ssl">
9709 <title>SSL Support</title>
9710
9711 <indexterm zone="libpq-ssl">
9712 <primary>SSL</primary>
9713 <secondary>TLS</secondary>
9714 </indexterm>
9715
9716 <para>
9717 <productname>PostgreSQL</productname> has native support for using <acronym>SSL</acronym>
9718 connections to encrypt client/server communications using
9719 <acronym>TLS</acronym> protocols for increased security.
9720 See <xref linkend="ssl-tcp"/> for details about the server-side
9721 <acronym>SSL</acronym> functionality.
9722 </para>
9723
9724 <para>
9725 <application>libpq</application> reads the system-wide
9726 <productname>OpenSSL</productname> configuration file. By default, this
9727 file is named <filename>openssl.cnf</filename> and is located in the
9728 directory reported by <literal>openssl version -d</literal>. This default
9729 can be overridden by setting environment variable
9730 <envar>OPENSSL_CONF</envar> to the name of the desired configuration
9731 file.
9732 </para>
9733
9734 <sect2 id="libq-ssl-certificates">
9735 <title>Client Verification of Server Certificates</title>
9736
9737 <para>
9738 By default, <productname>PostgreSQL</productname> will not perform any verification of
9739 the server certificate. This means that it is possible to spoof the server
9740 identity (for example by modifying a DNS record or by taking over the server
9741 IP address) without the client knowing. In order to prevent spoofing,
9742 the client must be able to verify the server's identity via a chain of
9743 trust. A chain of trust is established by placing a root (self-signed)
9744 certificate authority (<acronym>CA</acronym>) certificate on one
9745 computer and a leaf certificate <emphasis>signed</emphasis> by the
9746 root certificate on another computer. It is also possible to use an
9747 <quote>intermediate</quote> certificate which is signed by the root
9748 certificate and signs leaf certificates.
9749 </para>
9750
9751 <para>
9752 To allow the client to verify the identity of the server, place a root
9753 certificate on the client and a leaf certificate signed by the root
9754 certificate on the server. To allow the server to verify the identity
9755 of the client, place a root certificate on the server and a leaf
9756 certificate signed by the root certificate on the client. One or more
9757 intermediate certificates (usually stored with the leaf certificate)
9758 can also be used to link the leaf certificate to the root certificate.
9759 </para>
9760
9761 <para>
9762 Once a chain of trust has been established, there are two ways for
9763 the client to validate the leaf certificate sent by the server.
9764 If the parameter <literal>sslmode</literal> is set to <literal>verify-ca</literal>,
9765 libpq will verify that the server is trustworthy by checking the
9766 certificate chain up to the root certificate stored on the client.
9767 If <literal>sslmode</literal> is set to <literal>verify-full</literal>,
9768 libpq will <emphasis>also</emphasis> verify that the server host
9769 name matches the name stored in the server certificate. The
9770 SSL connection will fail if the server certificate cannot be
9771 verified. <literal>verify-full</literal> is recommended in most
9772 security-sensitive environments.
9773 </para>
9774
9775 <para>
9776 In <literal>verify-full</literal> mode, the host name is matched against the
9777 certificate's Subject Alternative Name attribute(s) (SAN), or against the
9778 Common Name attribute if no SAN of type <literal>dNSName</literal> is
9779 present. If the certificate's name attribute starts with an asterisk
9780 (<literal>*</literal>), the asterisk will be treated as
9781 a wildcard, which will match all characters <emphasis>except</emphasis> a dot
9782 (<literal>.</literal>). This means the certificate will not match subdomains.
9783 If the connection is made using an IP address instead of a host name, the
9784 IP address will be matched (without doing any DNS lookups) against SANs of
9785 type <literal>iPAddress</literal> or <literal>dNSName</literal>. If no
9786 <literal>iPAddress</literal> SAN is present and no
9787 matching <literal>dNSName</literal> SAN is present, the host IP address is
9788 matched against the Common Name attribute.
9789 </para>
9790
9791 <note>
9792 <para>
9793 For backward compatibility with earlier versions of PostgreSQL, the host
9794 IP address is verified in a manner different
9795 from <ulink url="https://datatracker.ietf.org/doc/html/rfc6125">RFC 6125</ulink>.
9796 The host IP address is always matched against <literal>dNSName</literal>
9797 SANs as well as <literal>iPAddress</literal> SANs, and can be matched
9798 against the Common Name attribute if no relevant SANs exist.
9799 </para>
9800 </note>
9801
9802 <para>
9803 To allow server certificate verification, one or more root certificates
9804 must be placed in the file <filename>~/.postgresql/root.crt</filename>
9805 in the user's home directory. (On Microsoft Windows the file is named
9806 <filename>%APPDATA%\postgresql\root.crt</filename>.) Intermediate
9807 certificates should also be added to the file if they are needed to link
9808 the certificate chain sent by the server to the root certificates
9809 stored on the client.
9810 </para>
9811
9812 <para>
9813 Certificate Revocation List (CRL) entries are also checked
9814 if the file <filename>~/.postgresql/root.crl</filename> exists
9815 (<filename>%APPDATA%\postgresql\root.crl</filename> on Microsoft
9816 Windows).
9817 </para>
9818
9819 <para>
9820 The location of the root certificate file and the CRL can be changed by
9821 setting
9822 the connection parameters <literal>sslrootcert</literal> and <literal>sslcrl</literal>
9823 or the environment variables <envar>PGSSLROOTCERT</envar> and <envar>PGSSLCRL</envar>.
9824 <literal>sslcrldir</literal> or the environment variable <envar>PGSSLCRLDIR</envar>
9825 can also be used to specify a directory containing CRL files.
9826 </para>
9827
9828 <note>
9829 <para>
9830 For backwards compatibility with earlier versions of PostgreSQL, if a
9831 root CA file exists, the behavior of
9832 <literal>sslmode=require</literal> will be the same
9833 as that of <literal>verify-ca</literal>, meaning the server certificate
9834 is validated against the CA. Relying on this behavior is discouraged,
9835 and applications that need certificate validation should always use
9836 <literal>verify-ca</literal> or <literal>verify-full</literal>.
9837 </para>
9838 </note>
9839 </sect2>
9840
9841 <sect2 id="libpq-ssl-clientcert">
9842 <title>Client Certificates</title>
9843
9844 <para>
9845 If the server attempts to verify the identity of the
9846 client by requesting the client's leaf certificate,
9847 <application>libpq</application> will send the certificate(s) stored in
9848 file <filename>~/.postgresql/postgresql.crt</filename> in the user's home
9849 directory. The certificates must chain to the root certificate trusted
9850 by the server. A matching
9851 private key file <filename>~/.postgresql/postgresql.key</filename> must also
9852 be present.
9853 On Microsoft Windows these files are named
9854 <filename>%APPDATA%\postgresql\postgresql.crt</filename> and
9855 <filename>%APPDATA%\postgresql\postgresql.key</filename>.
9856 The location of the certificate and key files can be overridden by the
9857 connection parameters <literal>sslcert</literal>
9858 and <literal>sslkey</literal>, or by the
9859 environment variables <envar>PGSSLCERT</envar> and <envar>PGSSLKEY</envar>.
9860 </para>
9861
9862 <para>
9863 On Unix systems, the permissions on the private key file must disallow
9864 any access to world or group; achieve this by a command such as
9865 <command>chmod 0600 ~/.postgresql/postgresql.key</command>.
9866 Alternatively, the file can be owned by root and have group read access
9867 (that is, <literal>0640</literal> permissions). That setup is intended
9868 for installations where certificate and key files are managed by the
9869 operating system. The user of <application>libpq</application> should
9870 then be made a member of the group that has access to those certificate
9871 and key files. (On Microsoft Windows, there is no file permissions
9872 check, since the <filename>%APPDATA%\postgresql</filename> directory is
9873 presumed secure.)
9874 </para>
9875
9876 <para>
9877 The first certificate in <filename>postgresql.crt</filename> must be the
9878 client's certificate because it must match the client's private key.
9879 <quote>Intermediate</quote> certificates can be optionally appended
9880 to the file &mdash; doing so avoids requiring storage of intermediate
9881 certificates on the server (<xref linkend="guc-ssl-ca-file"/>).
9882 </para>
9883
9884 <para>
9885 The certificate and key may be in PEM or ASN.1 DER format.
9886 </para>
9887
9888 <para>
9889 The key may be
9890 stored in cleartext or encrypted with a passphrase using any algorithm
9891 supported by <productname>OpenSSL</productname>, like AES-128. If the key
9892 is stored encrypted, then the passphrase may be provided in the
9893 <xref linkend="libpq-connect-sslpassword"/> connection option. If an
9894 encrypted key is supplied and the <literal>sslpassword</literal> option
9895 is absent or blank, a password will be prompted for interactively by
9896 <productname>OpenSSL</productname> with a
9897 <literal>Enter PEM pass phrase:</literal> prompt if a TTY is available.
9898 Applications can override the client certificate prompt and the handling
9899 of the <literal>sslpassword</literal> parameter by supplying their own
9900 key password callback; see
9901 <xref linkend="libpq-pqsetsslkeypasshook-openssl"/>.
9902 </para>
9903
9904 <para>
9905 For instructions on creating certificates, see <xref
9906 linkend="ssl-certificate-creation"/>.
9907 </para>
9908 </sect2>
9909
9910 <sect2 id="libpq-ssl-protection">
9911 <title>Protection Provided in Different Modes</title>
9912
9913 <para>
9914 The different values for the <literal>sslmode</literal> parameter provide different
9915 levels of protection. SSL can provide
9916 protection against three types of attacks:
9917
9918 <variablelist>
9919 <varlistentry>
9920 <term>Eavesdropping</term>
9921 <listitem>
9922 <para>If a third party can examine the network traffic between the
9923 client and the server, it can read both connection information (including
9924 the user name and password) and the data that is passed. <acronym>SSL</acronym>
9925 uses encryption to prevent this.
9926 </para>
9927 </listitem>
9928 </varlistentry>
9929
9930 <varlistentry>
9931 <term>Man-in-the-middle (<acronym>MITM</acronym>)</term>
9932 <listitem>
9933 <para>If a third party can modify the data while passing between the
9934 client and server, it can pretend to be the server and therefore see and
9935 modify data <emphasis>even if it is encrypted</emphasis>. The third party can then
9936 forward the connection information and data to the original server,
9937 making it impossible to detect this attack. Common vectors to do this
9938 include DNS poisoning and address hijacking, whereby the client is directed
9939 to a different server than intended. There are also several other
9940 attack methods that can accomplish this. <acronym>SSL</acronym> uses certificate
9941 verification to prevent this, by authenticating the server to the client.
9942 </para>
9943 </listitem>
9944 </varlistentry>
9945
9946 <varlistentry>
9947 <term>Impersonation</term>
9948 <listitem>
9949 <para>If a third party can pretend to be an authorized client, it can
9950 simply access data it should not have access to. Typically this can
9951 happen through insecure password management. <acronym>SSL</acronym> uses
9952 client certificates to prevent this, by making sure that only holders
9953 of valid certificates can access the server.
9954 </para>
9955 </listitem>
9956 </varlistentry>
9957 </variablelist>
9958 </para>
9959
9960 <para>
9961 For a connection to be known SSL-secured, SSL usage must be configured
9962 on <emphasis>both the client and the server</emphasis> before the connection
9963 is made. If it is only configured on the server, the client may end up
9964 sending sensitive information (e.g., passwords) before
9965 it knows that the server requires high security. In libpq, secure
9966 connections can be ensured
9967 by setting the <literal>sslmode</literal> parameter to <literal>verify-full</literal> or
9968 <literal>verify-ca</literal>, and providing the system with a root certificate to
9969 verify against. This is analogous to using an <literal>https</literal>
9970 <acronym>URL</acronym> for encrypted web browsing.
9971 </para>
9972
9973 <para>
9974 Once the server has been authenticated, the client can pass sensitive data.
9975 This means that up until this point, the client does not need to know if
9976 certificates will be used for authentication, making it safe to specify that
9977 only in the server configuration.
9978 </para>
9979
9980 <para>
9981 All <acronym>SSL</acronym> options carry overhead in the form of encryption and
9982 key-exchange, so there is a trade-off that has to be made between performance
9983 and security. <xref linkend="libpq-ssl-sslmode-statements"/>
9984 illustrates the risks the different <literal>sslmode</literal> values
9985 protect against, and what statement they make about security and overhead.
9986 </para>
9987
9988 <table id="libpq-ssl-sslmode-statements">
9989 <title>SSL Mode Descriptions</title>
9990 <tgroup cols="4">
9991 <colspec colname="col1" colwidth="1*"/>
9992 <colspec colname="col2" colwidth="1*"/>
9993 <colspec colname="col3" colwidth="1*"/>
9994 <colspec colname="col4" colwidth="2*"/>
9995 <thead>
9996 <row>
9997 <entry><literal>sslmode</literal></entry>
9998 <entry>Eavesdropping protection</entry>
9999 <entry><acronym>MITM</acronym> protection</entry>
10000 <entry>Statement</entry>
10001 </row>
10002 </thead>
10003
10004 <tbody>
10005 <row>
10006 <entry><literal>disable</literal></entry>
10007 <entry>No</entry>
10008 <entry>No</entry>
10009 <entry>I don't care about security, and I don't want to pay the overhead
10010 of encryption.
10011 </entry>
10012 </row>
10013
10014 <row>
10015 <entry><literal>allow</literal></entry>
10016 <entry>Maybe</entry>
10017 <entry>No</entry>
10018 <entry>I don't care about security, but I will pay the overhead of
10019 encryption if the server insists on it.
10020 </entry>
10021 </row>
10022
10023 <row>
10024 <entry><literal>prefer</literal></entry>
10025 <entry>Maybe</entry>
10026 <entry>No</entry>
10027 <entry>I don't care about encryption, but I wish to pay the overhead of
10028 encryption if the server supports it.
10029 </entry>
10030 </row>
10031
10032 <row>
10033 <entry><literal>require</literal></entry>
10034 <entry>Yes</entry>
10035 <entry>No</entry>
10036 <entry>I want my data to be encrypted, and I accept the overhead. I trust
10037 that the network will make sure I always connect to the server I want.
10038 </entry>
10039 </row>
10040
10041 <row>
10042 <entry><literal>verify-ca</literal></entry>
10043 <entry>Yes</entry>
10044 <entry>Depends on CA policy</entry>
10045 <entry>I want my data encrypted, and I accept the overhead. I want to be
10046 sure that I connect to a server that I trust.
10047 </entry>
10048 </row>
10049
10050 <row>
10051 <entry><literal>verify-full</literal></entry>
10052 <entry>Yes</entry>
10053 <entry>Yes</entry>
10054 <entry>I want my data encrypted, and I accept the overhead. I want to be
10055 sure that I connect to a server I trust, and that it's the one I
10056 specify.
10057 </entry>
10058 </row>
10059
10060 </tbody>
10061 </tgroup>
10062 </table>
10063
10064 <para>
10065 The difference between <literal>verify-ca</literal> and <literal>verify-full</literal>
10066 depends on the policy of the root <acronym>CA</acronym>. If a public
10067 <acronym>CA</acronym> is used, <literal>verify-ca</literal> allows connections to a server
10068 that <emphasis>somebody else</emphasis> may have registered with the <acronym>CA</acronym>.
10069 In this case, <literal>verify-full</literal> should always be used. If
10070 a local <acronym>CA</acronym> is used, or even a self-signed certificate, using
10071 <literal>verify-ca</literal> often provides enough protection.
10072 </para>
10073
10074 <para>
10075 The default value for <literal>sslmode</literal> is <literal>prefer</literal>. As is shown
10076 in the table, this makes no sense from a security point of view, and it only
10077 promises performance overhead if possible. It is only provided as the default
10078 for backward compatibility, and is not recommended in secure deployments.
10079 </para>
10080
10081 </sect2>
10082
10083 <sect2 id="libpq-ssl-fileusage">
10084 <title>SSL Client File Usage</title>
10085
10086 <para>
10087 <xref linkend="libpq-ssl-file-usage"/> summarizes the files that are
10088 relevant to the SSL setup on the client.
10089 </para>
10090
10091 <table id="libpq-ssl-file-usage">
10092 <title>Libpq/Client SSL File Usage</title>
10093 <tgroup cols="3">
10094 <thead>
10095 <row>
10096 <entry>File</entry>
10097 <entry>Contents</entry>
10098 <entry>Effect</entry>
10099 </row>
10100 </thead>
10101
10102 <tbody>
10103
10104 <row>
10105 <entry><filename>~/.postgresql/postgresql.crt</filename></entry>
10106 <entry>client certificate</entry>
10107 <entry>sent to server</entry>
10108 </row>
10109
10110 <row>
10111 <entry><filename>~/.postgresql/postgresql.key</filename></entry>
10112 <entry>client private key</entry>
10113 <entry>proves client certificate sent by owner; does not indicate
10114 certificate owner is trustworthy</entry>
10115 </row>
10116
10117 <row>
10118 <entry><filename>~/.postgresql/root.crt</filename></entry>
10119 <entry>trusted certificate authorities</entry>
10120 <entry>checks that server certificate is signed by a trusted certificate
10121 authority</entry>
10122 </row>
10123
10124 <row>
10125 <entry><filename>~/.postgresql/root.crl</filename></entry>
10126 <entry>certificates revoked by certificate authorities</entry>
10127 <entry>server certificate must not be on this list</entry>
10128 </row>
10129
10130 </tbody>
10131 </tgroup>
10132 </table>
10133 </sect2>
10134
10135 <sect2 id="libpq-ssl-initialize">
10136 <title>SSL Library Initialization</title>
10137
10138 <para>
10139 Applications which need to be compatible with older versions of
10140 <productname>PostgreSQL</productname>, using <productname>OpenSSL</productname>
10141 version 1.0.2 or older, need to initialize the SSL library before using it.
10142 Applications which initialize <literal>libssl</literal> and/or
10143 <literal>libcrypto</literal> libraries should call
10144 <xref linkend="libpq-PQinitOpenSSL"/> to tell <application>libpq</application>
10145 that the <literal>libssl</literal> and/or <literal>libcrypto</literal> libraries
10146 have been initialized by your application, so that
10147 <application>libpq</application> will not also initialize those libraries.
10148 However, this is unnecessary when using <productname>OpenSSL</productname>
10149 version 1.1.0 or later, as duplicate initializations are no longer problematic.
10150 </para>
10151 <para>
10152 Refer to the documentation for the version of <productname>PostgreSQL</productname>
10153 that you are targeting for details on their use.
10154 </para>
10155
10156 <para>
10157 <variablelist>
10158 <varlistentry id="libpq-PQinitOpenSSL">
10159 <term><function>PQinitOpenSSL</function><indexterm><primary>PQinitOpenSSL</primary></indexterm></term>
10160
10161 <listitem>
10162 <para>
10163 Allows applications to select which security libraries to initialize.
10164 <synopsis>
10165 void PQinitOpenSSL(int do_ssl, int do_crypto);
10166 </synopsis>
10167 </para>
10168
10169 <para>
10170 This function is deprecated and only present for backwards compatibility,
10171 it does nothing.
10172 </para>
10173 </listitem>
10174 </varlistentry>
10175
10176 <varlistentry id="libpq-PQinitSSL">
10177 <term><function>PQinitSSL</function><indexterm><primary>PQinitSSL</primary></indexterm></term><listitem>
10178 <para>
10179 Allows applications to select which security libraries to initialize.
10180 <synopsis>
10181 void PQinitSSL(int do_ssl);
10182 </synopsis>
10183 </para>
10184
10185 <para>
10186 This function is equivalent to
10187 <literal>PQinitOpenSSL(do_ssl, do_ssl)</literal>.
10188 This function is deprecated and only present for backwards compatibility,
10189 it does nothing.
10190 </para>
10191
10192 <para>
10193 <xref linkend="libpq-PQinitSSL"/> and <xref linkend="libpq-PQinitOpenSSL"/>
10194 are maintained for backwards compatibility, but are no longer required
10195 since <productname>PostgreSQL</productname> 18.
10196 <xref linkend="libpq-PQinitSSL"/> has been present since
10197 <productname>PostgreSQL</productname> 8.0, while <xref linkend="libpq-PQinitOpenSSL"/>
10198 was added in <productname>PostgreSQL</productname> 8.4, so <xref linkend="libpq-PQinitSSL"/>
10199 might be preferable for applications that need to work with older
10200 versions of <application>libpq</application>.
10201 </para>
10202 </listitem>
10203 </varlistentry>
10204 </variablelist>
10205 </para>
10206 </sect2>
10207
10208 </sect1>
10209
10210 <sect1 id="libpq-oauth">
10211 <title>OAuth Support</title>
10212
10213 <para>
10214 <application>libpq</application> implements support for the OAuth v2 Device Authorization client flow,
10215 documented in
10216 <ulink url="https://datatracker.ietf.org/doc/html/rfc8628">RFC 8628</ulink>,
10217 as an optional module. See the <link linkend="configure-option-with-libcurl">
10218 installation documentation</link> for information on how to enable support
10219 for Device Authorization as a builtin flow.
10220 </para>
10221 <para>
10222 When support is enabled and the optional module installed, <application>libpq</application>
10223 will use the builtin flow by default if the server
10224 <link linkend="auth-oauth">requests a bearer token</link> during
10225 authentication. This flow can be utilized even if the system running the
10226 client application does not have a usable web browser, for example when
10227 running a client via <acronym>SSH</acronym>.
10228 </para>
10229 <para>
10230 The builtin flow will, by default, print a URL to visit and a user code to
10231 enter there:
10232 <programlisting>
10233 $ psql 'dbname=postgres oauth_issuer=https://example.com oauth_client_id=...'
10234 Visit https://example.com/device and enter the code: ABCD-EFGH
10235 </programlisting>
10236 (This prompt may be
10237 <link linkend="libpq-oauth-authdata-prompt-oauth-device">customized</link>.)
10238 The user will then log into their OAuth provider, which will ask whether
10239 to allow libpq and the server to perform actions on their behalf. It is always
10240 a good idea to carefully review the URL and permissions displayed, to ensure
10241 they match expectations, before continuing. Permissions should not be given
10242 to untrusted third parties.
10243 </para>
10244 <para>
10245 Client applications may implement their own flows to customize interaction
10246 and integration with applications. See <xref linkend="libpq-oauth-authdata-hooks"/>
10247 for more information on how add a custom flow to <application>libpq</application>.
10248 </para>
10249 <para>
10250 For an OAuth client flow to be usable, the connection string must at minimum
10251 contain <xref linkend="libpq-connect-oauth-issuer"/> and
10252 <xref linkend="libpq-connect-oauth-client-id"/>. (These settings are
10253 determined by your organization's OAuth provider.) The builtin flow
10254 additionally requires the OAuth authorization server to publish a device
10255 authorization endpoint.
10256 </para>
10257
10258 <note>
10259 <para>
10260 The builtin Device Authorization flow is not currently supported on Windows.
10261 Custom client flows may still be implemented.
10262 </para>
10263 </note>
10264
10265 <sect2 id="libpq-oauth-authdata-hooks">
10266 <title>Authdata Hooks</title>
10267
10268 <para>
10269 The behavior of the OAuth flow may be modified or replaced by a client using
10270 the following hook API:
10271
10272 <variablelist>
10273 <varlistentry id="libpq-PQsetAuthDataHook">
10274 <term><function>PQsetAuthDataHook</function><indexterm><primary>PQsetAuthDataHook</primary></indexterm></term>
10275
10276 <listitem>
10277 <para>
10278 Sets the <symbol>PGauthDataHook</symbol>, overriding
10279 <application>libpq</application>'s handling of one or more aspects of
10280 its OAuth client flow.
10281 <synopsis>
10282 void PQsetAuthDataHook(PQauthDataHook_type hook);
10283 </synopsis>
10284 If <replaceable>hook</replaceable> is <literal>NULL</literal>, the
10285 default handler will be reinstalled. Otherwise, the application passes
10286 a pointer to a callback function with the signature:
10287 <programlisting>
10288 int hook_fn(PGauthData type, PGconn *conn, void *data);
10289 </programlisting>
10290 which <application>libpq</application> will call when an action is
10291 required of the application. <replaceable>type</replaceable> describes
10292 the request being made, <replaceable>conn</replaceable> is the
10293 connection handle being authenticated, and <replaceable>data</replaceable>
10294 points to request-specific metadata. The contents of this pointer are
10295 determined by <replaceable>type</replaceable>; see
10296 <xref linkend="libpq-oauth-authdata-hooks-types"/> for the supported
10297 list.
10298 </para>
10299 <para>
10300 Hooks can be chained together to allow cooperative and/or fallback
10301 behavior. In general, a hook implementation should examine the incoming
10302 <replaceable>type</replaceable> (and, potentially, the request metadata
10303 and/or the settings for the particular <replaceable>conn</replaceable>
10304 in use) to decide whether or not to handle a specific piece of authdata.
10305 If not, it should delegate to the previous hook in the chain
10306 (retrievable via <function>PQgetAuthDataHook</function>).
10307 </para>
10308 <para>
10309 Success is indicated by returning an integer greater than zero.
10310 Returning a negative integer signals an error condition and abandons the
10311 connection attempt. (A zero value is reserved for the default
10312 implementation.)
10313 </para>
10314 </listitem>
10315 </varlistentry>
10316
10317 <varlistentry id="libpq-PQgetAuthDataHook">
10318 <term><function>PQgetAuthDataHook</function><indexterm><primary>PQgetAuthDataHook</primary></indexterm></term>
10319
10320 <listitem>
10321 <para>
10322 Retrieves the current value of <symbol>PGauthDataHook</symbol>.
10323 <synopsis>
10324 PQauthDataHook_type PQgetAuthDataHook(void);
10325 </synopsis>
10326 At initialization time (before the first call to
10327 <function>PQsetAuthDataHook</function>), this function will return
10328 <symbol>PQdefaultAuthDataHook</symbol>.
10329 </para>
10330 </listitem>
10331 </varlistentry>
10332 </variablelist>
10333 </para>
10334
10335 <sect3 id="libpq-oauth-authdata-hooks-types">
10336 <title>Hook Types</title>
10337 <para>
10338 The following <symbol>PGauthData</symbol> types and their corresponding
10339 <replaceable>data</replaceable> structures are defined:
10340
10341 <variablelist>
10342 <varlistentry id="libpq-oauth-authdata-prompt-oauth-device">
10343 <term>
10344 <symbol>PQAUTHDATA_PROMPT_OAUTH_DEVICE</symbol>
10345 <indexterm><primary>PQAUTHDATA_PROMPT_OAUTH_DEVICE</primary></indexterm>
10346 </term>
10347 <listitem>
10348 <para>
10349 Replaces the default user prompt during the builtin device
10350 authorization client flow. <replaceable>data</replaceable> points to
10351 an instance of <symbol>PGpromptOAuthDevice</symbol>:
10352 <synopsis>
10353 typedef struct _PGpromptOAuthDevice
10354 {
10355 const char *verification_uri; /* verification URI to visit */
10356 const char *user_code; /* user code to enter */
10357 const char *verification_uri_complete; /* optional combination of URI and
10358 * code, or NULL */
10359 int expires_in; /* seconds until user code expires */
10360 } PGpromptOAuthDevice;
10361 </synopsis>
10362 </para>
10363 <para>
10364 The OAuth Device Authorization flow which
10365 <link linkend="configure-option-with-libcurl">can be included</link>
10366 in <application>libpq</application>
10367 requires the end user to visit a URL with a browser, then enter a code
10368 which permits <application>libpq</application> to connect to the server
10369 on their behalf. The default prompt simply prints the
10370 <literal>verification_uri</literal> and <literal>user_code</literal>
10371 on standard error. Replacement implementations may display this
10372 information using any preferred method, for example with a GUI.
10373 </para>
10374 <para>
10375 This callback is only invoked during the builtin device
10376 authorization flow. If the application installs a
10377 <link linkend="libpq-oauth-authdata-oauth-bearer-token">custom OAuth
10378 flow</link>, or <application>libpq</application> was not built with
10379 support for the builtin flow, this authdata type will not be used.
10380 </para>
10381 <para>
10382 If a non-NULL <structfield>verification_uri_complete</structfield> is
10383 provided, it may optionally be used for non-textual verification (for
10384 example, by displaying a QR code). The URL and user code should still
10385 be displayed to the end user in this case, because the code will be
10386 manually confirmed by the provider, and the URL lets users continue
10387 even if they can't use the non-textual method. For more information,
10388 see section 3.3.1 in
10389 <ulink url="https://datatracker.ietf.org/doc/html/rfc8628#section-3.3.1">RFC 8628</ulink>.
10390 </para>
10391 </listitem>
10392 </varlistentry>
10393
10394 <varlistentry id="libpq-oauth-authdata-oauth-bearer-token">
10395 <term>
10396 <symbol>PQAUTHDATA_OAUTH_BEARER_TOKEN</symbol>
10397 <indexterm><primary>PQAUTHDATA_OAUTH_BEARER_TOKEN</primary></indexterm>
10398 </term>
10399 <listitem>
10400 <para>
10401 Adds a custom implementation of a flow, replacing the builtin flow if
10402 it is <link linkend="configure-option-with-libcurl">installed</link>.
10403 The hook should either directly return a Bearer token for the current
10404 user/issuer/scope combination, if one is available without blocking, or
10405 else set up an asynchronous callback to retrieve one.
10406 </para>
10407 <para>
10408 <replaceable>data</replaceable> points to an instance
10409 of <symbol>PGoauthBearerRequest</symbol>, which should be filled in
10410 by the implementation:
10411 <synopsis>
10412 typedef struct PGoauthBearerRequest
10413 {
10414 /* Hook inputs (constant across all calls) */
10415 const char *openid_configuration; /* OIDC discovery URL */
10416 const char *scope; /* required scope(s), or NULL */
10417
10418 /* Hook outputs */
10419
10420 /*
10421 * Callback implementing a custom asynchronous OAuth flow. The signature is
10422 * platform-dependent: PQ_SOCKTYPE is SOCKET on Windows, and int everywhere
10423 * else.
10424 */
10425 PostgresPollingStatusType (*async) (PGconn *conn,
10426 struct PGoauthBearerRequest *request,
10427 PQ_SOCKTYPE *altsock);
10428
10429 /* Callback to clean up custom allocations. */
10430 void (*cleanup) (PGconn *conn, struct PGoauthBearerRequest *request);
10431
10432 char *token; /* acquired Bearer token */
10433 void *user; /* hook-defined allocated data */
10434 } PGoauthBearerRequest;
10435 </synopsis>
10436 </para>
10437 <para>
10438 Two pieces of information are provided to the hook by
10439 <application>libpq</application>:
10440 <replaceable>openid_configuration</replaceable> contains the URL of an
10441 OAuth discovery document describing the authorization server's
10442 supported flows, and <replaceable>scope</replaceable> contains a
10443 (possibly empty) space-separated list of OAuth scopes which are
10444 required to access the server. Either or both may be
10445 <literal>NULL</literal> to indicate that the information was not
10446 discoverable. (In this case, implementations may be able to establish
10447 the requirements using some other preconfigured knowledge, or they may
10448 choose to fail.)
10449 </para>
10450 <para>
10451 The final output of the hook is <replaceable>token</replaceable>, which
10452 must point to a valid Bearer token for use on the connection. (This
10453 token should be issued by the
10454 <xref linkend="libpq-connect-oauth-issuer"/> and hold the requested
10455 scopes, or the connection will be rejected by the server's validator
10456 module.) The allocated token string must remain valid until
10457 <application>libpq</application> is finished connecting; the hook
10458 should set a <replaceable>cleanup</replaceable> callback which will be
10459 called when <application>libpq</application> no longer requires it.
10460 </para>
10461 <para>
10462 If an implementation cannot immediately produce a
10463 <replaceable>token</replaceable> during the initial call to the hook,
10464 it should set the <replaceable>async</replaceable> callback to handle
10465 nonblocking communication with the authorization server.
10466 <footnote>
10467 <para>
10468 Performing blocking operations during the
10469 <symbol>PQAUTHDATA_OAUTH_BEARER_TOKEN</symbol> hook callback will
10470 interfere with nonblocking connection APIs such as
10471 <function>PQconnectPoll</function> and prevent concurrent connections
10472 from making progress. Applications which only ever use the
10473 synchronous connection primitives, such as
10474 <function>PQconnectdb</function>, may synchronously retrieve a token
10475 during the hook instead of implementing the
10476 <replaceable>async</replaceable> callback, but they will necessarily
10477 be limited to one connection at a time.
10478 </para>
10479 </footnote>
10480 This will be called to begin the flow immediately upon return from the
10481 hook. When the callback cannot make further progress without blocking,
10482 it should return either <symbol>PGRES_POLLING_READING</symbol> or
10483 <symbol>PGRES_POLLING_WRITING</symbol> after setting
10484 <literal>*altsock</literal> to the file descriptor that will be marked
10485 ready to read/write when progress can be made again. (This descriptor
10486 is then provided to the top-level polling loop via
10487 <function>PQsocket()</function>.) Return <symbol>PGRES_POLLING_OK</symbol>
10488 after setting <replaceable>token</replaceable> when the flow is
10489 complete, or <symbol>PGRES_POLLING_FAILED</symbol> to indicate failure.
10490 </para>
10491 <para>
10492 Implementations may wish to store additional data for bookkeeping
10493 across calls to the <replaceable>async</replaceable> and
10494 <replaceable>cleanup</replaceable> callbacks. The
10495 <replaceable>user</replaceable> pointer is provided for this purpose;
10496 <application>libpq</application> will not touch its contents and the
10497 application may use it at its convenience. (Remember to free any
10498 allocations during token cleanup.)
10499 </para>
10500 </listitem>
10501 </varlistentry>
10502 </variablelist>
10503 </para>
10504 </sect3>
10505 </sect2>
10506
10507 <sect2 id="libpq-oauth-debugging">
10508 <title>Debugging and Developer Settings</title>
10509
10510 <para>
10511 A "dangerous debugging mode" may be enabled by setting the environment
10512 variable <envar>PGOAUTHDEBUG=UNSAFE</envar>. This functionality is provided
10513 for ease of local development and testing only. It does several things that
10514 you will not want a production system to do:
10515
10516 <itemizedlist spacing="compact">
10517 <listitem>
10518 <para>
10519 permits the use of unencrypted HTTP during the OAuth provider exchange
10520 </para>
10521 </listitem>
10522 <listitem>
10523 <para>
10524 allows the system's trusted CA list to be completely replaced using the
10525 <envar>PGOAUTHCAFILE</envar> environment variable
10526 </para>
10527 </listitem>
10528 <listitem>
10529 <para>
10530 prints HTTP traffic (containing several critical secrets) to standard
10531 error during the OAuth flow
10532 </para>
10533 </listitem>
10534 <listitem>
10535 <para>
10536 permits the use of zero-second retry intervals, which can cause the
10537 client to busy-loop and pointlessly consume CPU
10538 </para>
10539 </listitem>
10540 </itemizedlist>
10541 </para>
10542 <warning>
10543 <para>
10544 Do not share the output of the OAuth flow traffic with third parties. It
10545 contains secrets that can be used to attack your clients and servers.
10546 </para>
10547 </warning>
10548 </sect2>
10549 </sect1>
10550
10551
10552 <sect1 id="libpq-threading">
10553 <title>Behavior in Threaded Programs</title>
10554
10555 <indexterm zone="libpq-threading">
10556 <primary>threads</primary>
10557 <secondary>with libpq</secondary>
10558 </indexterm>
10559
10560 <para>
10561 As of version 17, <application>libpq</application> is always reentrant and thread-safe.
10562 However, one restriction is that no two threads attempt to manipulate
10563 the same <structname>PGconn</structname> object at the same time. In particular,
10564 you cannot issue concurrent commands from different threads through
10565 the same connection object. (If you need to run concurrent commands,
10566 use multiple connections.)
10567 </para>
10568
10569 <para>
10570 <structname>PGresult</structname> objects are normally read-only after creation,
10571 and so can be passed around freely between threads. However, if you use
10572 any of the <structname>PGresult</structname>-modifying functions described in
10573 <xref linkend="libpq-misc"/> or <xref linkend="libpq-events"/>, it's up
10574 to you to avoid concurrent operations on the same <structname>PGresult</structname>,
10575 too.
10576 </para>
10577
10578 <para>
10579 In earlier versions, <application>libpq</application> could be compiled
10580 with or without thread support, depending on compiler options. This
10581 function allows the querying of <application>libpq</application>'s
10582 thread-safe status:
10583 </para>
10584
10585 <variablelist>
10586 <varlistentry id="libpq-PQisthreadsafe">
10587 <term><function>PQisthreadsafe</function><indexterm><primary>PQisthreadsafe</primary></indexterm></term>
10588
10589 <listitem>
10590 <para>
10591 Returns the thread safety status of the
10592 <application>libpq</application> library.
10593 <synopsis>
10594 int PQisthreadsafe();
10595 </synopsis>
10596 </para>
10597
10598 <para>
10599 Returns 1 if the <application>libpq</application> is thread-safe
10600 and 0 if it is not. Always returns 1 on version 17 and above.
10601 </para>
10602 </listitem>
10603 </varlistentry>
10604 </variablelist>
10605
10606 <para>
10607 The deprecated functions <xref linkend="libpq-PQrequestCancel"/> and
10608 <xref linkend="libpq-PQoidStatus"/> are not thread-safe and should not be
10609 used in multithread programs. <xref linkend="libpq-PQrequestCancel"/>
10610 can be replaced by <xref linkend="libpq-PQcancelBlocking"/>.
10611 <xref linkend="libpq-PQoidStatus"/> can be replaced by
10612 <xref linkend="libpq-PQoidValue"/>.
10613 </para>
10614
10615 <para>
10616 If you are using Kerberos inside your application (in addition to inside
10617 <application>libpq</application>), you will need to do locking around
10618 Kerberos calls because Kerberos functions are not thread-safe. See
10619 function <function>PQregisterThreadLock</function> in the
10620 <application>libpq</application> source code for a way to do cooperative
10621 locking between <application>libpq</application> and your application.
10622 </para>
10623
10624 <para>
10625 Similarly, if you are using <productname>Curl</productname> inside your application,
10626 <emphasis>and</emphasis> you do not already
10627 <ulink url="https://curl.se/libcurl/c/curl_global_init.html">initialize
10628 libcurl globally</ulink> before starting new threads, you will need to
10629 cooperatively lock (again via <function>PQregisterThreadLock</function>)
10630 around any code that may initialize libcurl. This restriction is lifted for
10631 more recent versions of <productname>Curl</productname> that are built to support thread-safe
10632 initialization; those builds can be identified by the advertisement of a
10633 <literal>threadsafe</literal> feature in their version metadata.
10634 </para>
10635 </sect1>
10636
10637
10638 <sect1 id="libpq-build">
10639 <title>Building <application>libpq</application> Programs</title>
10640
10641 <indexterm zone="libpq-build">
10642 <primary>compiling</primary>
10643 <secondary>libpq applications</secondary>
10644 </indexterm>
10645
10646 <para>
10647 To build (i.e., compile and link) a program using
10648 <application>libpq</application> you need to do all of the following
10649 things:
10650
10651 <itemizedlist>
10652 <listitem>
10653 <para>
10654 Include the <filename>libpq-fe.h</filename> header file:
10655 <programlisting>
10656 #include &lt;libpq-fe.h&gt;
10657 </programlisting>
10658 If you failed to do that then you will normally get error messages
10659 from your compiler similar to:
10660 <screen>
10661 foo.c: In function `main':
10662 foo.c:34: `PGconn' undeclared (first use in this function)
10663 foo.c:35: `PGresult' undeclared (first use in this function)
10664 foo.c:54: `CONNECTION_BAD' undeclared (first use in this function)
10665 foo.c:68: `PGRES_COMMAND_OK' undeclared (first use in this function)
10666 foo.c:95: `PGRES_TUPLES_OK' undeclared (first use in this function)
10667 </screen>
10668 </para>
10669 </listitem>
10670
10671 <listitem>
10672 <para>
10673 Point your compiler to the directory where the <productname>PostgreSQL</productname> header
10674 files were installed, by supplying the
10675 <literal>-I<replaceable>directory</replaceable></literal> option
10676 to your compiler. (In some cases the compiler will look into
10677 the directory in question by default, so you can omit this
10678 option.) For instance, your compile command line could look
10679 like:
10680 <programlisting>
10681 cc -c -I/usr/local/pgsql/include testprog.c
10682 </programlisting>
10683 If you are using makefiles then add the option to the
10684 <varname>CPPFLAGS</varname> variable:
10685 <programlisting>
10686 CPPFLAGS += -I/usr/local/pgsql/include
10687 </programlisting>
10688 </para>
10689
10690 <para>
10691 If there is any chance that your program might be compiled by
10692 other users then you should not hardcode the directory location
10693 like that. Instead, you can run the utility
10694 <command>pg_config</command><indexterm><primary>pg_config</primary><secondary
10695 sortas="libpq">with libpq</secondary></indexterm> to find out where the header
10696 files are on the local system:
10697 <screen>
10698 <prompt>$</prompt> pg_config --includedir
10699 <computeroutput>/usr/local/include</computeroutput>
10700 </screen>
10701 </para>
10702
10703 <para>
10704 If you
10705 have <command>pkg-config</command><indexterm><primary>pkg-config</primary><secondary sortas="libpq">with
10706 libpq</secondary></indexterm> installed, you can run instead:
10707 <screen>
10708 <prompt>$</prompt> pkg-config --cflags libpq
10709 <computeroutput>-I/usr/local/include</computeroutput>
10710 </screen>
10711 Note that this will already include the <option>-I</option> in front of
10712 the path.
10713 </para>
10714
10715 <para>
10716 Failure to specify the correct option to the compiler will
10717 result in an error message such as:
10718 <screen>
10719 testlibpq.c:8:22: libpq-fe.h: No such file or directory
10720 </screen>
10721 </para>
10722 </listitem>
10723
10724 <listitem>
10725 <para>
10726 When linking the final program, specify the option
10727 <literal>-lpq</literal> so that the <application>libpq</application>
10728 library gets pulled in, as well as the option
10729 <literal>-L<replaceable>directory</replaceable></literal> to point
10730 the compiler to the directory where the
10731 <application>libpq</application> library resides. (Again, the
10732 compiler will search some directories by default.) For maximum
10733 portability, put the <option>-L</option> option before the
10734 <option>-lpq</option> option. For example:
10735 <programlisting>
10736 cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq
10737 </programlisting>
10738 </para>
10739
10740 <para>
10741 You can find out the library directory using
10742 <command>pg_config</command> as well:
10743 <screen>
10744 <prompt>$</prompt> pg_config --libdir
10745 <computeroutput>/usr/local/pgsql/lib</computeroutput>
10746 </screen>
10747 </para>
10748
10749 <para>
10750 Or again use <command>pkg-config</command>:
10751 <screen>
10752 <prompt>$</prompt> pkg-config --libs libpq
10753 <computeroutput>-L/usr/local/pgsql/lib -lpq</computeroutput>
10754 </screen>
10755 Note again that this prints the full options, not only the path.
10756 </para>
10757
10758 <para>
10759 Error messages that point to problems in this area could look like
10760 the following:
10761 <screen>
10762 testlibpq.o: In function `main':
10763 testlibpq.o(.text+0x60): undefined reference to `PQsetdbLogin'
10764 testlibpq.o(.text+0x71): undefined reference to `PQstatus'
10765 testlibpq.o(.text+0xa4): undefined reference to `PQerrorMessage'
10766 </screen>
10767 This means you forgot <option>-lpq</option>.
10768 <screen>
10769 /usr/bin/ld: cannot find -lpq
10770 </screen>
10771 This means you forgot the <option>-L</option> option or did not
10772 specify the right directory.
10773 </para>
10774 </listitem>
10775 </itemizedlist>
10776 </para>
10777
10778 </sect1>
10779
10780
10781 <sect1 id="libpq-example">
10782 <title>Example Programs</title>
10783
10784 <para>
10785 These examples and others can be found in the
10786 directory <filename>src/test/examples</filename> in the source code
10787 distribution.
10788 </para>
10789
10790 <example id="libpq-example-1">
10791 <title><application>libpq</application> Example Program 1</title>
10792
10793 <programlisting>
10794 <![CDATA[
10795 /*
10796 * src/test/examples/testlibpq.c
10797 *
10798 *
10799 * testlibpq.c
10800 *
10801 * Test the C version of libpq, the PostgreSQL frontend library.
10802 */
10803 #include <stdio.h>
10804 #include <stdlib.h>
10805 #include "libpq-fe.h"
10806
10807 static void
10808 exit_nicely(PGconn *conn)
10809 {
10810 PQfinish(conn);
10811 exit(1);
10812 }
10813
10814 int
10815 main(int argc, char **argv)
10816 {
10817 const char *conninfo;
10818 PGconn *conn;
10819 PGresult *res;
10820 int nFields;
10821 int i,
10822 j;
10823
10824 /*
10825 * If the user supplies a parameter on the command line, use it as the
10826 * conninfo string; otherwise default to setting dbname=postgres and using
10827 * environment variables or defaults for all other connection parameters.
10828 */
10829 if (argc > 1)
10830 conninfo = argv[1];
10831 else
10832 conninfo = "dbname = postgres";
10833
10834 /* Make a connection to the database */
10835 conn = PQconnectdb(conninfo);
10836
10837 /* Check to see that the backend connection was successfully made */
10838 if (PQstatus(conn) != CONNECTION_OK)
10839 {
10840 fprintf(stderr, "%s", PQerrorMessage(conn));
10841 exit_nicely(conn);
10842 }
10843
10844 /* Set always-secure search path, so malicious users can't take control. */
10845 res = PQexec(conn,
10846 "SELECT pg_catalog.set_config('search_path', '', false)");
10847 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10848 {
10849 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
10850 PQclear(res);
10851 exit_nicely(conn);
10852 }
10853
10854 /*
10855 * Should PQclear PGresult whenever it is no longer needed to avoid memory
10856 * leaks
10857 */
10858 PQclear(res);
10859
10860 /*
10861 * Our test case here involves using a cursor, for which we must be inside
10862 * a transaction block. We could do the whole thing with a single
10863 * PQexec() of "select * from pg_database", but that's too trivial to make
10864 * a good example.
10865 */
10866
10867 /* Start a transaction block */
10868 res = PQexec(conn, "BEGIN");
10869 if (PQresultStatus(res) != PGRES_COMMAND_OK)
10870 {
10871 fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn));
10872 PQclear(res);
10873 exit_nicely(conn);
10874 }
10875 PQclear(res);
10876
10877 /*
10878 * Fetch rows from pg_database, the system catalog of databases
10879 */
10880 res = PQexec(conn, "DECLARE myportal CURSOR FOR select * from pg_database");
10881 if (PQresultStatus(res) != PGRES_COMMAND_OK)
10882 {
10883 fprintf(stderr, "DECLARE CURSOR failed: %s", PQerrorMessage(conn));
10884 PQclear(res);
10885 exit_nicely(conn);
10886 }
10887 PQclear(res);
10888
10889 res = PQexec(conn, "FETCH ALL in myportal");
10890 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10891 {
10892 fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(conn));
10893 PQclear(res);
10894 exit_nicely(conn);
10895 }
10896
10897 /* first, print out the attribute names */
10898 nFields = PQnfields(res);
10899 for (i = 0; i < nFields; i++)
10900 printf("%-15s", PQfname(res, i));
10901 printf("\n\n");
10902
10903 /* next, print out the rows */
10904 for (i = 0; i < PQntuples(res); i++)
10905 {
10906 for (j = 0; j < nFields; j++)
10907 printf("%-15s", PQgetvalue(res, i, j));
10908 printf("\n");
10909 }
10910
10911 PQclear(res);
10912
10913 /* close the portal ... we don't bother to check for errors ... */
10914 res = PQexec(conn, "CLOSE myportal");
10915 PQclear(res);
10916
10917 /* end the transaction */
10918 res = PQexec(conn, "END");
10919 PQclear(res);
10920
10921 /* close the connection to the database and cleanup */
10922 PQfinish(conn);
10923
10924 return 0;
10925 }
10926 ]]>
10927 </programlisting>
10928 </example>
10929
10930 <example id="libpq-example-2">
10931 <title><application>libpq</application> Example Program 2</title>
10932
10933 <programlisting>
10934 <![CDATA[
10935 /*
10936 * src/test/examples/testlibpq2.c
10937 *
10938 *
10939 * testlibpq2.c
10940 * Test of the asynchronous notification interface
10941 *
10942 * Start this program, then from psql in another window do
10943 * NOTIFY TBL2;
10944 * Repeat four times to get this program to exit.
10945 *
10946 * Or, if you want to get fancy, try this:
10947 * populate a database with the following commands
10948 * (provided in src/test/examples/testlibpq2.sql):
10949 *
10950 * CREATE SCHEMA TESTLIBPQ2;
10951 * SET search_path = TESTLIBPQ2;
10952 * CREATE TABLE TBL1 (i int4);
10953 * CREATE TABLE TBL2 (i int4);
10954 * CREATE RULE r1 AS ON INSERT TO TBL1 DO
10955 * (INSERT INTO TBL2 VALUES (new.i); NOTIFY TBL2);
10956 *
10957 * Start this program, then from psql do this four times:
10958 *
10959 * INSERT INTO TESTLIBPQ2.TBL1 VALUES (10);
10960 */
10961
10962 #ifdef WIN32
10963 #include <windows.h>
10964 #endif
10965 #include <stdio.h>
10966 #include <stdlib.h>
10967 #include <string.h>
10968 #include <errno.h>
10969 #include <sys/select.h>
10970 #include <sys/time.h>
10971 #include <sys/types.h>
10972
10973 #include "libpq-fe.h"
10974
10975 static void
10976 exit_nicely(PGconn *conn)
10977 {
10978 PQfinish(conn);
10979 exit(1);
10980 }
10981
10982 int
10983 main(int argc, char **argv)
10984 {
10985 const char *conninfo;
10986 PGconn *conn;
10987 PGresult *res;
10988 PGnotify *notify;
10989 int nnotifies;
10990
10991 /*
10992 * If the user supplies a parameter on the command line, use it as the
10993 * conninfo string; otherwise default to setting dbname=postgres and using
10994 * environment variables or defaults for all other connection parameters.
10995 */
10996 if (argc > 1)
10997 conninfo = argv[1];
10998 else
10999 conninfo = "dbname = postgres";
11000
11001 /* Make a connection to the database */
11002 conn = PQconnectdb(conninfo);
11003
11004 /* Check to see that the backend connection was successfully made */
11005 if (PQstatus(conn) != CONNECTION_OK)
11006 {
11007 fprintf(stderr, "%s", PQerrorMessage(conn));
11008 exit_nicely(conn);
11009 }
11010
11011 /* Set always-secure search path, so malicious users can't take control. */
11012 res = PQexec(conn,
11013 "SELECT pg_catalog.set_config('search_path', '', false)");
11014 if (PQresultStatus(res) != PGRES_TUPLES_OK)
11015 {
11016 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
11017 PQclear(res);
11018 exit_nicely(conn);
11019 }
11020
11021 /*
11022 * Should PQclear PGresult whenever it is no longer needed to avoid memory
11023 * leaks
11024 */
11025 PQclear(res);
11026
11027 /*
11028 * Issue LISTEN command to enable notifications from the rule's NOTIFY.
11029 */
11030 res = PQexec(conn, "LISTEN TBL2");
11031 if (PQresultStatus(res) != PGRES_COMMAND_OK)
11032 {
11033 fprintf(stderr, "LISTEN command failed: %s", PQerrorMessage(conn));
11034 PQclear(res);
11035 exit_nicely(conn);
11036 }
11037 PQclear(res);
11038
11039 /* Quit after four notifies are received. */
11040 nnotifies = 0;
11041 while (nnotifies < 4)
11042 {
11043 /*
11044 * Sleep until something happens on the connection. We use select(2)
11045 * to wait for input, but you could also use poll() or similar
11046 * facilities.
11047 */
11048 int sock;
11049 fd_set input_mask;
11050
11051 sock = PQsocket(conn);
11052
11053 if (sock < 0)
11054 break; /* shouldn't happen */
11055
11056 FD_ZERO(&input_mask);
11057 FD_SET(sock, &input_mask);
11058
11059 if (select(sock + 1, &input_mask, NULL, NULL, NULL) < 0)
11060 {
11061 fprintf(stderr, "select() failed: %s\n", strerror(errno));
11062 exit_nicely(conn);
11063 }
11064
11065 /* Now check for input */
11066 PQconsumeInput(conn);
11067 while ((notify = PQnotifies(conn)) != NULL)
11068 {
11069 fprintf(stderr,
11070 "ASYNC NOTIFY of '%s' received from backend PID %d\n",
11071 notify->relname, notify->be_pid);
11072 PQfreemem(notify);
11073 nnotifies++;
11074 PQconsumeInput(conn);
11075 }
11076 }
11077
11078 fprintf(stderr, "Done.\n");
11079
11080 /* close the connection to the database and cleanup */
11081 PQfinish(conn);
11082
11083 return 0;
11084 }
11085 ]]>
11086 </programlisting>
11087 </example>
11088
11089 <example id="libpq-example-3">
11090 <title><application>libpq</application> Example Program 3</title>
11091
11092 <programlisting>
11093 <![CDATA[
11094 /*
11095 * src/test/examples/testlibpq3.c
11096 *
11097 *
11098 * testlibpq3.c
11099 * Test out-of-line parameters and binary I/O.
11100 *
11101 * Before running this, populate a database with the following commands
11102 * (provided in src/test/examples/testlibpq3.sql):
11103 *
11104 * CREATE SCHEMA testlibpq3;
11105 * SET search_path = testlibpq3;
11106 * SET standard_conforming_strings = ON;
11107 * CREATE TABLE test1 (i int4, t text, b bytea);
11108 * INSERT INTO test1 values (1, 'joe''s place', '\000\001\002\003\004');
11109 * INSERT INTO test1 values (2, 'ho there', '\004\003\002\001\000');
11110 *
11111 * The expected output is:
11112 *
11113 * tuple 0: got
11114 * i = (4 bytes) 1
11115 * t = (11 bytes) 'joe's place'
11116 * b = (5 bytes) \000\001\002\003\004
11117 *
11118 * tuple 0: got
11119 * i = (4 bytes) 2
11120 * t = (8 bytes) 'ho there'
11121 * b = (5 bytes) \004\003\002\001\000
11122 */
11123
11124 #ifdef WIN32
11125 #include <windows.h>
11126 #endif
11127
11128 #include <stdio.h>
11129 #include <stdlib.h>
11130 #include <stdint.h>
11131 #include <string.h>
11132 #include <sys/types.h>
11133 #include "libpq-fe.h"
11134
11135 /* for ntohl/htonl */
11136 #include <netinet/in.h>
11137 #include <arpa/inet.h>
11138
11139
11140 static void
11141 exit_nicely(PGconn *conn)
11142 {
11143 PQfinish(conn);
11144 exit(1);
11145 }
11146
11147 /*
11148 * This function prints a query result that is a binary-format fetch from
11149 * a table defined as in the comment above. We split it out because the
11150 * main() function uses it twice.
11151 */
11152 static void
11153 show_binary_results(PGresult *res)
11154 {
11155 int i,
11156 j;
11157 int i_fnum,
11158 t_fnum,
11159 b_fnum;
11160
11161 /* Use PQfnumber to avoid assumptions about field order in result */
11162 i_fnum = PQfnumber(res, "i");
11163 t_fnum = PQfnumber(res, "t");
11164 b_fnum = PQfnumber(res, "b");
11165
11166 for (i = 0; i < PQntuples(res); i++)
11167 {
11168 char *iptr;
11169 char *tptr;
11170 char *bptr;
11171 int blen;
11172 int ival;
11173
11174 /* Get the field values (we ignore possibility they are null!) */
11175 iptr = PQgetvalue(res, i, i_fnum);
11176 tptr = PQgetvalue(res, i, t_fnum);
11177 bptr = PQgetvalue(res, i, b_fnum);
11178
11179 /*
11180 * The binary representation of INT4 is in network byte order, which
11181 * we'd better coerce to the local byte order.
11182 */
11183 ival = ntohl(*((uint32_t *) iptr));
11184
11185 /*
11186 * The binary representation of TEXT is, well, text, and since libpq
11187 * was nice enough to append a zero byte to it, it'll work just fine
11188 * as a C string.
11189 *
11190 * The binary representation of BYTEA is a bunch of bytes, which could
11191 * include embedded nulls so we have to pay attention to field length.
11192 */
11193 blen = PQgetlength(res, i, b_fnum);
11194
11195 printf("tuple %d: got\n", i);
11196 printf(" i = (%d bytes) %d\n",
11197 PQgetlength(res, i, i_fnum), ival);
11198 printf(" t = (%d bytes) '%s'\n",
11199 PQgetlength(res, i, t_fnum), tptr);
11200 printf(" b = (%d bytes) ", blen);
11201 for (j = 0; j < blen; j++)
11202 printf("\\%03o", bptr[j]);
11203 printf("\n\n");
11204 }
11205 }
11206
11207 int
11208 main(int argc, char **argv)
11209 {
11210 const char *conninfo;
11211 PGconn *conn;
11212 PGresult *res;
11213 const char *paramValues[1];
11214 int paramLengths[1];
11215 int paramFormats[1];
11216 uint32_t binaryIntVal;
11217
11218 /*
11219 * If the user supplies a parameter on the command line, use it as the
11220 * conninfo string; otherwise default to setting dbname=postgres and using
11221 * environment variables or defaults for all other connection parameters.
11222 */
11223 if (argc > 1)
11224 conninfo = argv[1];
11225 else
11226 conninfo = "dbname = postgres";
11227
11228 /* Make a connection to the database */
11229 conn = PQconnectdb(conninfo);
11230
11231 /* Check to see that the backend connection was successfully made */
11232 if (PQstatus(conn) != CONNECTION_OK)
11233 {
11234 fprintf(stderr, "%s", PQerrorMessage(conn));
11235 exit_nicely(conn);
11236 }
11237
11238 /* Set always-secure search path, so malicious users can't take control. */
11239 res = PQexec(conn, "SET search_path = testlibpq3");
11240 if (PQresultStatus(res) != PGRES_COMMAND_OK)
11241 {
11242 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
11243 PQclear(res);
11244 exit_nicely(conn);
11245 }
11246 PQclear(res);
11247
11248 /*
11249 * The point of this program is to illustrate use of PQexecParams() with
11250 * out-of-line parameters, as well as binary transmission of data.
11251 *
11252 * This first example transmits the parameters as text, but receives the
11253 * results in binary format. By using out-of-line parameters we can avoid
11254 * a lot of tedious mucking about with quoting and escaping, even though
11255 * the data is text. Notice how we don't have to do anything special with
11256 * the quote mark in the parameter value.
11257 */
11258
11259 /* Here is our out-of-line parameter value */
11260 paramValues[0] = "joe's place";
11261
11262 res = PQexecParams(conn,
11263 "SELECT * FROM test1 WHERE t = $1",
11264 1, /* one param */
11265 NULL, /* let the backend deduce param type */
11266 paramValues,
11267 NULL, /* don't need param lengths since text */
11268 NULL, /* default to all text params */
11269 1); /* ask for binary results */
11270
11271 if (PQresultStatus(res) != PGRES_TUPLES_OK)
11272 {
11273 fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
11274 PQclear(res);
11275 exit_nicely(conn);
11276 }
11277
11278 show_binary_results(res);
11279
11280 PQclear(res);
11281
11282 /*
11283 * In this second example we transmit an integer parameter in binary form,
11284 * and again retrieve the results in binary form.
11285 *
11286 * Although we tell PQexecParams we are letting the backend deduce
11287 * parameter type, we really force the decision by casting the parameter
11288 * symbol in the query text. This is a good safety measure when sending
11289 * binary parameters.
11290 */
11291
11292 /* Convert integer value "2" to network byte order */
11293 binaryIntVal = htonl((uint32_t) 2);
11294
11295 /* Set up parameter arrays for PQexecParams */
11296 paramValues[0] = (char *) &binaryIntVal;
11297 paramLengths[0] = sizeof(binaryIntVal);
11298 paramFormats[0] = 1; /* binary */
11299
11300 res = PQexecParams(conn,
11301 "SELECT * FROM test1 WHERE i = $1::int4",
11302 1, /* one param */
11303 NULL, /* let the backend deduce param type */
11304 paramValues,
11305 paramLengths,
11306 paramFormats,
11307 1); /* ask for binary results */
11308
11309 if (PQresultStatus(res) != PGRES_TUPLES_OK)
11310 {
11311 fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
11312 PQclear(res);
11313 exit_nicely(conn);
11314 }
11315
11316 show_binary_results(res);
11317
11318 PQclear(res);
11319
11320 /* close the connection to the database and cleanup */
11321 PQfinish(conn);
11322
11323 return 0;
11324 }
11325 ]]>
11326 </programlisting>
11327 </example>
11328
11329 </sect1>
11330 </chapter>