doc: correct description of libpq's PQsetnonblocking() mode
[pgsql.git] / doc / src / sgml / libpq.sgml
blobed88ac001a17e4970ff7142edf24e33ae5c53e4f
1 <!-- doc/src/sgml/libpq.sgml -->
3 <chapter id="libpq">
4 <title><application>libpq</application> &mdash; C Library</title>
6 <indexterm zone="libpq">
7 <primary>libpq</primary>
8 </indexterm>
10 <indexterm zone="libpq">
11 <primary>C</primary>
12 </indexterm>
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>
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>
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>
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>
49 <sect1 id="libpq-connect">
50 <title>Database Connection Control Functions</title>
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.
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>
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>
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.
101 <synopsis>
102 PGconn *PQconnectdbParams(const char * const *keywords,
103 const char * const *values,
104 int expand_dbname);
105 </synopsis>
106 </para>
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>
120 <para>
121 The currently recognized parameter key words are listed in
122 <xref linkend="libpq-paramkeywords"/>.
123 </para>
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>
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>
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>
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>
175 </listitem>
176 </varlistentry>
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.
184 <synopsis>
185 PGconn *PQconnectdb(const char *conninfo);
186 </synopsis>
187 </para>
189 <para>
190 This function opens a new database connection using the parameters taken
191 from the string <literal>conninfo</literal>.
192 </para>
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>
202 </listitem>
203 </varlistentry>
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>
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>
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>
236 <para>
237 <literal>pgtty</literal> is no longer used and any value passed will
238 be ignored.
239 </para>
240 </listitem>
241 </varlistentry>
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>
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>
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><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.
274 <synopsis>
275 PGconn *PQconnectStartParams(const char * const *keywords,
276 const char * const *values,
277 int expand_dbname);
279 PGconn *PQconnectStart(const char *conninfo);
281 PostgresPollingStatusType PQconnectPoll(PGconn *conn);
282 </synopsis>
283 </para>
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>
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>
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>
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>
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>
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>
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>
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).
362 Then call <function>PQconnectPoll(conn)</function> again.
363 Conversely, if <function>PQconnectPoll(conn)</function> last returned
364 <symbol>PGRES_POLLING_WRITING</symbol>, wait until the socket is ready
365 to write, then call <function>PQconnectPoll(conn)</function> again.
366 On the first iteration, i.e., if you have yet to call
367 <function>PQconnectPoll</function>, behave as if it last returned
368 <symbol>PGRES_POLLING_WRITING</symbol>. Continue this loop until
369 <function>PQconnectPoll(conn)</function> returns
370 <symbol>PGRES_POLLING_FAILED</symbol>, indicating the connection procedure
371 has failed, or <symbol>PGRES_POLLING_OK</symbol>, indicating the connection
372 has been successfully made.
373 </para>
375 <para>
376 At any time during connection, the status of the connection can be
377 checked by calling <xref linkend="libpq-PQstatus"/>. If this call returns <symbol>CONNECTION_BAD</symbol>, then the
378 connection procedure has failed; if the call returns <function>CONNECTION_OK</function>, then the
379 connection is ready. Both of these states are equally detectable
380 from the return value of <function>PQconnectPoll</function>, described above. Other states might also occur
381 during (and only during) an asynchronous connection procedure. These
382 indicate the current stage of the connection procedure and might be useful
383 to provide feedback to the user for example. These statuses are:
385 <variablelist>
386 <varlistentry id="libpq-connection-started">
387 <term><symbol>CONNECTION_STARTED</symbol></term>
388 <listitem>
389 <para>
390 Waiting for connection to be made.
391 </para>
392 </listitem>
393 </varlistentry>
395 <varlistentry id="libpq-connection-made">
396 <term><symbol>CONNECTION_MADE</symbol></term>
397 <listitem>
398 <para>
399 Connection OK; waiting to send.
400 </para>
401 </listitem>
402 </varlistentry>
404 <varlistentry id="libpq-connection-awaiting-response">
405 <term><symbol>CONNECTION_AWAITING_RESPONSE</symbol></term>
406 <listitem>
407 <para>
408 Waiting for a response from the server.
409 </para>
410 </listitem>
411 </varlistentry>
413 <varlistentry id="libpq-connection-auth-ok">
414 <term><symbol>CONNECTION_AUTH_OK</symbol></term>
415 <listitem>
416 <para>
417 Received authentication; waiting for backend start-up to finish.
418 </para>
419 </listitem>
420 </varlistentry>
422 <varlistentry id="libpq-connection-ssl-startup">
423 <term><symbol>CONNECTION_SSL_STARTUP</symbol></term>
424 <listitem>
425 <para>
426 Negotiating SSL encryption.
427 </para>
428 </listitem>
429 </varlistentry>
431 <varlistentry id="libpq-connection-setenv">
432 <term><symbol>CONNECTION_SETENV</symbol></term>
433 <listitem>
434 <para>
435 Negotiating environment-driven parameter settings.
436 </para>
437 </listitem>
438 </varlistentry>
440 <varlistentry id="libpq-connection-check-writable">
441 <term><symbol>CONNECTION_CHECK_WRITABLE</symbol></term>
442 <listitem>
443 <para>
444 Checking if connection is able to handle write transactions.
445 </para>
446 </listitem>
447 </varlistentry>
449 <varlistentry id="libpq-connection-consume">
450 <term><symbol>CONNECTION_CONSUME</symbol></term>
451 <listitem>
452 <para>
453 Consuming any remaining response messages on connection.
454 </para>
455 </listitem>
456 </varlistentry>
457 </variablelist>
459 Note that, although these constants will remain (in order to maintain
460 compatibility), an application should never rely upon these occurring in a
461 particular order, or at all, or on the status always being one of these
462 documented values. An application might do something like this:
463 <programlisting>
464 switch(PQstatus(conn))
466 case CONNECTION_STARTED:
467 feedback = "Connecting...";
468 break;
470 case CONNECTION_MADE:
471 feedback = "Connected to server...";
472 break;
476 default:
477 feedback = "Connecting...";
479 </programlisting>
480 </para>
482 <para>
483 The <literal>connect_timeout</literal> connection parameter is ignored
484 when using <function>PQconnectPoll</function>; it is the application's
485 responsibility to decide whether an excessive amount of time has elapsed.
486 Otherwise, <function>PQconnectStart</function> followed by a
487 <function>PQconnectPoll</function> loop is equivalent to
488 <xref linkend="libpq-PQconnectdb"/>.
489 </para>
491 <para>
492 Note that when <function>PQconnectStart</function>
493 or <xref linkend="libpq-PQconnectStartParams"/> returns a non-null
494 pointer, you must call <xref linkend="libpq-PQfinish"/> when you are
495 finished with it, in order to dispose of the structure and any
496 associated memory blocks. This must be done even if the connection
497 attempt fails or is abandoned.
498 </para>
499 </listitem>
500 </varlistentry>
502 <varlistentry id="libpq-PQconndefaults">
503 <term><function>PQconndefaults</function><indexterm><primary>PQconndefaults</primary></indexterm></term>
504 <listitem>
505 <para>
506 Returns the default connection options.
507 <synopsis>
508 PQconninfoOption *PQconndefaults(void);
510 typedef struct
512 char *keyword; /* The keyword of the option */
513 char *envvar; /* Fallback environment variable name */
514 char *compiled; /* Fallback compiled in default value */
515 char *val; /* Option's current value, or NULL */
516 char *label; /* Label for field in connect dialog */
517 char *dispchar; /* Indicates how to display this field
518 in a connect dialog. Values are:
519 "" Display entered value as is
520 "*" Password field - hide value
521 "D" Debug option - don't show by default */
522 int dispsize; /* Field size in characters for dialog */
523 } PQconninfoOption;
524 </synopsis>
525 </para>
527 <para>
528 Returns a connection options array. This can be used to determine
529 all possible <xref linkend="libpq-PQconnectdb"/> options and their
530 current default values. The return value points to an array of
531 <structname>PQconninfoOption</structname> structures, which ends
532 with an entry having a null <structfield>keyword</structfield> pointer. The
533 null pointer is returned if memory could not be allocated. Note that
534 the current default values (<structfield>val</structfield> fields)
535 will depend on environment variables and other context. A
536 missing or invalid service file will be silently ignored. Callers
537 must treat the connection options data as read-only.
538 </para>
540 <para>
541 After processing the options array, free it by passing it to
542 <xref linkend="libpq-PQconninfoFree"/>. If this is not done, a small amount of memory
543 is leaked for each call to <xref linkend="libpq-PQconndefaults"/>.
544 </para>
546 </listitem>
547 </varlistentry>
549 <varlistentry id="libpq-PQconninfo">
550 <term><function>PQconninfo</function><indexterm><primary>PQconninfo</primary></indexterm></term>
551 <listitem>
552 <para>
553 Returns the connection options used by a live connection.
554 <synopsis>
555 PQconninfoOption *PQconninfo(PGconn *conn);
556 </synopsis>
557 </para>
559 <para>
560 Returns a connection options array. This can be used to determine
561 all possible <xref linkend="libpq-PQconnectdb"/> options and the
562 values that were used to connect to the server. The return
563 value points to an array of <structname>PQconninfoOption</structname>
564 structures, which ends with an entry having a null <structfield>keyword</structfield>
565 pointer. All notes above for <xref linkend="libpq-PQconndefaults"/> also
566 apply to the result of <xref linkend="libpq-PQconninfo"/>.
567 </para>
569 </listitem>
570 </varlistentry>
573 <varlistentry id="libpq-PQconninfoParse">
574 <term><function>PQconninfoParse</function><indexterm><primary>PQconninfoParse</primary></indexterm></term>
575 <listitem>
576 <para>
577 Returns parsed connection options from the provided connection string.
579 <synopsis>
580 PQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg);
581 </synopsis>
582 </para>
584 <para>
585 Parses a connection string and returns the resulting options as an
586 array; or returns <symbol>NULL</symbol> if there is a problem with the connection
587 string. This function can be used to extract
588 the <xref linkend="libpq-PQconnectdb"/> options in the provided
589 connection string. The return value points to an array of
590 <structname>PQconninfoOption</structname> structures, which ends
591 with an entry having a null <structfield>keyword</structfield> pointer.
592 </para>
594 <para>
595 All legal options will be present in the result array, but the
596 <literal>PQconninfoOption</literal> for any option not present
597 in the connection string will have <literal>val</literal> set to
598 <literal>NULL</literal>; default values are not inserted.
599 </para>
601 <para>
602 If <literal>errmsg</literal> is not <symbol>NULL</symbol>, then <literal>*errmsg</literal> is set
603 to <symbol>NULL</symbol> on success, else to a <function>malloc</function>'d error string explaining
604 the problem. (It is also possible for <literal>*errmsg</literal> to be
605 set to <symbol>NULL</symbol> and the function to return <symbol>NULL</symbol>;
606 this indicates an out-of-memory condition.)
607 </para>
609 <para>
610 After processing the options array, free it by passing it to
611 <xref linkend="libpq-PQconninfoFree"/>. If this is not done, some memory
612 is leaked for each call to <xref linkend="libpq-PQconninfoParse"/>.
613 Conversely, if an error occurs and <literal>errmsg</literal> is not <symbol>NULL</symbol>,
614 be sure to free the error string using <xref linkend="libpq-PQfreemem"/>.
615 </para>
617 </listitem>
618 </varlistentry>
620 <varlistentry id="libpq-PQfinish">
621 <term><function>PQfinish</function><indexterm><primary>PQfinish</primary></indexterm></term>
622 <listitem>
623 <para>
624 Closes the connection to the server. Also frees
625 memory used by the <structname>PGconn</structname> object.
626 <synopsis>
627 void PQfinish(PGconn *conn);
628 </synopsis>
629 </para>
631 <para>
632 Note that even if the server connection attempt fails (as
633 indicated by <xref linkend="libpq-PQstatus"/>), the application should call <xref linkend="libpq-PQfinish"/>
634 to free the memory used by the <structname>PGconn</structname> object.
635 The <structname>PGconn</structname> pointer must not be used again after
636 <xref linkend="libpq-PQfinish"/> has been called.
637 </para>
638 </listitem>
639 </varlistentry>
641 <varlistentry id="libpq-PQreset">
642 <term><function>PQreset</function><indexterm><primary>PQreset</primary></indexterm></term>
643 <listitem>
644 <para>
645 Resets the communication channel to the server.
646 <synopsis>
647 void PQreset(PGconn *conn);
648 </synopsis>
649 </para>
651 <para>
652 This function will close the connection
653 to the server and attempt to establish a new
654 connection, using all the same
655 parameters previously used. This might be useful for
656 error recovery if a working connection is lost.
657 </para>
658 </listitem>
659 </varlistentry>
661 <varlistentry id="libpq-PQresetStart">
662 <term><function>PQresetStart</function><indexterm><primary>PQresetStart</primary></indexterm></term>
663 <term><function>PQresetPoll</function><indexterm><primary>PQresetPoll</primary></indexterm></term>
664 <listitem>
665 <para>
666 Reset the communication channel to the server, in a nonblocking manner.
668 <synopsis>
669 int PQresetStart(PGconn *conn);
671 PostgresPollingStatusType PQresetPoll(PGconn *conn);
672 </synopsis>
673 </para>
675 <para>
676 These functions will close the connection to the server and attempt to
677 establish a new connection, using all the same
678 parameters previously used. This can be useful for error recovery if a
679 working connection is lost. They differ from <xref linkend="libpq-PQreset"/> (above) in that they
680 act in a nonblocking manner. These functions suffer from the same
681 restrictions as <xref linkend="libpq-PQconnectStartParams"/>, <function>PQconnectStart</function>
682 and <function>PQconnectPoll</function>.
683 </para>
685 <para>
686 To initiate a connection reset, call
687 <xref linkend="libpq-PQresetStart"/>. If it returns 0, the reset has
688 failed. If it returns 1, poll the reset using
689 <function>PQresetPoll</function> in exactly the same way as you
690 would create the connection using <function>PQconnectPoll</function>.
691 </para>
692 </listitem>
693 </varlistentry>
695 <varlistentry id="libpq-PQpingParams">
696 <term><function>PQpingParams</function><indexterm><primary>PQpingParams</primary></indexterm></term>
697 <listitem>
698 <para>
699 <xref linkend="libpq-PQpingParams"/> reports the status of the
700 server. It accepts connection parameters identical to those of
701 <xref linkend="libpq-PQconnectdbParams"/>, described above. It is not
702 necessary to supply correct user name, password, or database name
703 values to obtain the server status; however, if incorrect values
704 are provided, the server will log a failed connection attempt.
706 <synopsis>
707 PGPing PQpingParams(const char * const *keywords,
708 const char * const *values,
709 int expand_dbname);
710 </synopsis>
712 The function returns one of the following values:
714 <variablelist>
715 <varlistentry id="libpq-PQpingParams-PQPING_OK">
716 <term><literal>PQPING_OK</literal></term>
717 <listitem>
718 <para>
719 The server is running and appears to be accepting connections.
720 </para>
721 </listitem>
722 </varlistentry>
724 <varlistentry id="libpq-PQpingParams-PQPING_REJECT">
725 <term><literal>PQPING_REJECT</literal></term>
726 <listitem>
727 <para>
728 The server is running but is in a state that disallows connections
729 (startup, shutdown, or crash recovery).
730 </para>
731 </listitem>
732 </varlistentry>
734 <varlistentry id="libpq-PQpingParams-PQPING_NO_RESPONSE">
735 <term><literal>PQPING_NO_RESPONSE</literal></term>
736 <listitem>
737 <para>
738 The server could not be contacted. This might indicate that the
739 server is not running, or that there is something wrong with the
740 given connection parameters (for example, wrong port number), or
741 that there is a network connectivity problem (for example, a
742 firewall blocking the connection request).
743 </para>
744 </listitem>
745 </varlistentry>
747 <varlistentry id="libpq-PQpingParams-PQPING_NO_ATTEMPT">
748 <term><literal>PQPING_NO_ATTEMPT</literal></term>
749 <listitem>
750 <para>
751 No attempt was made to contact the server, because the supplied
752 parameters were obviously incorrect or there was some client-side
753 problem (for example, out of memory).
754 </para>
755 </listitem>
756 </varlistentry>
757 </variablelist>
759 </para>
761 </listitem>
762 </varlistentry>
764 <varlistentry id="libpq-PQping">
765 <term><function>PQping</function><indexterm><primary>PQping</primary></indexterm></term>
766 <listitem>
767 <para>
768 <xref linkend="libpq-PQping"/> reports the status of the
769 server. It accepts connection parameters identical to those of
770 <xref linkend="libpq-PQconnectdb"/>, described above. It is not
771 necessary to supply correct user name, password, or database name
772 values to obtain the server status; however, if incorrect values
773 are provided, the server will log a failed connection attempt.
775 <synopsis>
776 PGPing PQping(const char *conninfo);
777 </synopsis>
778 </para>
780 <para>
781 The return values are the same as for <xref linkend="libpq-PQpingParams"/>.
782 </para>
784 </listitem>
785 </varlistentry>
787 <varlistentry id="libpq-pqsetsslkeypasshook-openssl">
788 <term><function>PQsetSSLKeyPassHook_OpenSSL</function><indexterm><primary>PQsetSSLKeyPassHook_OpenSSL</primary></indexterm></term>
789 <listitem>
790 <para>
791 <function>PQsetSSLKeyPassHook_OpenSSL</function> lets an application override
792 <application>libpq</application>'s <link linkend="libpq-ssl-clientcert">default
793 handling of encrypted client certificate key files</link> using
794 <xref linkend="libpq-connect-sslpassword"/> or interactive prompting.
796 <synopsis>
797 void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook);
798 </synopsis>
800 The application passes a pointer to a callback function with signature:
801 <programlisting>
802 int callback_fn(char *buf, int size, PGconn *conn);
803 </programlisting>
804 which <application>libpq</application> will then call
805 <emphasis>instead of</emphasis> its default
806 <function>PQdefaultSSLKeyPassHook_OpenSSL</function> handler. The
807 callback should determine the password for the key and copy it to
808 result-buffer <parameter>buf</parameter> of size
809 <parameter>size</parameter>. The string in <parameter>buf</parameter>
810 must be null-terminated. The callback must return the length of the
811 password stored in <parameter>buf</parameter> excluding the null
812 terminator. On failure, the callback should set
813 <literal>buf[0] = '\0'</literal> and return 0. See
814 <function>PQdefaultSSLKeyPassHook_OpenSSL</function> in
815 <application>libpq</application>'s source code for an example.
816 </para>
818 <para>
819 If the user specified an explicit key location,
820 its path will be in <literal>conn->sslkey</literal> when the callback
821 is invoked. This will be empty if the default key path is being used.
822 For keys that are engine specifiers, it is up to engine implementations
823 whether they use the <productname>OpenSSL</productname> password
824 callback or define their own handling.
825 </para>
827 <para>
828 The app callback may choose to delegate unhandled cases to
829 <function>PQdefaultSSLKeyPassHook_OpenSSL</function>,
830 or call it first and try something else if it returns 0, or completely override it.
831 </para>
833 <para>
834 The callback <emphasis>must not</emphasis> escape normal flow control with exceptions,
835 <function>longjmp(...)</function>, etc. It must return normally.
836 </para>
838 </listitem>
839 </varlistentry>
841 <varlistentry id="libpq-pqgetsslkeypasshook-openssl">
842 <term><function>PQgetSSLKeyPassHook_OpenSSL</function><indexterm><primary>PQgetSSLKeyPassHook_OpenSSL</primary></indexterm></term>
843 <listitem>
844 <para>
845 <function>PQgetSSLKeyPassHook_OpenSSL</function> returns the current
846 client certificate key password hook, or <literal>NULL</literal>
847 if none has been set.
849 <synopsis>
850 PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void);
851 </synopsis>
852 </para>
854 </listitem>
855 </varlistentry>
857 </variablelist>
858 </para>
860 <sect2 id="libpq-connstring">
861 <title>Connection Strings</title>
863 <indexterm zone="libpq-connstring">
864 <primary><literal>conninfo</literal></primary>
865 </indexterm>
867 <indexterm zone="libpq-connstring">
868 <primary><literal>URI</literal></primary>
869 </indexterm>
871 <para>
872 Several <application>libpq</application> functions parse a user-specified string to obtain
873 connection parameters. There are two accepted formats for these strings:
874 plain keyword/value strings
875 and URIs. URIs generally follow
876 <ulink url="https://tools.ietf.org/html/rfc3986">RFC
877 3986</ulink>, except that multi-host connection strings are allowed
878 as further described below.
879 </para>
881 <sect3 id="libpq-connstring-keyword-value">
882 <title>Keyword/Value Connection Strings</title>
884 <para>
885 In the keyword/value format, each parameter setting is in the form
886 <replaceable>keyword</replaceable> <literal>=</literal>
887 <replaceable>value</replaceable>, with space(s) between settings.
888 Spaces around a setting's equal sign are
889 optional. To write an empty value, or a value containing spaces, surround it
890 with single quotes, for example <literal>keyword = 'a value'</literal>.
891 Single quotes and backslashes within
892 a value must be escaped with a backslash, i.e., <literal>\'</literal> and
893 <literal>\\</literal>.
894 </para>
896 <para>
897 Example:
898 <programlisting>
899 host=localhost port=5432 dbname=mydb connect_timeout=10
900 </programlisting>
901 </para>
903 <para>
904 The recognized parameter key words are listed in <xref
905 linkend="libpq-paramkeywords"/>.
906 </para>
907 </sect3>
909 <sect3 id="libpq-connstring-uris">
910 <title>Connection URIs</title>
912 <para>
913 The general form for a connection <acronym>URI</acronym> is:
914 <synopsis>
915 postgresql://<optional><replaceable>userspec</replaceable>@</optional><optional><replaceable>hostspec</replaceable></optional><optional>/<replaceable>dbname</replaceable></optional><optional>?<replaceable>paramspec</replaceable></optional>
917 <phrase>where <replaceable>userspec</replaceable> is:</phrase>
919 <replaceable>user</replaceable><optional>:<replaceable>password</replaceable></optional>
921 <phrase>and <replaceable>hostspec</replaceable> is:</phrase>
923 <optional><replaceable>host</replaceable></optional><optional>:<replaceable>port</replaceable></optional><optional>,...</optional>
925 <phrase>and <replaceable>paramspec</replaceable> is:</phrase>
927 <replaceable>name</replaceable>=<replaceable>value</replaceable><optional>&amp;...</optional>
928 </synopsis>
929 </para>
931 <para>
932 The <acronym>URI</acronym> scheme designator can be either
933 <literal>postgresql://</literal> or <literal>postgres://</literal>. Each
934 of the remaining <acronym>URI</acronym> parts is optional. The
935 following examples illustrate valid <acronym>URI</acronym> syntax:
936 <programlisting>
937 postgresql://
938 postgresql://localhost
939 postgresql://localhost:5433
940 postgresql://localhost/mydb
941 postgresql://user@localhost
942 postgresql://user:secret@localhost
943 postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp
944 postgresql://host1:123,host2:456/somedb?target_session_attrs=any&amp;application_name=myapp
945 </programlisting>
946 Values that would normally appear in the hierarchical part of
947 the <acronym>URI</acronym> can alternatively be given as named
948 parameters. For example:
949 <programlisting>
950 postgresql:///mydb?host=localhost&amp;port=5433
951 </programlisting>
952 All named parameters must match key words listed in
953 <xref linkend="libpq-paramkeywords"/>, except that for compatibility
954 with JDBC connection <acronym>URI</acronym>s, instances
955 of <literal>ssl=true</literal> are translated into
956 <literal>sslmode=require</literal>.
957 </para>
959 <para>
960 The connection <acronym>URI</acronym> needs to be encoded with <ulink
961 url="https://tools.ietf.org/html/rfc3986#section-2.1">percent-encoding</ulink>
962 if it includes symbols with special meaning in any of its parts. Here is
963 an example where the equal sign (<literal>=</literal>) is replaced with
964 <literal>%3D</literal> and the space character with
965 <literal>%20</literal>:
966 <programlisting>
967 postgresql://user@localhost:5433/mydb?options=-c%20synchronous_commit%3Doff
968 </programlisting>
969 </para>
971 <para>
972 The host part may be either a host name or an IP address. To specify an
973 IPv6 address, enclose it in square brackets:
974 <synopsis>
975 postgresql://[2001:db8::1234]/database
976 </synopsis>
977 </para>
979 <para>
980 The host part is interpreted as described for the parameter <xref
981 linkend="libpq-connect-host"/>. In particular, a Unix-domain socket
982 connection is chosen if the host part is either empty or looks like an
983 absolute path name,
984 otherwise a TCP/IP connection is initiated. Note, however, that the
985 slash is a reserved character in the hierarchical part of the URI. So, to
986 specify a non-standard Unix-domain socket directory, either omit the host
987 part of the URI and specify the host as a named parameter, or
988 percent-encode the path in the host part of the URI:
989 <programlisting>
990 postgresql:///dbname?host=/var/lib/postgresql
991 postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
992 </programlisting>
993 </para>
995 <para>
996 It is possible to specify multiple host components, each with an optional
997 port component, in a single URI. A URI of the form
998 <literal>postgresql://host1:port1,host2:port2,host3:port3/</literal>
999 is equivalent to a connection string of the form
1000 <literal>host=host1,host2,host3 port=port1,port2,port3</literal>.
1001 As further described below, each
1002 host will be tried in turn until a connection is successfully established.
1003 </para>
1004 </sect3>
1006 <sect3 id="libpq-multiple-hosts">
1007 <title>Specifying Multiple Hosts</title>
1009 <para>
1010 It is possible to specify multiple hosts to connect to, so that they are
1011 tried in the given order. In the Keyword/Value format, the <literal>host</literal>,
1012 <literal>hostaddr</literal>, and <literal>port</literal> options accept comma-separated
1013 lists of values. The same number of elements must be given in each
1014 option that is specified, such
1015 that e.g., the first <literal>hostaddr</literal> corresponds to the first host name,
1016 the second <literal>hostaddr</literal> corresponds to the second host name, and so
1017 forth. As an exception, if only one <literal>port</literal> is specified, it
1018 applies to all the hosts.
1019 </para>
1021 <para>
1022 In the connection URI format, you can list multiple <literal>host:port</literal> pairs
1023 separated by commas in the <literal>host</literal> component of the URI.
1024 </para>
1026 <para>
1027 In either format, a single host name can translate to multiple network
1028 addresses. A common example of this is a host that has both an IPv4 and
1029 an IPv6 address.
1030 </para>
1032 <para>
1033 When multiple hosts are specified, or when a single host name is
1034 translated to multiple addresses, all the hosts and addresses will be
1035 tried in order, until one succeeds. If none of the hosts can be reached,
1036 the connection fails. If a connection is established successfully, but
1037 authentication fails, the remaining hosts in the list are not tried.
1038 </para>
1040 <para>
1041 If a password file is used, you can have different passwords for
1042 different hosts. All the other connection options are the same for every
1043 host in the list; it is not possible to e.g., specify different
1044 usernames for different hosts.
1045 </para>
1046 </sect3>
1047 </sect2>
1049 <sect2 id="libpq-paramkeywords">
1050 <title>Parameter Key Words</title>
1052 <para>
1053 The currently recognized parameter key words are:
1055 <variablelist>
1056 <varlistentry id="libpq-connect-host" xreflabel="host">
1057 <term><literal>host</literal></term>
1058 <listitem>
1059 <para>
1060 Name of host to connect to.<indexterm><primary>host
1061 name</primary></indexterm> If a host name looks like an absolute path
1062 name, it specifies Unix-domain communication rather than TCP/IP
1063 communication; the value is the name of the directory in which the
1064 socket file is stored. (On Unix, an absolute path name begins with a
1065 slash. On Windows, paths starting with drive letters are also
1066 recognized.) If the host name starts with <literal>@</literal>, it is
1067 taken as a Unix-domain socket in the abstract namespace (currently
1068 supported on Linux and Windows).
1069 The default behavior when <literal>host</literal> is not
1070 specified, or is empty, is to connect to a Unix-domain
1071 socket<indexterm><primary>Unix domain socket</primary></indexterm> in
1072 <filename>/tmp</filename> (or whatever socket directory was specified
1073 when <productname>PostgreSQL</productname> was built). On Windows,
1074 the default is to connect to <literal>localhost</literal>.
1075 </para>
1076 <para>
1077 A comma-separated list of host names is also accepted, in which case
1078 each host name in the list is tried in order; an empty item in the
1079 list selects the default behavior as explained above. See
1080 <xref linkend="libpq-multiple-hosts"/> for details.
1081 </para>
1082 </listitem>
1083 </varlistentry>
1085 <varlistentry id="libpq-connect-hostaddr" xreflabel="hostaddr">
1086 <term><literal>hostaddr</literal></term>
1087 <listitem>
1088 <para>
1089 Numeric IP address of host to connect to. This should be in the
1090 standard IPv4 address format, e.g., <literal>172.28.40.9</literal>. If
1091 your machine supports IPv6, you can also use those addresses.
1092 TCP/IP communication is
1093 always used when a nonempty string is specified for this parameter.
1094 If this parameter is not specified, the value of <literal>host</literal>
1095 will be looked up to find the corresponding IP address &mdash; or, if
1096 <literal>host</literal> specifies an IP address, that value will be
1097 used directly.
1098 </para>
1100 <para>
1101 Using <literal>hostaddr</literal> allows the
1102 application to avoid a host name look-up, which might be important
1103 in applications with time constraints. However, a host name is
1104 required for GSSAPI or SSPI authentication
1105 methods, as well as for <literal>verify-full</literal> SSL
1106 certificate verification. The following rules are used:
1107 <itemizedlist>
1108 <listitem>
1109 <para>
1110 If <literal>host</literal> is specified
1111 without <literal>hostaddr</literal>, a host name lookup occurs.
1112 (When using <function>PQconnectPoll</function>, the lookup occurs
1113 when <function>PQconnectPoll</function> first considers this host
1114 name, and it may cause <function>PQconnectPoll</function> to block
1115 for a significant amount of time.)
1116 </para>
1117 </listitem>
1118 <listitem>
1119 <para>
1120 If <literal>hostaddr</literal> is specified without <literal>host</literal>,
1121 the value for <literal>hostaddr</literal> gives the server network address.
1122 The connection attempt will fail if the authentication
1123 method requires a host name.
1124 </para>
1125 </listitem>
1126 <listitem>
1127 <para>
1128 If both <literal>host</literal> and <literal>hostaddr</literal> are specified,
1129 the value for <literal>hostaddr</literal> gives the server network address.
1130 The value for <literal>host</literal> is ignored unless the
1131 authentication method requires it, in which case it will be
1132 used as the host name.
1133 </para>
1134 </listitem>
1135 </itemizedlist>
1136 Note that authentication is likely to fail if <literal>host</literal>
1137 is not the name of the server at network address <literal>hostaddr</literal>.
1138 Also, when both <literal>host</literal> and <literal>hostaddr</literal>
1139 are specified, <literal>host</literal>
1140 is used to identify the connection in a password file (see
1141 <xref linkend="libpq-pgpass"/>).
1142 </para>
1144 <para>
1145 A comma-separated list of <literal>hostaddr</literal> values is also
1146 accepted, in which case each host in the list is tried in order.
1147 An empty item in the list causes the corresponding host name to be
1148 used, or the default host name if that is empty as well. See
1149 <xref linkend="libpq-multiple-hosts"/> for details.
1150 </para>
1151 <para>
1152 Without either a host name or host address,
1153 <application>libpq</application> will connect using a local
1154 Unix-domain socket; or on Windows, it will attempt to connect to
1155 <literal>localhost</literal>.
1156 </para>
1157 </listitem>
1158 </varlistentry>
1160 <varlistentry id="libpq-connect-port" xreflabel="port">
1161 <term><literal>port</literal></term>
1162 <listitem>
1163 <para>
1164 Port number to connect to at the server host, or socket file
1165 name extension for Unix-domain
1166 connections.<indexterm><primary>port</primary></indexterm>
1167 If multiple hosts were given in the <literal>host</literal> or
1168 <literal>hostaddr</literal> parameters, this parameter may specify a
1169 comma-separated list of ports of the same length as the host list, or
1170 it may specify a single port number to be used for all hosts.
1171 An empty string, or an empty item in a comma-separated list,
1172 specifies the default port number established
1173 when <productname>PostgreSQL</productname> was built.
1174 </para>
1175 </listitem>
1176 </varlistentry>
1178 <varlistentry id="libpq-connect-dbname" xreflabel="dbname">
1179 <term><literal>dbname</literal></term>
1180 <listitem>
1181 <para>
1182 The database name. Defaults to be the same as the user name.
1183 In certain contexts, the value is checked for extended
1184 formats; see <xref linkend="libpq-connstring"/> for more details on
1185 those.
1186 </para>
1187 </listitem>
1188 </varlistentry>
1190 <varlistentry id="libpq-connect-user" xreflabel="user">
1191 <term><literal>user</literal></term>
1192 <listitem>
1193 <para>
1194 <productname>PostgreSQL</productname> user name to connect as.
1195 Defaults to be the same as the operating system name of the user
1196 running the application.
1197 </para>
1198 </listitem>
1199 </varlistentry>
1201 <varlistentry id="libpq-connect-password" xreflabel="password">
1202 <term><literal>password</literal></term>
1203 <listitem>
1204 <para>
1205 Password to be used if the server demands password authentication.
1206 </para>
1207 </listitem>
1208 </varlistentry>
1210 <varlistentry id="libpq-connect-passfile" xreflabel="passfile">
1211 <term><literal>passfile</literal></term>
1212 <listitem>
1213 <para>
1214 Specifies the name of the file used to store passwords
1215 (see <xref linkend="libpq-pgpass"/>).
1216 Defaults to <filename>~/.pgpass</filename>, or
1217 <filename>%APPDATA%\postgresql\pgpass.conf</filename> on Microsoft Windows.
1218 (No error is reported if this file does not exist.)
1219 </para>
1220 </listitem>
1221 </varlistentry>
1223 <varlistentry id="libpq-connect-require-auth" xreflabel="require_auth">
1224 <term><literal>require_auth</literal></term>
1225 <listitem>
1226 <para>
1227 Specifies the authentication method that the client requires from the
1228 server. If the server does not use the required method to authenticate
1229 the client, or if the authentication handshake is not fully completed by
1230 the server, the connection will fail. A comma-separated list of methods
1231 may also be provided, of which the server must use exactly one in order
1232 for the connection to succeed. By default, any authentication method is
1233 accepted, and the server is free to skip authentication altogether.
1234 </para>
1235 <para>
1236 Methods may be negated with the addition of a <literal>!</literal>
1237 prefix, in which case the server must <emphasis>not</emphasis> attempt
1238 the listed method; any other method is accepted, and the server is free
1239 not to authenticate the client at all. If a comma-separated list is
1240 provided, the server may not attempt <emphasis>any</emphasis> of the
1241 listed negated methods. Negated and non-negated forms may not be
1242 combined in the same setting.
1243 </para>
1244 <para>
1245 As a final special case, the <literal>none</literal> method requires the
1246 server not to use an authentication challenge. (It may also be negated,
1247 to require some form of authentication.)
1248 </para>
1249 <para>
1250 The following methods may be specified:
1252 <variablelist>
1253 <varlistentry>
1254 <term><literal>password</literal></term>
1255 <listitem>
1256 <para>
1257 The server must request plaintext password authentication.
1258 </para>
1259 </listitem>
1260 </varlistentry>
1262 <varlistentry>
1263 <term><literal>md5</literal></term>
1264 <listitem>
1265 <para>
1266 The server must request MD5 hashed password authentication.
1267 </para>
1268 </listitem>
1269 </varlistentry>
1271 <varlistentry>
1272 <term><literal>gss</literal></term>
1273 <listitem>
1274 <para>
1275 The server must either request a Kerberos handshake via
1276 <acronym>GSSAPI</acronym> or establish a
1277 <acronym>GSS</acronym>-encrypted channel (see also
1278 <xref linkend="libpq-connect-gssencmode" />).
1279 </para>
1280 </listitem>
1281 </varlistentry>
1283 <varlistentry>
1284 <term><literal>sspi</literal></term>
1285 <listitem>
1286 <para>
1287 The server must request Windows <acronym>SSPI</acronym>
1288 authentication.
1289 </para>
1290 </listitem>
1291 </varlistentry>
1293 <varlistentry>
1294 <term><literal>scram-sha-256</literal></term>
1295 <listitem>
1296 <para>
1297 The server must successfully complete a SCRAM-SHA-256 authentication
1298 exchange with the client.
1299 </para>
1300 </listitem>
1301 </varlistentry>
1303 <varlistentry>
1304 <term><literal>none</literal></term>
1305 <listitem>
1306 <para>
1307 The server must not prompt the client for an authentication
1308 exchange. (This does not prohibit client certificate authentication
1309 via TLS, nor GSS authentication via its encrypted transport.)
1310 </para>
1311 </listitem>
1312 </varlistentry>
1313 </variablelist>
1314 </para>
1315 </listitem>
1316 </varlistentry>
1318 <varlistentry id="libpq-connect-channel-binding" xreflabel="channel_binding">
1319 <term><literal>channel_binding</literal></term>
1320 <listitem>
1321 <para>
1322 This option controls the client's use of channel binding. A setting
1323 of <literal>require</literal> means that the connection must employ
1324 channel binding, <literal>prefer</literal> means that the client will
1325 choose channel binding if available, and <literal>disable</literal>
1326 prevents the use of channel binding. The default
1327 is <literal>prefer</literal> if
1328 <productname>PostgreSQL</productname> is compiled with SSL support;
1329 otherwise the default is <literal>disable</literal>.
1330 </para>
1331 <para>
1332 Channel binding is a method for the server to authenticate itself to
1333 the client. It is only supported over SSL connections
1334 with <productname>PostgreSQL</productname> 11 or later servers using
1335 the <literal>SCRAM</literal> authentication method.
1336 </para>
1337 </listitem>
1338 </varlistentry>
1340 <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout">
1341 <term><literal>connect_timeout</literal></term>
1342 <listitem>
1343 <para>
1344 Maximum time to wait while connecting, in seconds (write as a decimal integer,
1345 e.g., <literal>10</literal>). Zero, negative, or not specified means
1346 wait indefinitely. The minimum allowed timeout is 2 seconds, therefore
1347 a value of <literal>1</literal> is interpreted as <literal>2</literal>.
1348 This timeout applies separately to each host name or IP address.
1349 For example, if you specify two hosts and <literal>connect_timeout</literal>
1350 is 5, each host will time out if no connection is made within 5
1351 seconds, so the total time spent waiting for a connection might be
1352 up to 10 seconds.
1353 </para>
1354 </listitem>
1355 </varlistentry>
1357 <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding">
1358 <term><literal>client_encoding</literal></term>
1359 <listitem>
1360 <para>
1361 This sets the <varname>client_encoding</varname>
1362 configuration parameter for this connection. In addition to
1363 the values accepted by the corresponding server option, you
1364 can use <literal>auto</literal> to determine the right
1365 encoding from the current locale in the client
1366 (<envar>LC_CTYPE</envar> environment variable on Unix
1367 systems).
1368 </para>
1369 </listitem>
1370 </varlistentry>
1372 <varlistentry id="libpq-connect-options" xreflabel="options">
1373 <term><literal>options</literal></term>
1374 <listitem>
1375 <para>
1376 Specifies command-line options to send to the server at connection
1377 start. For example, setting this to <literal>-c geqo=off</literal> sets the
1378 session's value of the <varname>geqo</varname> parameter to
1379 <literal>off</literal>. Spaces within this string are considered to
1380 separate command-line arguments, unless escaped with a backslash
1381 (<literal>\</literal>); write <literal>\\</literal> to represent a literal
1382 backslash. For a detailed discussion of the available
1383 options, consult <xref linkend="runtime-config"/>.
1384 </para>
1385 </listitem>
1386 </varlistentry>
1388 <varlistentry id="libpq-connect-application-name" xreflabel="application_name">
1389 <term><literal>application_name</literal></term>
1390 <listitem>
1391 <para>
1392 Specifies a value for the <xref linkend="guc-application-name"/>
1393 configuration parameter.
1394 </para>
1395 </listitem>
1396 </varlistentry>
1398 <varlistentry id="libpq-connect-fallback-application-name" xreflabel="fallback_application_name">
1399 <term><literal>fallback_application_name</literal></term>
1400 <listitem>
1401 <para>
1402 Specifies a fallback value for the <xref
1403 linkend="guc-application-name"/> configuration parameter.
1404 This value will be used if no value has been given for
1405 <literal>application_name</literal> via a connection parameter or the
1406 <envar>PGAPPNAME</envar> environment variable. Specifying
1407 a fallback name is useful in generic utility programs that
1408 wish to set a default application name but allow it to be
1409 overridden by the user.
1410 </para>
1411 </listitem>
1412 </varlistentry>
1414 <varlistentry id="libpq-keepalives" xreflabel="keepalives">
1415 <term><literal>keepalives</literal></term>
1416 <listitem>
1417 <para>
1418 Controls whether client-side TCP keepalives are used. The default
1419 value is 1, meaning on, but you can change this to 0, meaning off,
1420 if keepalives are not wanted. This parameter is ignored for
1421 connections made via a Unix-domain socket.
1422 </para>
1423 </listitem>
1424 </varlistentry>
1426 <varlistentry id="libpq-keepalives-idle" xreflabel="keepalives_idle">
1427 <term><literal>keepalives_idle</literal></term>
1428 <listitem>
1429 <para>
1430 Controls the number of seconds of inactivity after which TCP should
1431 send a keepalive message to the server. A value of zero uses the
1432 system default. This parameter is ignored for connections made via a
1433 Unix-domain socket, or if keepalives are disabled.
1434 It is only supported on systems where <symbol>TCP_KEEPIDLE</symbol> or
1435 an equivalent socket option is available, and on Windows; on other
1436 systems, it has no effect.
1437 </para>
1438 </listitem>
1439 </varlistentry>
1441 <varlistentry id="libpq-keepalives-interval" xreflabel="keepalives_interval">
1442 <term><literal>keepalives_interval</literal></term>
1443 <listitem>
1444 <para>
1445 Controls the number of seconds after which a TCP keepalive message
1446 that is not acknowledged by the server should be retransmitted. A
1447 value of zero uses the system default. This parameter is ignored for
1448 connections made via a Unix-domain socket, or if keepalives are disabled.
1449 It is only supported on systems where <symbol>TCP_KEEPINTVL</symbol> or
1450 an equivalent socket option is available, and on Windows; on other
1451 systems, it has no effect.
1452 </para>
1453 </listitem>
1454 </varlistentry>
1456 <varlistentry id="libpq-keepalives-count" xreflabel="keepalives_count">
1457 <term><literal>keepalives_count</literal></term>
1458 <listitem>
1459 <para>
1460 Controls the number of TCP keepalives that can be lost before the
1461 client's connection to the server is considered dead. A value of
1462 zero uses the system default. This parameter is ignored for
1463 connections made via a Unix-domain socket, or if keepalives are disabled.
1464 It is only supported on systems where <symbol>TCP_KEEPCNT</symbol> or
1465 an equivalent socket option is available; on other systems, it has no
1466 effect.
1467 </para>
1468 </listitem>
1469 </varlistentry>
1471 <varlistentry id="libpq-tcp-user-timeout" xreflabel="tcp_user_timeout">
1472 <term><literal>tcp_user_timeout</literal></term>
1473 <listitem>
1474 <para>
1475 Controls the number of milliseconds that transmitted data may
1476 remain unacknowledged before a connection is forcibly closed.
1477 A value of zero uses the system default. This parameter is
1478 ignored for connections made via a Unix-domain socket.
1479 It is only supported on systems where <symbol>TCP_USER_TIMEOUT</symbol>
1480 is available; on other systems, it has no effect.
1481 </para>
1482 </listitem>
1483 </varlistentry>
1485 <varlistentry id="libpq-connect-replication" xreflabel="replication">
1486 <term><literal>replication</literal></term>
1487 <listitem>
1488 <para>
1489 This option determines whether the connection should use the
1490 replication protocol instead of the normal protocol. This is what
1491 PostgreSQL replication connections as well as tools such as
1492 <application>pg_basebackup</application> use internally, but it can
1493 also be used by third-party applications. For a description of the
1494 replication protocol, consult <xref linkend="protocol-replication"/>.
1495 </para>
1497 <para>
1498 The following values, which are case-insensitive, are supported:
1499 <variablelist>
1500 <varlistentry>
1501 <term>
1502 <literal>true</literal>, <literal>on</literal>,
1503 <literal>yes</literal>, <literal>1</literal>
1504 </term>
1505 <listitem>
1506 <para>
1507 The connection goes into physical replication mode.
1508 </para>
1509 </listitem>
1510 </varlistentry>
1512 <varlistentry>
1513 <term><literal>database</literal></term>
1514 <listitem>
1515 <para>
1516 The connection goes into logical replication mode, connecting to
1517 the database specified in the <literal>dbname</literal> parameter.
1518 </para>
1519 </listitem>
1520 </varlistentry>
1522 <varlistentry>
1523 <term>
1524 <literal>false</literal>, <literal>off</literal>,
1525 <literal>no</literal>, <literal>0</literal>
1526 </term>
1527 <listitem>
1528 <para>
1529 The connection is a regular one, which is the default behavior.
1530 </para>
1531 </listitem>
1532 </varlistentry>
1533 </variablelist>
1534 </para>
1536 <para>
1537 In physical or logical replication mode, only the simple query protocol
1538 can be used.
1539 </para>
1540 </listitem>
1541 </varlistentry>
1543 <varlistentry id="libpq-connect-gssencmode" xreflabel="gssencmode">
1544 <term><literal>gssencmode</literal></term>
1545 <listitem>
1546 <para>
1547 This option determines whether or with what priority a secure
1548 <acronym>GSS</acronym> TCP/IP connection will be negotiated with the
1549 server. There are three modes:
1551 <variablelist>
1552 <varlistentry>
1553 <term><literal>disable</literal></term>
1554 <listitem>
1555 <para>
1556 only try a non-<acronym>GSSAPI</acronym>-encrypted connection
1557 </para>
1558 </listitem>
1559 </varlistentry>
1561 <varlistentry>
1562 <term><literal>prefer</literal> (default)</term>
1563 <listitem>
1564 <para>
1565 if there are <acronym>GSSAPI</acronym> credentials present (i.e.,
1566 in a credentials cache), first try
1567 a <acronym>GSSAPI</acronym>-encrypted connection; if that fails or
1568 there are no credentials, try a
1569 non-<acronym>GSSAPI</acronym>-encrypted connection. This is the
1570 default when <productname>PostgreSQL</productname> has been
1571 compiled with <acronym>GSSAPI</acronym> support.
1572 </para>
1573 </listitem>
1574 </varlistentry>
1576 <varlistentry>
1577 <term><literal>require</literal></term>
1578 <listitem>
1579 <para>
1580 only try a <acronym>GSSAPI</acronym>-encrypted connection
1581 </para>
1582 </listitem>
1583 </varlistentry>
1584 </variablelist>
1585 </para>
1587 <para>
1588 <literal>gssencmode</literal> is ignored for Unix domain socket
1589 communication. If <productname>PostgreSQL</productname> is compiled
1590 without GSSAPI support, using the <literal>require</literal> option
1591 will cause an error, while <literal>prefer</literal> will be accepted
1592 but <application>libpq</application> will not actually attempt
1593 a <acronym>GSSAPI</acronym>-encrypted
1594 connection.<indexterm><primary>GSSAPI</primary><secondary sortas="libpq">with
1595 libpq</secondary></indexterm>
1596 </para>
1597 </listitem>
1598 </varlistentry>
1600 <varlistentry id="libpq-connect-sslmode" xreflabel="sslmode">
1601 <term><literal>sslmode</literal></term>
1602 <listitem>
1603 <para>
1604 This option determines whether or with what priority a secure
1605 <acronym>SSL</acronym> TCP/IP connection will be negotiated with the
1606 server. There are six modes:
1608 <variablelist>
1609 <varlistentry>
1610 <term><literal>disable</literal></term>
1611 <listitem>
1612 <para>
1613 only try a non-<acronym>SSL</acronym> connection
1614 </para>
1615 </listitem>
1616 </varlistentry>
1618 <varlistentry>
1619 <term><literal>allow</literal></term>
1620 <listitem>
1621 <para>
1622 first try a non-<acronym>SSL</acronym> connection; if that
1623 fails, try an <acronym>SSL</acronym> connection
1624 </para>
1625 </listitem>
1626 </varlistentry>
1628 <varlistentry>
1629 <term><literal>prefer</literal> (default)</term>
1630 <listitem>
1631 <para>
1632 first try an <acronym>SSL</acronym> connection; if that fails,
1633 try a non-<acronym>SSL</acronym> connection
1634 </para>
1635 </listitem>
1636 </varlistentry>
1638 <varlistentry>
1639 <term><literal>require</literal></term>
1640 <listitem>
1641 <para>
1642 only try an <acronym>SSL</acronym> connection. If a root CA
1643 file is present, verify the certificate in the same way as
1644 if <literal>verify-ca</literal> was specified
1645 </para>
1646 </listitem>
1647 </varlistentry>
1649 <varlistentry>
1650 <term><literal>verify-ca</literal></term>
1651 <listitem>
1652 <para>
1653 only try an <acronym>SSL</acronym> connection, and verify that
1654 the server certificate is issued by a trusted
1655 certificate authority (<acronym>CA</acronym>)
1656 </para>
1657 </listitem>
1658 </varlistentry>
1660 <varlistentry>
1661 <term><literal>verify-full</literal></term>
1662 <listitem>
1663 <para>
1664 only try an <acronym>SSL</acronym> connection, verify that the
1665 server certificate is issued by a
1666 trusted <acronym>CA</acronym> and that the requested server host name
1667 matches that in the certificate
1668 </para>
1669 </listitem>
1670 </varlistentry>
1671 </variablelist>
1673 See <xref linkend="libpq-ssl"/> for a detailed description of how
1674 these options work.
1675 </para>
1677 <para>
1678 <literal>sslmode</literal> is ignored for Unix domain socket
1679 communication.
1680 If <productname>PostgreSQL</productname> is compiled without SSL support,
1681 using options <literal>require</literal>, <literal>verify-ca</literal>, or
1682 <literal>verify-full</literal> will cause an error, while
1683 options <literal>allow</literal> and <literal>prefer</literal> will be
1684 accepted but <application>libpq</application> will not actually attempt
1685 an <acronym>SSL</acronym>
1686 connection.<indexterm><primary>SSL</primary><secondary
1687 sortas="libpq">with libpq</secondary></indexterm>
1688 </para>
1690 <para>
1691 Note that if <acronym>GSSAPI</acronym> encryption is possible,
1692 that will be used in preference to <acronym>SSL</acronym>
1693 encryption, regardless of the value of <literal>sslmode</literal>.
1694 To force use of <acronym>SSL</acronym> encryption in an
1695 environment that has working <acronym>GSSAPI</acronym>
1696 infrastructure (such as a Kerberos server), also
1697 set <literal>gssencmode</literal> to <literal>disable</literal>.
1698 </para>
1699 </listitem>
1700 </varlistentry>
1702 <varlistentry id="libpq-connect-requiressl" xreflabel="requiressl">
1703 <term><literal>requiressl</literal></term>
1704 <listitem>
1705 <para>
1706 This option is deprecated in favor of the <literal>sslmode</literal>
1707 setting.
1708 </para>
1710 <para>
1711 If set to 1, an <acronym>SSL</acronym> connection to the server
1712 is required (this is equivalent to <literal>sslmode</literal>
1713 <literal>require</literal>). <application>libpq</application> will then refuse
1714 to connect if the server does not accept an
1715 <acronym>SSL</acronym> connection. If set to 0 (default),
1716 <application>libpq</application> will negotiate the connection type with
1717 the server (equivalent to <literal>sslmode</literal>
1718 <literal>prefer</literal>). This option is only available if
1719 <productname>PostgreSQL</productname> is compiled with SSL support.
1720 </para>
1721 </listitem>
1722 </varlistentry>
1724 <varlistentry id="libpq-connect-sslcompression" xreflabel="sslcompression">
1725 <term><literal>sslcompression</literal></term>
1726 <listitem>
1727 <para>
1728 If set to 1, data sent over SSL connections will be compressed. If
1729 set to 0, compression will be disabled. The default is 0. This
1730 parameter is ignored if a connection without SSL is made.
1731 </para>
1733 <para>
1734 SSL compression is nowadays considered insecure and its use is no
1735 longer recommended. <productname>OpenSSL</productname> 1.1.0 disables
1736 compression by default, and many operating system distributions
1737 disable it in prior versions as well, so setting this parameter to on
1738 will not have any effect if the server does not accept compression.
1739 <productname>PostgreSQL</productname> 14 disables compression
1740 completely in the backend.
1741 </para>
1743 <para>
1744 If security is not a primary concern, compression can improve
1745 throughput if the network is the bottleneck. Disabling compression
1746 can improve response time and throughput if CPU performance is the
1747 limiting factor.
1748 </para>
1749 </listitem>
1750 </varlistentry>
1752 <varlistentry id="libpq-connect-sslcert" xreflabel="sslcert">
1753 <term><literal>sslcert</literal></term>
1754 <listitem>
1755 <para>
1756 This parameter specifies the file name of the client SSL
1757 certificate, replacing the default
1758 <filename>~/.postgresql/postgresql.crt</filename>.
1759 This parameter is ignored if an SSL connection is not made.
1760 </para>
1761 </listitem>
1762 </varlistentry>
1764 <varlistentry id="libpq-connect-sslkey" xreflabel="sslkey">
1765 <term><literal>sslkey</literal></term>
1766 <listitem>
1767 <para>
1768 This parameter specifies the location for the secret key used for
1769 the client certificate. It can either specify a file name that will
1770 be used instead of the default
1771 <filename>~/.postgresql/postgresql.key</filename>, or it can specify a key
1772 obtained from an external <quote>engine</quote> (engines are
1773 <productname>OpenSSL</productname> loadable modules). An external engine
1774 specification should consist of a colon-separated engine name and
1775 an engine-specific key identifier. This parameter is ignored if an
1776 SSL connection is not made.
1777 </para>
1778 </listitem>
1779 </varlistentry>
1781 <varlistentry id="libpq-connect-sslpassword" xreflabel="sslpassword">
1782 <term><literal>sslpassword</literal></term>
1783 <listitem>
1784 <para>
1785 This parameter specifies the password for the secret key specified in
1786 <literal>sslkey</literal>, allowing client certificate private keys
1787 to be stored in encrypted form on disk even when interactive passphrase
1788 input is not practical.
1789 </para>
1790 <para>
1791 Specifying this parameter with any non-empty value suppresses the
1792 <literal>Enter PEM pass phrase:</literal>
1793 prompt that <productname>OpenSSL</productname> will emit by default
1794 when an encrypted client certificate key is provided to
1795 <literal>libpq</literal>.
1796 </para>
1797 <para>
1798 If the key is not encrypted this parameter is ignored. The parameter
1799 has no effect on keys specified by <productname>OpenSSL</productname>
1800 engines unless the engine uses the <productname>OpenSSL</productname>
1801 password callback mechanism for prompts.
1802 </para>
1803 <para>
1804 There is no environment variable equivalent to this option, and no
1805 facility for looking it up in <filename>.pgpass</filename>. It can be
1806 used in a service file connection definition. Users with
1807 more sophisticated uses should consider using <productname>OpenSSL</productname> engines and
1808 tools like PKCS#11 or USB crypto offload devices.
1809 </para>
1810 </listitem>
1811 </varlistentry>
1813 <varlistentry id="libpq-connect-sslcertmode" xreflabel="sslcertmode">
1814 <term><literal>sslcertmode</literal></term>
1815 <listitem>
1816 <para>
1817 This option determines whether a client certificate may be sent to the
1818 server, and whether the server is required to request one. There are
1819 three modes:
1821 <variablelist>
1822 <varlistentry>
1823 <term><literal>disable</literal></term>
1824 <listitem>
1825 <para>
1826 A client certificate is never sent, even if one is available
1827 (default location or provided via
1828 <xref linkend="libpq-connect-sslcert" />).
1829 </para>
1830 </listitem>
1831 </varlistentry>
1833 <varlistentry>
1834 <term><literal>allow</literal> (default)</term>
1835 <listitem>
1836 <para>
1837 A certificate may be sent, if the server requests one and the
1838 client has one to send.
1839 </para>
1840 </listitem>
1841 </varlistentry>
1843 <varlistentry>
1844 <term><literal>require</literal></term>
1845 <listitem>
1846 <para>
1847 The server <emphasis>must</emphasis> request a certificate. The
1848 connection will fail if the client does not send a certificate and
1849 the server successfully authenticates the client anyway.
1850 </para>
1851 </listitem>
1852 </varlistentry>
1853 </variablelist>
1854 </para>
1856 <note>
1857 <para>
1858 <literal>sslcertmode=require</literal> doesn't add any additional
1859 security, since there is no guarantee that the server is validating
1860 the certificate correctly; PostgreSQL servers generally request TLS
1861 certificates from clients whether they validate them or not. The
1862 option may be useful when troubleshooting more complicated TLS
1863 setups.
1864 </para>
1865 </note>
1866 </listitem>
1867 </varlistentry>
1869 <varlistentry id="libpq-connect-sslrootcert" xreflabel="sslrootcert">
1870 <term><literal>sslrootcert</literal></term>
1871 <listitem>
1872 <para>
1873 This parameter specifies the name of a file containing SSL
1874 certificate authority (<acronym>CA</acronym>) certificate(s).
1875 If the file exists, the server's certificate will be verified
1876 to be signed by one of these authorities. The default is
1877 <filename>~/.postgresql/root.crt</filename>.
1878 </para>
1879 <para>
1880 The special value <literal>system</literal> may be specified instead, in
1881 which case the system's trusted CA roots will be loaded. The exact
1882 locations of these root certificates differ by SSL implementation and
1883 platform. For <productname>OpenSSL</productname> in particular, the
1884 locations may be further modified by the <envar>SSL_CERT_DIR</envar>
1885 and <envar>SSL_CERT_FILE</envar> environment variables.
1886 </para>
1887 <note>
1888 <para>
1889 When using <literal>sslrootcert=system</literal>, the default
1890 <literal>sslmode</literal> is changed to <literal>verify-full</literal>,
1891 and any weaker setting will result in an error. In most cases it is
1892 trivial for anyone to obtain a certificate trusted by the system for a
1893 hostname they control, rendering <literal>verify-ca</literal> and all
1894 weaker modes useless.
1895 </para>
1896 <para>
1897 The magic <literal>system</literal> value will take precedence over a
1898 local certificate file with the same name. If for some reason you find
1899 yourself in this situation, use an alternative path like
1900 <literal>sslrootcert=./system</literal> instead.
1901 </para>
1902 </note>
1903 </listitem>
1904 </varlistentry>
1906 <varlistentry id="libpq-connect-sslcrl" xreflabel="sslcrl">
1907 <term><literal>sslcrl</literal></term>
1908 <listitem>
1909 <para>
1910 This parameter specifies the file name of the SSL server certificate
1911 revocation list (CRL). Certificates listed in this file, if it
1912 exists, will be rejected while attempting to authenticate the
1913 server's certificate. If neither
1914 <xref linkend="libpq-connect-sslcrl"/> nor
1915 <xref linkend="libpq-connect-sslcrldir"/> is set, this setting is
1916 taken as
1917 <filename>~/.postgresql/root.crl</filename>.
1918 </para>
1919 </listitem>
1920 </varlistentry>
1922 <varlistentry id="libpq-connect-sslcrldir" xreflabel="sslcrldir">
1923 <term><literal>sslcrldir</literal></term>
1924 <listitem>
1925 <para>
1926 This parameter specifies the directory name of the SSL server certificate
1927 revocation list (CRL). Certificates listed in the files in this
1928 directory, if it exists, will be rejected while attempting to
1929 authenticate the server's certificate.
1930 </para>
1932 <para>
1933 The directory needs to be prepared with the
1934 <productname>OpenSSL</productname> command
1935 <literal>openssl rehash</literal> or <literal>c_rehash</literal>. See
1936 its documentation for details.
1937 </para>
1939 <para>
1940 Both <literal>sslcrl</literal> and <literal>sslcrldir</literal> can be
1941 specified together.
1942 </para>
1943 </listitem>
1944 </varlistentry>
1946 <varlistentry id="libpq-connect-sslsni" xreflabel="sslsni">
1947 <term><literal>sslsni</literal><indexterm><primary>Server Name Indication</primary></indexterm></term>
1948 <listitem>
1949 <para>
1950 If set to 1 (default), libpq sets the TLS extension <quote>Server Name
1951 Indication</quote> (<acronym>SNI</acronym>) on SSL-enabled connections.
1952 By setting this parameter to 0, this is turned off.
1953 </para>
1955 <para>
1956 The Server Name Indication can be used by SSL-aware proxies to route
1957 connections without having to decrypt the SSL stream. (Note that this
1958 requires a proxy that is aware of the PostgreSQL protocol handshake,
1959 not just any SSL proxy.) However, <acronym>SNI</acronym> makes the
1960 destination host name appear in cleartext in the network traffic, so
1961 it might be undesirable in some cases.
1962 </para>
1963 </listitem>
1964 </varlistentry>
1966 <varlistentry id="libpq-connect-requirepeer" xreflabel="requirepeer">
1967 <term><literal>requirepeer</literal></term>
1968 <listitem>
1969 <para>
1970 This parameter specifies the operating-system user name of the
1971 server, for example <literal>requirepeer=postgres</literal>.
1972 When making a Unix-domain socket connection, if this
1973 parameter is set, the client checks at the beginning of the
1974 connection that the server process is running under the specified
1975 user name; if it is not, the connection is aborted with an error.
1976 This parameter can be used to provide server authentication similar
1977 to that available with SSL certificates on TCP/IP connections.
1978 (Note that if the Unix-domain socket is in
1979 <filename>/tmp</filename> or another publicly writable location,
1980 any user could start a server listening there. Use this parameter
1981 to ensure that you are connected to a server run by a trusted user.)
1982 This option is only supported on platforms for which the
1983 <literal>peer</literal> authentication method is implemented; see
1984 <xref linkend="auth-peer"/>.
1985 </para>
1986 </listitem>
1987 </varlistentry>
1989 <varlistentry id="libpq-connect-ssl-min-protocol-version" xreflabel="ssl_min_protocol_version">
1990 <term><literal>ssl_min_protocol_version</literal></term>
1991 <listitem>
1992 <para>
1993 This parameter specifies the minimum SSL/TLS protocol version to allow
1994 for the connection. Valid values are <literal>TLSv1</literal>,
1995 <literal>TLSv1.1</literal>, <literal>TLSv1.2</literal> and
1996 <literal>TLSv1.3</literal>. The supported protocols depend on the
1997 version of <productname>OpenSSL</productname> used, older versions
1998 not supporting the most modern protocol versions. If not specified,
1999 the default is <literal>TLSv1.2</literal>, which satisfies industry
2000 best practices as of this writing.
2001 </para>
2002 </listitem>
2003 </varlistentry>
2005 <varlistentry id="libpq-connect-ssl-max-protocol-version" xreflabel="ssl_max_protocol_version">
2006 <term><literal>ssl_max_protocol_version</literal></term>
2007 <listitem>
2008 <para>
2009 This parameter specifies the maximum SSL/TLS protocol version to allow
2010 for the connection. Valid values are <literal>TLSv1</literal>,
2011 <literal>TLSv1.1</literal>, <literal>TLSv1.2</literal> and
2012 <literal>TLSv1.3</literal>. The supported protocols depend on the
2013 version of <productname>OpenSSL</productname> used, older versions
2014 not supporting the most modern protocol versions. If not set, this
2015 parameter is ignored and the connection will use the maximum bound
2016 defined by the backend, if set. Setting the maximum protocol version
2017 is mainly useful for testing or if some component has issues working
2018 with a newer protocol.
2019 </para>
2020 </listitem>
2021 </varlistentry>
2023 <varlistentry id="libpq-connect-krbsrvname" xreflabel="krbsrvname">
2024 <term><literal>krbsrvname</literal></term>
2025 <listitem>
2026 <para>
2027 Kerberos service name to use when authenticating with GSSAPI.
2028 This must match the service name specified in the server
2029 configuration for Kerberos authentication to succeed. (See also
2030 <xref linkend="gssapi-auth"/>.)
2031 The default value is normally <literal>postgres</literal>,
2032 but that can be changed when
2033 building <productname>PostgreSQL</productname> via
2034 the <option>--with-krb-srvnam</option> option
2035 of <application>configure</application>.
2036 In most environments, this parameter never needs to be changed.
2037 Some Kerberos implementations might require a different service name,
2038 such as Microsoft Active Directory which requires the service name
2039 to be in upper case (<literal>POSTGRES</literal>).
2040 </para>
2041 </listitem>
2042 </varlistentry>
2044 <varlistentry id="libpq-connect-gsslib" xreflabel="gsslib">
2045 <term><literal>gsslib</literal></term>
2046 <listitem>
2047 <para>
2048 GSS library to use for GSSAPI authentication.
2049 Currently this is disregarded except on Windows builds that include
2050 both GSSAPI and SSPI support. In that case, set
2051 this to <literal>gssapi</literal> to cause libpq to use the GSSAPI
2052 library for authentication instead of the default SSPI.
2053 </para>
2054 </listitem>
2055 </varlistentry>
2057 <varlistentry id="libpq-connect-gssdelegation" xreflabel="gssdelegation">
2058 <term><literal>gssdelegation</literal></term>
2059 <listitem>
2060 <para>
2061 Forward (delegate) GSS credentials to the server. The default is
2062 <literal>0</literal> which means credentials will not be forwarded
2063 to the server. Set this to <literal>1</literal> to have credentials
2064 forwarded when possible.
2065 </para>
2066 </listitem>
2067 </varlistentry>
2069 <varlistentry id="libpq-connect-service" xreflabel="service">
2070 <term><literal>service</literal></term>
2071 <listitem>
2072 <para>
2073 Service name to use for additional parameters. It specifies a service
2074 name in <filename>pg_service.conf</filename> that holds additional connection parameters.
2075 This allows applications to specify only a service name so connection parameters
2076 can be centrally maintained. See <xref linkend="libpq-pgservice"/>.
2077 </para>
2078 </listitem>
2079 </varlistentry>
2081 <varlistentry id="libpq-connect-target-session-attrs" xreflabel="target_session_attrs">
2082 <term><literal>target_session_attrs</literal></term>
2083 <listitem>
2084 <para>
2085 This option determines whether the session must have certain
2086 properties to be acceptable. It's typically used in combination
2087 with multiple host names to select the first acceptable alternative
2088 among several hosts. There are six modes:
2090 <variablelist>
2091 <varlistentry>
2092 <term><literal>any</literal> (default)</term>
2093 <listitem>
2094 <para>
2095 any successful connection is acceptable
2096 </para>
2097 </listitem>
2098 </varlistentry>
2100 <varlistentry>
2101 <term><literal>read-write</literal></term>
2102 <listitem>
2103 <para>
2104 session must accept read-write transactions by default (that
2105 is, the server must not be in hot standby mode and
2106 the <varname>default_transaction_read_only</varname> parameter
2107 must be <literal>off</literal>)
2108 </para>
2109 </listitem>
2110 </varlistentry>
2112 <varlistentry>
2113 <term><literal>read-only</literal></term>
2114 <listitem>
2115 <para>
2116 session must not accept read-write transactions by default (the
2117 converse)
2118 </para>
2119 </listitem>
2120 </varlistentry>
2122 <varlistentry>
2123 <term><literal>primary</literal></term>
2124 <listitem>
2125 <para>
2126 server must not be in hot standby mode
2127 </para>
2128 </listitem>
2129 </varlistentry>
2131 <varlistentry>
2132 <term><literal>standby</literal></term>
2133 <listitem>
2134 <para>
2135 server must be in hot standby mode
2136 </para>
2137 </listitem>
2138 </varlistentry>
2140 <varlistentry>
2141 <term><literal>prefer-standby</literal></term>
2142 <listitem>
2143 <para>
2144 first try to find a standby server, but if none of the listed
2145 hosts is a standby server, try again in <literal>any</literal>
2146 mode
2147 </para>
2148 </listitem>
2149 </varlistentry>
2150 </variablelist>
2151 </para>
2152 </listitem>
2153 </varlistentry>
2155 <varlistentry id="libpq-connect-load-balance-hosts" xreflabel="load_balance_hosts">
2156 <term><literal>load_balance_hosts</literal></term>
2157 <listitem>
2158 <para>
2159 Controls the order in which the client tries to connect to the available
2160 hosts and addresses. Once a connection attempt is successful no other
2161 hosts and addresses will be tried. This parameter is typically used in
2162 combination with multiple host names or a DNS record that returns
2163 multiple IPs. This parameter can be used in combination with
2164 <xref linkend="libpq-connect-target-session-attrs"/>
2165 to, for example, load balance over standby servers only. Once successfully
2166 connected, subsequent queries on the returned connection will all be
2167 sent to the same server. There are currently two modes:
2168 <variablelist>
2169 <varlistentry>
2170 <term><literal>disable</literal> (default)</term>
2171 <listitem>
2172 <para>
2173 No load balancing across hosts is performed. Hosts are tried in
2174 the order in which they are provided and addresses are tried in
2175 the order they are received from DNS or a hosts file.
2176 </para>
2177 </listitem>
2178 </varlistentry>
2180 <varlistentry>
2181 <term><literal>random</literal></term>
2182 <listitem>
2183 <para>
2184 Hosts and addresses are tried in random order. This value is mostly
2185 useful when opening multiple connections at the same time, possibly
2186 from different machines. This way connections can be load balanced
2187 across multiple <productname>PostgreSQL</productname> servers.
2188 </para>
2189 <para>
2190 While random load balancing, due to its random nature, will almost
2191 never result in a completely uniform distribution, it statistically
2192 gets quite close. One important aspect here is that this algorithm
2193 uses two levels of random choices: First the hosts
2194 will be resolved in random order. Then secondly, before resolving
2195 the next host, all resolved addresses for the current host will be
2196 tried in random order. This behaviour can skew the amount of
2197 connections each node gets greatly in certain cases, for instance
2198 when some hosts resolve to more addresses than others. But such a
2199 skew can also be used on purpose, e.g. to increase the number of
2200 connections a larger server gets by providing its hostname multiple
2201 times in the host string.
2202 </para>
2203 <para>
2204 When using this value it's recommended to also configure a reasonable
2205 value for <xref linkend="libpq-connect-connect-timeout"/>. Because then,
2206 if one of the nodes that are used for load balancing is not responding,
2207 a new node will be tried.
2208 </para>
2209 </listitem>
2210 </varlistentry>
2211 </variablelist>
2212 </para>
2213 </listitem>
2214 </varlistentry>
2215 </variablelist>
2216 </para>
2217 </sect2>
2218 </sect1>
2220 <sect1 id="libpq-status">
2221 <title>Connection Status Functions</title>
2223 <para>
2224 These functions can be used to interrogate the status
2225 of an existing database connection object.
2226 </para>
2228 <tip>
2229 <para>
2230 <indexterm><primary>libpq-fe.h</primary></indexterm>
2231 <indexterm><primary>libpq-int.h</primary></indexterm>
2232 <application>libpq</application> application programmers should be careful to
2233 maintain the <structname>PGconn</structname> abstraction. Use the accessor
2234 functions described below to get at the contents of <structname>PGconn</structname>.
2235 Reference to internal <structname>PGconn</structname> fields using
2236 <filename>libpq-int.h</filename> is not recommended because they are subject to change
2237 in the future.
2238 </para>
2239 </tip>
2241 <para>
2242 The following functions return parameter values established at connection.
2243 These values are fixed for the life of the connection. If a multi-host
2244 connection string is used, the values of <xref linkend="libpq-PQhost"/>,
2245 <xref linkend="libpq-PQport"/>, and <xref linkend="libpq-PQpass"/> can change if a new connection
2246 is established using the same <structname>PGconn</structname> object. Other values
2247 are fixed for the lifetime of the <structname>PGconn</structname> object.
2249 <variablelist>
2250 <varlistentry id="libpq-PQdb">
2251 <term><function>PQdb</function><indexterm><primary>PQdb</primary></indexterm></term>
2253 <listitem>
2254 <para>
2255 Returns the database name of the connection.
2256 <synopsis>
2257 char *PQdb(const PGconn *conn);
2258 </synopsis>
2259 </para>
2260 </listitem>
2261 </varlistentry>
2263 <varlistentry id="libpq-PQuser">
2264 <term><function>PQuser</function><indexterm><primary>PQuser</primary></indexterm></term>
2266 <listitem>
2267 <para>
2268 Returns the user name of the connection.
2269 <synopsis>
2270 char *PQuser(const PGconn *conn);
2271 </synopsis>
2272 </para>
2273 </listitem>
2274 </varlistentry>
2276 <varlistentry id="libpq-PQpass">
2277 <term><function>PQpass</function><indexterm><primary>PQpass</primary></indexterm></term>
2279 <listitem>
2280 <para>
2281 Returns the password of the connection.
2282 <synopsis>
2283 char *PQpass(const PGconn *conn);
2284 </synopsis>
2285 </para>
2287 <para>
2288 <xref linkend="libpq-PQpass"/> will return either the password specified
2289 in the connection parameters, or if there was none and the password
2290 was obtained from the <link linkend="libpq-pgpass">password
2291 file</link>, it will return that. In the latter case,
2292 if multiple hosts were specified in the connection parameters, it is
2293 not possible to rely on the result of <xref linkend="libpq-PQpass"/> until
2294 the connection is established. The status of the connection can be
2295 checked using the function <xref linkend="libpq-PQstatus"/>.
2296 </para>
2297 </listitem>
2298 </varlistentry>
2300 <varlistentry id="libpq-PQhost">
2301 <term><function>PQhost</function><indexterm><primary>PQhost</primary></indexterm></term>
2303 <listitem>
2304 <para>
2305 Returns the server host name of the active connection.
2306 This can be a host name, an IP address, or a directory path if the
2307 connection is via Unix socket. (The path case can be distinguished
2308 because it will always be an absolute path, beginning
2309 with <literal>/</literal>.)
2310 <synopsis>
2311 char *PQhost(const PGconn *conn);
2312 </synopsis>
2313 </para>
2315 <para>
2316 If the connection parameters specified both <literal>host</literal> and
2317 <literal>hostaddr</literal>, then <xref linkend="libpq-PQhost"/> will
2318 return the <literal>host</literal> information. If only
2319 <literal>hostaddr</literal> was specified, then that is returned.
2320 If multiple hosts were specified in the connection parameters,
2321 <xref linkend="libpq-PQhost"/> returns the host actually connected to.
2322 </para>
2324 <para>
2325 <xref linkend="libpq-PQhost"/> returns <symbol>NULL</symbol> if the
2326 <parameter>conn</parameter> argument is <symbol>NULL</symbol>.
2327 Otherwise, if there is an error producing the host information (perhaps
2328 if the connection has not been fully established or there was an
2329 error), it returns an empty string.
2330 </para>
2332 <para>
2333 If multiple hosts were specified in the connection parameters, it is
2334 not possible to rely on the result of <xref linkend="libpq-PQhost"/> until
2335 the connection is established. The status of the connection can be
2336 checked using the function <xref linkend="libpq-PQstatus"/>.
2337 </para>
2338 </listitem>
2339 </varlistentry>
2342 <varlistentry id="libpq-PQhostaddr">
2343 <term><function>PQhostaddr</function><indexterm><primary>PQhostaddr</primary></indexterm></term>
2345 <listitem>
2346 <para>
2347 Returns the server IP address of the active connection.
2348 This can be the address that a host name resolved to,
2349 or an IP address provided through the <literal>hostaddr</literal>
2350 parameter.
2351 <synopsis>
2352 char *PQhostaddr(const PGconn *conn);
2353 </synopsis>
2354 </para>
2356 <para>
2357 <xref linkend="libpq-PQhostaddr"/> returns <symbol>NULL</symbol> if the
2358 <parameter>conn</parameter> argument is <symbol>NULL</symbol>.
2359 Otherwise, if there is an error producing the host information
2360 (perhaps if the connection has not been fully established or
2361 there was an error), it returns an empty string.
2362 </para>
2363 </listitem>
2364 </varlistentry>
2366 <varlistentry id="libpq-PQport">
2367 <term><function>PQport</function><indexterm><primary>PQport</primary></indexterm></term>
2369 <listitem>
2370 <para>
2371 Returns the port of the active connection.
2373 <synopsis>
2374 char *PQport(const PGconn *conn);
2375 </synopsis>
2376 </para>
2378 <para>
2379 If multiple ports were specified in the connection parameters,
2380 <xref linkend="libpq-PQport"/> returns the port actually connected to.
2381 </para>
2383 <para>
2384 <xref linkend="libpq-PQport"/> returns <symbol>NULL</symbol> if the
2385 <parameter>conn</parameter> argument is <symbol>NULL</symbol>.
2386 Otherwise, if there is an error producing the port information (perhaps
2387 if the connection has not been fully established or there was an
2388 error), it returns an empty string.
2389 </para>
2391 <para>
2392 If multiple ports were specified in the connection parameters, it is
2393 not possible to rely on the result of <xref linkend="libpq-PQport"/> until
2394 the connection is established. The status of the connection can be
2395 checked using the function <xref linkend="libpq-PQstatus"/>.
2396 </para>
2397 </listitem>
2398 </varlistentry>
2400 <varlistentry id="libpq-PQtty">
2401 <term><function>PQtty</function><indexterm><primary>PQtty</primary></indexterm></term>
2403 <listitem>
2404 <para>
2405 This function no longer does anything, but it remains for backwards
2406 compatibility. The function always return an empty string, or
2407 <symbol>NULL</symbol> if the <parameter>conn</parameter> argument is
2408 <symbol>NULL</symbol>.
2410 <synopsis>
2411 char *PQtty(const PGconn *conn);
2412 </synopsis>
2413 </para>
2414 </listitem>
2415 </varlistentry>
2417 <varlistentry id="libpq-PQoptions">
2418 <term><function>PQoptions</function><indexterm><primary>PQoptions</primary></indexterm></term>
2420 <listitem>
2421 <para>
2422 Returns the command-line options passed in the connection request.
2423 <synopsis>
2424 char *PQoptions(const PGconn *conn);
2425 </synopsis>
2426 </para>
2427 </listitem>
2428 </varlistentry>
2429 </variablelist>
2430 </para>
2432 <para>
2433 The following functions return status data that can change as operations
2434 are executed on the <structname>PGconn</structname> object.
2436 <variablelist>
2437 <varlistentry id="libpq-PQstatus">
2438 <term><function>PQstatus</function><indexterm><primary>PQstatus</primary></indexterm></term>
2440 <listitem>
2441 <para>
2442 Returns the status of the connection.
2443 <synopsis>
2444 ConnStatusType PQstatus(const PGconn *conn);
2445 </synopsis>
2446 </para>
2448 <para>
2449 The status can be one of a number of values. However, only two of
2450 these are seen outside of an asynchronous connection procedure:
2451 <literal>CONNECTION_OK</literal> and
2452 <literal>CONNECTION_BAD</literal>. A good connection to the database
2453 has the status <literal>CONNECTION_OK</literal>. A failed
2454 connection attempt is signaled by status
2455 <literal>CONNECTION_BAD</literal>. Ordinarily, an OK status will
2456 remain so until <xref linkend="libpq-PQfinish"/>, but a communications
2457 failure might result in the status changing to
2458 <literal>CONNECTION_BAD</literal> prematurely. In that case the
2459 application could try to recover by calling
2460 <xref linkend="libpq-PQreset"/>.
2461 </para>
2463 <para>
2464 See the entry for <xref linkend="libpq-PQconnectStartParams"/>, <function>PQconnectStart</function>
2465 and <function>PQconnectPoll</function> with regards to other status codes that
2466 might be returned.
2467 </para>
2468 </listitem>
2469 </varlistentry>
2471 <varlistentry id="libpq-PQtransactionStatus">
2472 <term><function>PQtransactionStatus</function><indexterm><primary>PQtransactionStatus</primary></indexterm></term>
2474 <listitem>
2475 <para>
2476 Returns the current in-transaction status of the server.
2478 <synopsis>
2479 PGTransactionStatusType PQtransactionStatus(const PGconn *conn);
2480 </synopsis>
2482 The status can be <literal>PQTRANS_IDLE</literal> (currently idle),
2483 <literal>PQTRANS_ACTIVE</literal> (a command is in progress),
2484 <literal>PQTRANS_INTRANS</literal> (idle, in a valid transaction block),
2485 or <literal>PQTRANS_INERROR</literal> (idle, in a failed transaction block).
2486 <literal>PQTRANS_UNKNOWN</literal> is reported if the connection is bad.
2487 <literal>PQTRANS_ACTIVE</literal> is reported only when a query
2488 has been sent to the server and not yet completed.
2489 </para>
2490 </listitem>
2491 </varlistentry>
2493 <varlistentry id="libpq-PQparameterStatus">
2494 <term><function>PQparameterStatus</function><indexterm><primary>PQparameterStatus</primary></indexterm></term>
2496 <listitem>
2497 <para>
2498 Looks up a current parameter setting of the server.
2500 <synopsis>
2501 const char *PQparameterStatus(const PGconn *conn, const char *paramName);
2502 </synopsis>
2504 Certain parameter values are reported by the server automatically at
2505 connection startup or whenever their values change.
2506 <xref linkend="libpq-PQparameterStatus"/> can be used to interrogate these settings.
2507 It returns the current value of a parameter if known, or <symbol>NULL</symbol>
2508 if the parameter is not known.
2509 </para>
2511 <para>
2512 Parameters reported as of the current release include
2513 <varname>server_version</varname>,
2514 <varname>server_encoding</varname>,
2515 <varname>client_encoding</varname>,
2516 <varname>application_name</varname>,
2517 <varname>default_transaction_read_only</varname>,
2518 <varname>in_hot_standby</varname>,
2519 <varname>is_superuser</varname>,
2520 <varname>session_authorization</varname>,
2521 <varname>DateStyle</varname>,
2522 <varname>IntervalStyle</varname>,
2523 <varname>TimeZone</varname>,
2524 <varname>integer_datetimes</varname>, and
2525 <varname>standard_conforming_strings</varname>.
2526 (<varname>server_encoding</varname>, <varname>TimeZone</varname>, and
2527 <varname>integer_datetimes</varname> were not reported by releases before 8.0;
2528 <varname>standard_conforming_strings</varname> was not reported by releases
2529 before 8.1;
2530 <varname>IntervalStyle</varname> was not reported by releases before 8.4;
2531 <varname>application_name</varname> was not reported by releases before
2532 9.0;
2533 <varname>default_transaction_read_only</varname> and
2534 <varname>in_hot_standby</varname> were not reported by releases before
2535 14.)
2536 Note that
2537 <varname>server_version</varname>,
2538 <varname>server_encoding</varname> and
2539 <varname>integer_datetimes</varname>
2540 cannot change after startup.
2541 </para>
2543 <para>
2544 If no value for <varname>standard_conforming_strings</varname> is reported,
2545 applications can assume it is <literal>off</literal>, that is, backslashes
2546 are treated as escapes in string literals. Also, the presence of
2547 this parameter can be taken as an indication that the escape string
2548 syntax (<literal>E'...'</literal>) is accepted.
2549 </para>
2551 <para>
2552 Although the returned pointer is declared <literal>const</literal>, it in fact
2553 points to mutable storage associated with the <literal>PGconn</literal> structure.
2554 It is unwise to assume the pointer will remain valid across queries.
2555 </para>
2556 </listitem>
2557 </varlistentry>
2559 <varlistentry id="libpq-PQprotocolVersion">
2560 <term><function>PQprotocolVersion</function><indexterm><primary>PQprotocolVersion</primary></indexterm></term>
2562 <listitem>
2563 <para>
2564 Interrogates the frontend/backend protocol being used.
2565 <synopsis>
2566 int PQprotocolVersion(const PGconn *conn);
2567 </synopsis>
2568 Applications might wish to use this function to determine whether certain
2569 features are supported. Currently, the possible values are 3
2570 (3.0 protocol), or zero (connection bad). The protocol version will
2571 not change after connection startup is complete, but it could
2572 theoretically change during a connection reset. The 3.0 protocol is
2573 supported by <productname>PostgreSQL</productname> server versions 7.4
2574 and above.
2575 </para>
2576 </listitem>
2577 </varlistentry>
2579 <varlistentry id="libpq-PQserverVersion">
2580 <term><function>PQserverVersion</function><indexterm><primary>PQserverVersion</primary></indexterm></term>
2582 <listitem>
2583 <para>
2584 Returns an integer representing the server version.
2585 <synopsis>
2586 int PQserverVersion(const PGconn *conn);
2587 </synopsis>
2588 </para>
2590 <para>
2591 Applications might use this function to determine the version of the
2592 database server they are connected to. The result is formed by
2593 multiplying the server's major version number by 10000 and adding
2594 the minor version number. For example, version 10.1 will be
2595 returned as 100001, and version 11.0 will be returned as 110000.
2596 Zero is returned if the connection is bad.
2597 </para>
2599 <para>
2600 Prior to major version 10, <productname>PostgreSQL</productname> used
2601 three-part version numbers in which the first two parts together
2602 represented the major version. For those
2603 versions, <xref linkend="libpq-PQserverVersion"/> uses two digits for each
2604 part; for example version 9.1.5 will be returned as 90105, and
2605 version 9.2.0 will be returned as 90200.
2606 </para>
2608 <para>
2609 Therefore, for purposes of determining feature compatibility,
2610 applications should divide the result of <xref linkend="libpq-PQserverVersion"/>
2611 by 100 not 10000 to determine a logical major version number.
2612 In all release series, only the last two digits differ between
2613 minor releases (bug-fix releases).
2614 </para>
2615 </listitem>
2616 </varlistentry>
2618 <varlistentry id="libpq-PQerrorMessage">
2619 <term><function>PQerrorMessage</function><indexterm><primary>PQerrorMessage</primary></indexterm></term>
2621 <listitem>
2622 <para>
2623 <indexterm><primary>error message</primary></indexterm> Returns the error message
2624 most recently generated by an operation on the connection.
2626 <synopsis>
2627 char *PQerrorMessage(const PGconn *conn);
2628 </synopsis>
2630 </para>
2632 <para>
2633 Nearly all <application>libpq</application> functions will set a message for
2634 <xref linkend="libpq-PQerrorMessage"/> if they fail. Note that by
2635 <application>libpq</application> convention, a nonempty
2636 <xref linkend="libpq-PQerrorMessage"/> result can consist of multiple lines,
2637 and will include a trailing newline. The caller should not free
2638 the result directly. It will be freed when the associated
2639 <structname>PGconn</structname> handle is passed to
2640 <xref linkend="libpq-PQfinish"/>. The result string should not be
2641 expected to remain the same across operations on the
2642 <literal>PGconn</literal> structure.
2643 </para>
2644 </listitem>
2645 </varlistentry>
2647 <varlistentry id="libpq-PQsocket">
2648 <term><function>PQsocket</function><indexterm><primary>PQsocket</primary></indexterm></term>
2649 <listitem>
2650 <para>
2651 Obtains the file descriptor number of the connection socket to
2652 the server. A valid descriptor will be greater than or equal
2653 to 0; a result of -1 indicates that no server connection is
2654 currently open. (This will not change during normal operation,
2655 but could change during connection setup or reset.)
2657 <synopsis>
2658 int PQsocket(const PGconn *conn);
2659 </synopsis>
2661 </para>
2662 </listitem>
2663 </varlistentry>
2665 <varlistentry id="libpq-PQbackendPID">
2666 <term><function>PQbackendPID</function><indexterm><primary>PQbackendPID</primary></indexterm></term>
2667 <listitem>
2668 <para>
2669 Returns the process <acronym>ID</acronym> (PID)<indexterm>
2670 <primary>PID</primary>
2671 <secondary>determining PID of server process</secondary>
2672 <tertiary>in libpq</tertiary>
2673 </indexterm>
2674 of the backend process handling this connection.
2676 <synopsis>
2677 int PQbackendPID(const PGconn *conn);
2678 </synopsis>
2679 </para>
2681 <para>
2682 The backend <acronym>PID</acronym> is useful for debugging
2683 purposes and for comparison to <command>NOTIFY</command>
2684 messages (which include the <acronym>PID</acronym> of the
2685 notifying backend process). Note that the
2686 <acronym>PID</acronym> belongs to a process executing on the
2687 database server host, not the local host!
2688 </para>
2689 </listitem>
2690 </varlistentry>
2692 <varlistentry id="libpq-PQconnectionNeedsPassword">
2693 <term><function>PQconnectionNeedsPassword</function><indexterm><primary>PQconnectionNeedsPassword</primary></indexterm></term>
2694 <listitem>
2695 <para>
2696 Returns true (1) if the connection authentication method
2697 required a password, but none was available.
2698 Returns false (0) if not.
2700 <synopsis>
2701 int PQconnectionNeedsPassword(const PGconn *conn);
2702 </synopsis>
2703 </para>
2705 <para>
2706 This function can be applied after a failed connection attempt
2707 to decide whether to prompt the user for a password.
2708 </para>
2709 </listitem>
2710 </varlistentry>
2712 <varlistentry id="libpq-PQconnectionUsedPassword">
2713 <term><function>PQconnectionUsedPassword</function><indexterm><primary>PQconnectionUsedPassword</primary></indexterm></term>
2714 <listitem>
2715 <para>
2716 Returns true (1) if the connection authentication method
2717 used a password. Returns false (0) if not.
2719 <synopsis>
2720 int PQconnectionUsedPassword(const PGconn *conn);
2721 </synopsis>
2722 </para>
2724 <para>
2725 This function can be applied after either a failed or successful
2726 connection attempt to detect whether the server demanded a password.
2727 </para>
2728 </listitem>
2729 </varlistentry>
2731 <varlistentry id="libpq-PQconnectionUsedGSSAPI">
2732 <term><function>PQconnectionUsedGSSAPI</function><indexterm><primary>PQconnectionUsedGSSAPI</primary></indexterm></term>
2733 <listitem>
2734 <para>
2735 Returns true (1) if the connection authentication method
2736 used GSSAPI. Returns false (0) if not.
2738 <synopsis>
2739 int PQconnectionUsedGSSAPI(const PGconn *conn);
2740 </synopsis>
2741 </para>
2743 <para>
2744 This function can be applied to detect whether the connection was
2745 authenticated with GSSAPI.
2746 </para>
2747 </listitem>
2748 </varlistentry>
2749 </variablelist>
2750 </para>
2752 <para>
2753 The following functions return information related to SSL. This information
2754 usually doesn't change after a connection is established.
2756 <variablelist>
2757 <varlistentry id="libpq-PQsslInUse">
2758 <term><function>PQsslInUse</function><indexterm><primary>PQsslInUse</primary></indexterm></term>
2759 <listitem>
2760 <para>
2761 Returns true (1) if the connection uses SSL, false (0) if not.
2763 <synopsis>
2764 int PQsslInUse(const PGconn *conn);
2765 </synopsis>
2766 </para>
2768 </listitem>
2769 </varlistentry>
2771 <varlistentry id="libpq-PQsslAttribute">
2772 <term><function>PQsslAttribute</function><indexterm><primary>PQsslAttribute</primary></indexterm></term>
2773 <listitem>
2774 <para>
2775 Returns SSL-related information about the connection.
2777 <synopsis>
2778 const char *PQsslAttribute(const PGconn *conn, const char *attribute_name);
2779 </synopsis>
2780 </para>
2782 <para>
2783 The list of available attributes varies depending on the SSL library
2784 being used and the type of connection. Returns NULL if the connection
2785 does not use SSL or the specified attribute name is not defined for the
2786 library in use.
2787 </para>
2789 <para>
2790 The following attributes are commonly available:
2791 <variablelist>
2792 <varlistentry>
2793 <term><literal>library</literal></term>
2794 <listitem>
2795 <para>
2796 Name of the SSL implementation in use. (Currently, only
2797 <literal>"OpenSSL"</literal> is implemented)
2798 </para>
2799 </listitem>
2800 </varlistentry>
2801 <varlistentry>
2802 <term><literal>protocol</literal></term>
2803 <listitem>
2804 <para>
2805 SSL/TLS version in use. Common values
2806 are <literal>"TLSv1"</literal>, <literal>"TLSv1.1"</literal>
2807 and <literal>"TLSv1.2"</literal>, but an implementation may
2808 return other strings if some other protocol is used.
2809 </para>
2810 </listitem>
2811 </varlistentry>
2812 <varlistentry>
2813 <term><literal>key_bits</literal></term>
2814 <listitem>
2815 <para>
2816 Number of key bits used by the encryption algorithm.
2817 </para>
2818 </listitem>
2819 </varlistentry>
2820 <varlistentry>
2821 <term><literal>cipher</literal></term>
2822 <listitem>
2823 <para>
2824 A short name of the ciphersuite used, e.g.,
2825 <literal>"DHE-RSA-DES-CBC3-SHA"</literal>. The names are specific
2826 to each SSL implementation.
2827 </para>
2828 </listitem>
2829 </varlistentry>
2830 <varlistentry>
2831 <term><literal>compression</literal></term>
2832 <listitem>
2833 <para>
2834 Returns "on" if SSL compression is in use, else it returns "off".
2835 </para>
2836 </listitem>
2837 </varlistentry>
2838 </variablelist>
2839 </para>
2841 <para>
2842 As a special case, the <literal>library</literal> attribute may be
2843 queried without a connection by passing NULL as
2844 the <literal>conn</literal> argument. The result will be the default
2845 SSL library name, or NULL if <application>libpq</application> was
2846 compiled without any SSL support. (Prior
2847 to <productname>PostgreSQL</productname> version 15, passing NULL as
2848 the <literal>conn</literal> argument always resulted in NULL.
2849 Client programs needing to differentiate between the newer and older
2850 implementations of this case may check the
2851 <literal>LIBPQ_HAS_SSL_LIBRARY_DETECTION</literal> feature macro.)
2852 </para>
2853 </listitem>
2854 </varlistentry>
2856 <varlistentry id="libpq-PQsslAttributeNames">
2857 <term><function>PQsslAttributeNames</function><indexterm><primary>PQsslAttributeNames</primary></indexterm></term>
2858 <listitem>
2859 <para>
2860 Returns an array of SSL attribute names that can be used
2861 in <function>PQsslAttribute()</function>.
2862 The array is terminated by a NULL pointer.
2863 <synopsis>
2864 const char * const * PQsslAttributeNames(const PGconn *conn);
2865 </synopsis>
2866 </para>
2868 <para>
2869 If <literal>conn</literal> is NULL, the attributes available for the
2870 default SSL library are returned, or an empty list
2871 if <application>libpq</application> was compiled without any SSL
2872 support. If <literal>conn</literal> is not NULL, the attributes
2873 available for the SSL library in use for the connection are returned,
2874 or an empty list if the connection is not encrypted.
2875 </para>
2876 </listitem>
2877 </varlistentry>
2879 <varlistentry id="libpq-PQsslStruct">
2880 <term><function>PQsslStruct</function><indexterm><primary>PQsslStruct</primary></indexterm></term>
2881 <listitem>
2882 <para>
2883 Returns a pointer to an SSL-implementation-specific object describing
2884 the connection. Returns NULL if the connection is not encrypted
2885 or the requested type of object is not available from the connection's
2886 SSL implementation.
2887 <synopsis>
2888 void *PQsslStruct(const PGconn *conn, const char *struct_name);
2889 </synopsis>
2890 </para>
2891 <para>
2892 The struct(s) available depend on the SSL implementation in use.
2893 For <productname>OpenSSL</productname>, there is one struct,
2894 available under the name <literal>OpenSSL</literal>,
2895 and it returns a pointer to
2896 <productname>OpenSSL</productname>'s <literal>SSL</literal> struct.
2897 To use this function, code along the following lines could be used:
2898 <programlisting><![CDATA[
2899 #include <libpq-fe.h>
2900 #include <openssl/ssl.h>
2904 SSL *ssl;
2906 dbconn = PQconnectdb(...);
2909 ssl = PQsslStruct(dbconn, "OpenSSL");
2910 if (ssl)
2912 /* use OpenSSL functions to access ssl */
2914 ]]></programlisting>
2915 </para>
2916 <para>
2917 This structure can be used to verify encryption levels, check server
2918 certificates, and more. Refer to the <productname>OpenSSL</productname>
2919 documentation for information about this structure.
2920 </para>
2921 </listitem>
2922 </varlistentry>
2924 <varlistentry id="libpq-PQgetssl">
2925 <term><function>PQgetssl</function><indexterm><primary>PQgetssl</primary></indexterm></term>
2926 <listitem>
2927 <para>
2928 <indexterm><primary>SSL</primary><secondary sortas="libpq">in libpq</secondary></indexterm>
2929 Returns the SSL structure used in the connection, or NULL
2930 if SSL is not in use.
2932 <synopsis>
2933 void *PQgetssl(const PGconn *conn);
2934 </synopsis>
2935 </para>
2937 <para>
2938 This function is equivalent to <literal>PQsslStruct(conn, "OpenSSL")</literal>. It should
2939 not be used in new applications, because the returned struct is
2940 specific to <productname>OpenSSL</productname> and will not be
2941 available if another <acronym>SSL</acronym> implementation is used.
2942 To check if a connection uses SSL, call
2943 <xref linkend="libpq-PQsslInUse"/> instead, and for more details about the
2944 connection, use <xref linkend="libpq-PQsslAttribute"/>.
2945 </para>
2946 </listitem>
2947 </varlistentry>
2949 </variablelist>
2950 </para>
2952 </sect1>
2954 <sect1 id="libpq-exec">
2955 <title>Command Execution Functions</title>
2957 <para>
2958 Once a connection to a database server has been successfully
2959 established, the functions described here are used to perform
2960 SQL queries and commands.
2961 </para>
2963 <sect2 id="libpq-exec-main">
2964 <title>Main Functions</title>
2966 <para>
2967 <variablelist>
2968 <varlistentry id="libpq-PQexec">
2969 <term><function>PQexec</function><indexterm><primary>PQexec</primary></indexterm></term>
2971 <listitem>
2972 <para>
2973 Submits a command to the server and waits for the result.
2975 <synopsis>
2976 PGresult *PQexec(PGconn *conn, const char *command);
2977 </synopsis>
2978 </para>
2980 <para>
2981 Returns a <structname>PGresult</structname> pointer or possibly a null
2982 pointer. A non-null pointer will generally be returned except in
2983 out-of-memory conditions or serious errors such as inability to send
2984 the command to the server. The <xref linkend="libpq-PQresultStatus"/> function
2985 should be called to check the return value for any errors (including
2986 the value of a null pointer, in which case it will return
2987 <symbol>PGRES_FATAL_ERROR</symbol>). Use
2988 <xref linkend="libpq-PQerrorMessage"/> to get more information about such
2989 errors.
2990 </para>
2991 </listitem>
2992 </varlistentry>
2993 </variablelist>
2995 The command string can include multiple SQL commands
2996 (separated by semicolons). Multiple queries sent in a single
2997 <xref linkend="libpq-PQexec"/> call are processed in a single transaction, unless
2998 there are explicit <command>BEGIN</command>/<command>COMMIT</command>
2999 commands included in the query string to divide it into multiple
3000 transactions. (See <xref linkend="protocol-flow-multi-statement"/>
3001 for more details about how the server handles multi-query strings.)
3002 Note however that the returned
3003 <structname>PGresult</structname> structure describes only the result
3004 of the last command executed from the string. Should one of the
3005 commands fail, processing of the string stops with it and the returned
3006 <structname>PGresult</structname> describes the error condition.
3007 </para>
3009 <para>
3010 <variablelist>
3011 <varlistentry id="libpq-PQexecParams">
3012 <term><function>PQexecParams</function><indexterm><primary>PQexecParams</primary></indexterm></term>
3014 <listitem>
3015 <para>
3016 Submits a command to the server and waits for the result,
3017 with the ability to pass parameters separately from the SQL
3018 command text.
3020 <synopsis>
3021 PGresult *PQexecParams(PGconn *conn,
3022 const char *command,
3023 int nParams,
3024 const Oid *paramTypes,
3025 const char * const *paramValues,
3026 const int *paramLengths,
3027 const int *paramFormats,
3028 int resultFormat);
3029 </synopsis>
3030 </para>
3032 <para>
3033 <xref linkend="libpq-PQexecParams"/> is like <xref linkend="libpq-PQexec"/>, but offers additional
3034 functionality: parameter values can be specified separately from the command
3035 string proper, and query results can be requested in either text or binary
3036 format.
3037 </para>
3039 <para>
3040 The function arguments are:
3042 <variablelist>
3043 <varlistentry>
3044 <term><parameter>conn</parameter></term>
3046 <listitem>
3047 <para>
3048 The connection object to send the command through.
3049 </para>
3050 </listitem>
3051 </varlistentry>
3053 <varlistentry>
3054 <term><parameter>command</parameter></term>
3055 <listitem>
3056 <para>
3057 The SQL command string to be executed. If parameters are used,
3058 they are referred to in the command string as <literal>$1</literal>,
3059 <literal>$2</literal>, etc.
3060 </para>
3061 </listitem>
3062 </varlistentry>
3064 <varlistentry>
3065 <term><parameter>nParams</parameter></term>
3066 <listitem>
3067 <para>
3068 The number of parameters supplied; it is the length of the arrays
3069 <parameter>paramTypes[]</parameter>, <parameter>paramValues[]</parameter>,
3070 <parameter>paramLengths[]</parameter>, and <parameter>paramFormats[]</parameter>. (The
3071 array pointers can be <symbol>NULL</symbol> when <parameter>nParams</parameter>
3072 is zero.)
3073 </para>
3074 </listitem>
3075 </varlistentry>
3077 <varlistentry>
3078 <term><parameter>paramTypes[]</parameter></term>
3079 <listitem>
3080 <para>
3081 Specifies, by OID, the data types to be assigned to the
3082 parameter symbols. If <parameter>paramTypes</parameter> is
3083 <symbol>NULL</symbol>, or any particular element in the array
3084 is zero, the server infers a data type for the parameter symbol
3085 in the same way it would do for an untyped literal string.
3086 </para>
3087 </listitem>
3088 </varlistentry>
3090 <varlistentry>
3091 <term><parameter>paramValues[]</parameter></term>
3092 <listitem>
3093 <para>
3094 Specifies the actual values of the parameters. A null pointer
3095 in this array means the corresponding parameter is null;
3096 otherwise the pointer points to a zero-terminated text string
3097 (for text format) or binary data in the format expected by the
3098 server (for binary format).
3099 </para>
3100 </listitem>
3101 </varlistentry>
3103 <varlistentry>
3104 <term><parameter>paramLengths[]</parameter></term>
3105 <listitem>
3106 <para>
3107 Specifies the actual data lengths of binary-format parameters.
3108 It is ignored for null parameters and text-format parameters.
3109 The array pointer can be null when there are no binary parameters.
3110 </para>
3111 </listitem>
3112 </varlistentry>
3114 <varlistentry>
3115 <term><parameter>paramFormats[]</parameter></term>
3116 <listitem>
3117 <para>
3118 Specifies whether parameters are text (put a zero in the
3119 array entry for the corresponding parameter) or binary (put
3120 a one in the array entry for the corresponding parameter).
3121 If the array pointer is null then all parameters are presumed
3122 to be text strings.
3123 </para>
3124 <para>
3125 Values passed in binary format require knowledge of
3126 the internal representation expected by the backend.
3127 For example, integers must be passed in network byte
3128 order. Passing <type>numeric</type> values requires
3129 knowledge of the server storage format, as implemented
3131 <filename>src/backend/utils/adt/numeric.c::numeric_send()</filename> and
3132 <filename>src/backend/utils/adt/numeric.c::numeric_recv()</filename>.
3133 </para>
3134 </listitem>
3135 </varlistentry>
3137 <varlistentry>
3138 <term><parameter>resultFormat</parameter></term>
3139 <listitem>
3140 <para>
3141 Specify zero to obtain results in text format, or one to obtain
3142 results in binary format. (There is not currently a provision
3143 to obtain different result columns in different formats,
3144 although that is possible in the underlying protocol.)
3145 </para>
3146 </listitem>
3147 </varlistentry>
3148 </variablelist>
3149 </para>
3150 </listitem>
3151 </varlistentry>
3152 </variablelist>
3153 </para>
3155 <para>
3156 The primary advantage of <xref linkend="libpq-PQexecParams"/> over
3157 <xref linkend="libpq-PQexec"/> is that parameter values can be separated from the
3158 command string, thus avoiding the need for tedious and error-prone
3159 quoting and escaping.
3160 </para>
3162 <para>
3163 Unlike <xref linkend="libpq-PQexec"/>, <xref linkend="libpq-PQexecParams"/> allows at most
3164 one SQL command in the given string. (There can be semicolons in it,
3165 but not more than one nonempty command.) This is a limitation of the
3166 underlying protocol, but has some usefulness as an extra defense against
3167 SQL-injection attacks.
3168 </para>
3170 <tip>
3171 <para>
3172 Specifying parameter types via OIDs is tedious, particularly if you prefer
3173 not to hard-wire particular OID values into your program. However, you can
3174 avoid doing so even in cases where the server by itself cannot determine the
3175 type of the parameter, or chooses a different type than you want. In the
3176 SQL command text, attach an explicit cast to the parameter symbol to show what
3177 data type you will send. For example:
3178 <programlisting>
3179 SELECT * FROM mytable WHERE x = $1::bigint;
3180 </programlisting>
3181 This forces parameter <literal>$1</literal> to be treated as <type>bigint</type>, whereas
3182 by default it would be assigned the same type as <literal>x</literal>. Forcing the
3183 parameter type decision, either this way or by specifying a numeric type OID,
3184 is strongly recommended when sending parameter values in binary format, because
3185 binary format has less redundancy than text format and so there is less chance
3186 that the server will detect a type mismatch mistake for you.
3187 </para>
3188 </tip>
3190 <para>
3191 <variablelist>
3192 <varlistentry id="libpq-PQprepare">
3193 <term><function>PQprepare</function><indexterm><primary>PQprepare</primary></indexterm></term>
3195 <listitem>
3196 <para>
3197 Submits a request to create a prepared statement with the
3198 given parameters, and waits for completion.
3199 <synopsis>
3200 PGresult *PQprepare(PGconn *conn,
3201 const char *stmtName,
3202 const char *query,
3203 int nParams,
3204 const Oid *paramTypes);
3205 </synopsis>
3206 </para>
3208 <para>
3209 <xref linkend="libpq-PQprepare"/> creates a prepared statement for later
3210 execution with <xref linkend="libpq-PQexecPrepared"/>. This feature allows
3211 commands to be executed repeatedly without being parsed and
3212 planned each time; see <xref linkend="sql-prepare"/> for details.
3213 </para>
3215 <para>
3216 The function creates a prepared statement named
3217 <parameter>stmtName</parameter> from the <parameter>query</parameter> string, which
3218 must contain a single SQL command. <parameter>stmtName</parameter> can be
3219 <literal>""</literal> to create an unnamed statement, in which case any
3220 pre-existing unnamed statement is automatically replaced; otherwise
3221 it is an error if the statement name is already defined in the
3222 current session. If any parameters are used, they are referred
3223 to in the query as <literal>$1</literal>, <literal>$2</literal>, etc.
3224 <parameter>nParams</parameter> is the number of parameters for which types
3225 are pre-specified in the array <parameter>paramTypes[]</parameter>. (The
3226 array pointer can be <symbol>NULL</symbol> when
3227 <parameter>nParams</parameter> is zero.) <parameter>paramTypes[]</parameter>
3228 specifies, by OID, the data types to be assigned to the parameter
3229 symbols. If <parameter>paramTypes</parameter> is <symbol>NULL</symbol>,
3230 or any particular element in the array is zero, the server assigns
3231 a data type to the parameter symbol in the same way it would do
3232 for an untyped literal string. Also, the query can use parameter
3233 symbols with numbers higher than <parameter>nParams</parameter>; data types
3234 will be inferred for these symbols as well. (See
3235 <xref linkend="libpq-PQdescribePrepared"/> for a means to find out
3236 what data types were inferred.)
3237 </para>
3239 <para>
3240 As with <xref linkend="libpq-PQexec"/>, the result is normally a
3241 <structname>PGresult</structname> object whose contents indicate
3242 server-side success or failure. A null result indicates
3243 out-of-memory or inability to send the command at all. Use
3244 <xref linkend="libpq-PQerrorMessage"/> to get more information about
3245 such errors.
3246 </para>
3247 </listitem>
3248 </varlistentry>
3249 </variablelist>
3251 Prepared statements for use with <xref linkend="libpq-PQexecPrepared"/> can also
3252 be created by executing SQL <xref linkend="sql-prepare"/>
3253 statements.
3254 </para>
3256 <para>
3257 <variablelist>
3258 <varlistentry id="libpq-PQexecPrepared">
3259 <term><function>PQexecPrepared</function><indexterm><primary>PQexecPrepared</primary></indexterm></term>
3261 <listitem>
3262 <para>
3263 Sends a request to execute a prepared statement with given
3264 parameters, and waits for the result.
3265 <synopsis>
3266 PGresult *PQexecPrepared(PGconn *conn,
3267 const char *stmtName,
3268 int nParams,
3269 const char * const *paramValues,
3270 const int *paramLengths,
3271 const int *paramFormats,
3272 int resultFormat);
3273 </synopsis>
3274 </para>
3276 <para>
3277 <xref linkend="libpq-PQexecPrepared"/> is like <xref linkend="libpq-PQexecParams"/>,
3278 but the command to be executed is specified by naming a
3279 previously-prepared statement, instead of giving a query string.
3280 This feature allows commands that will be used repeatedly to be
3281 parsed and planned just once, rather than each time they are
3282 executed. The statement must have been prepared previously in
3283 the current session.
3284 </para>
3286 <para>
3287 The parameters are identical to <xref linkend="libpq-PQexecParams"/>, except that the
3288 name of a prepared statement is given instead of a query string, and the
3289 <parameter>paramTypes[]</parameter> parameter is not present (it is not needed since
3290 the prepared statement's parameter types were determined when it was created).
3291 </para>
3292 </listitem>
3293 </varlistentry>
3295 <varlistentry id="libpq-PQdescribePrepared">
3296 <term><function>PQdescribePrepared</function><indexterm><primary>PQdescribePrepared</primary></indexterm></term>
3298 <listitem>
3299 <para>
3300 Submits a request to obtain information about the specified
3301 prepared statement, and waits for completion.
3302 <synopsis>
3303 PGresult *PQdescribePrepared(PGconn *conn, const char *stmtName);
3304 </synopsis>
3305 </para>
3307 <para>
3308 <xref linkend="libpq-PQdescribePrepared"/> allows an application to obtain
3309 information about a previously prepared statement.
3310 </para>
3312 <para>
3313 <parameter>stmtName</parameter> can be <literal>""</literal> or <symbol>NULL</symbol> to reference
3314 the unnamed statement, otherwise it must be the name of an existing
3315 prepared statement. On success, a <structname>PGresult</structname> with
3316 status <literal>PGRES_COMMAND_OK</literal> is returned. The
3317 functions <xref linkend="libpq-PQnparams"/> and
3318 <xref linkend="libpq-PQparamtype"/> can be applied to this
3319 <structname>PGresult</structname> to obtain information about the parameters
3320 of the prepared statement, and the functions
3321 <xref linkend="libpq-PQnfields"/>, <xref linkend="libpq-PQfname"/>,
3322 <xref linkend="libpq-PQftype"/>, etc. provide information about the
3323 result columns (if any) of the statement.
3324 </para>
3325 </listitem>
3326 </varlistentry>
3328 <varlistentry id="libpq-PQdescribePortal">
3329 <term><function>PQdescribePortal</function><indexterm><primary>PQdescribePortal</primary></indexterm></term>
3331 <listitem>
3332 <para>
3333 Submits a request to obtain information about the specified
3334 portal, and waits for completion.
3335 <synopsis>
3336 PGresult *PQdescribePortal(PGconn *conn, const char *portalName);
3337 </synopsis>
3338 </para>
3340 <para>
3341 <xref linkend="libpq-PQdescribePortal"/> allows an application to obtain
3342 information about a previously created portal.
3343 (<application>libpq</application> does not provide any direct access to
3344 portals, but you can use this function to inspect the properties
3345 of a cursor created with a <command>DECLARE CURSOR</command> SQL command.)
3346 </para>
3348 <para>
3349 <parameter>portalName</parameter> can be <literal>""</literal> or <symbol>NULL</symbol> to reference
3350 the unnamed portal, otherwise it must be the name of an existing
3351 portal. On success, a <structname>PGresult</structname> with status
3352 <literal>PGRES_COMMAND_OK</literal> is returned. The functions
3353 <xref linkend="libpq-PQnfields"/>, <xref linkend="libpq-PQfname"/>,
3354 <xref linkend="libpq-PQftype"/>, etc. can be applied to the
3355 <structname>PGresult</structname> to obtain information about the result
3356 columns (if any) of the portal.
3357 </para>
3358 </listitem>
3359 </varlistentry>
3361 <varlistentry id="libpq-PQclosePrepared">
3362 <term><function>PQclosePrepared</function><indexterm><primary>PQclosePrepared</primary></indexterm></term>
3364 <listitem>
3365 <para>
3366 Submits a request to close the specified prepared statement, and waits
3367 for completion.
3368 <synopsis>
3369 PGresult *PQclosePrepared(PGconn *conn, const char *stmtName);
3370 </synopsis>
3371 </para>
3373 <para>
3374 <xref linkend="libpq-PQclosePrepared"/> allows an application to close
3375 a previously prepared statement. Closing a statement releases all
3376 of its associated resources on the server and allows its name to be
3377 reused.
3378 </para>
3380 <para>
3381 <parameter>stmtName</parameter> can be <literal>""</literal> or
3382 <symbol>NULL</symbol> to reference the unnamed statement. It is fine
3383 if no statement exists with this name, in that case the operation is a
3384 no-op. On success, a <structname>PGresult</structname> with
3385 status <literal>PGRES_COMMAND_OK</literal> is returned.
3386 </para>
3387 </listitem>
3388 </varlistentry>
3390 <varlistentry id="libpq-PQclosePortal">
3391 <term><function>PQclosePortal</function><indexterm><primary>PQclosePortal</primary></indexterm></term>
3393 <listitem>
3394 <para>
3395 Submits a request to close the specified portal, and waits for
3396 completion.
3397 <synopsis>
3398 PGresult *PQclosePortal(PGconn *conn, const char *portalName);
3399 </synopsis>
3400 </para>
3402 <para>
3403 <xref linkend="libpq-PQclosePortal"/> allows an application to trigger
3404 a close of a previously created portal. Closing a portal releases all
3405 of its associated resources on the server and allows its name to be
3406 reused. (<application>libpq</application> does not provide any
3407 direct access to portals, but you can use this function to close a
3408 cursor created with a <command>DECLARE CURSOR</command> SQL command.)
3409 </para>
3411 <para>
3412 <parameter>portalName</parameter> can be <literal>""</literal> or
3413 <symbol>NULL</symbol> to reference the unnamed portal. It is fine
3414 if no portal exists with this name, in that case the operation is a
3415 no-op. On success, a <structname>PGresult</structname> with status
3416 <literal>PGRES_COMMAND_OK</literal> is returned.
3417 </para>
3418 </listitem>
3419 </varlistentry>
3420 </variablelist>
3421 </para>
3423 <para>
3424 The <structname>PGresult</structname><indexterm><primary>PGresult</primary></indexterm>
3425 structure encapsulates the result returned by the server.
3426 <application>libpq</application> application programmers should be
3427 careful to maintain the <structname>PGresult</structname> abstraction.
3428 Use the accessor functions below to get at the contents of
3429 <structname>PGresult</structname>. Avoid directly referencing the
3430 fields of the <structname>PGresult</structname> structure because they
3431 are subject to change in the future.
3433 <variablelist>
3434 <varlistentry id="libpq-PQresultStatus">
3435 <term><function>PQresultStatus</function><indexterm><primary>PQresultStatus</primary></indexterm></term>
3437 <listitem>
3438 <para>
3439 Returns the result status of the command.
3440 <synopsis>
3441 ExecStatusType PQresultStatus(const PGresult *res);
3442 </synopsis>
3443 </para>
3445 <para>
3446 <xref linkend="libpq-PQresultStatus"/> can return one of the following values:
3448 <variablelist>
3449 <varlistentry id="libpq-pgres-empty-query">
3450 <term><literal>PGRES_EMPTY_QUERY</literal></term>
3451 <listitem>
3452 <para>
3453 The string sent to the server was empty.
3454 </para>
3455 </listitem>
3456 </varlistentry>
3458 <varlistentry id="libpq-pgres-command-ok">
3459 <term><literal>PGRES_COMMAND_OK</literal></term>
3460 <listitem>
3461 <para>
3462 Successful completion of a command returning no data.
3463 </para>
3464 </listitem>
3465 </varlistentry>
3467 <varlistentry id="libpq-pgres-tuples-ok">
3468 <term><literal>PGRES_TUPLES_OK</literal></term>
3469 <listitem>
3470 <para>
3471 Successful completion of a command returning data (such as
3472 a <command>SELECT</command> or <command>SHOW</command>).
3473 </para>
3474 </listitem>
3475 </varlistentry>
3477 <varlistentry id="libpq-pgres-copy-out">
3478 <term><literal>PGRES_COPY_OUT</literal></term>
3479 <listitem>
3480 <para>
3481 Copy Out (from server) data transfer started.
3482 </para>
3483 </listitem>
3484 </varlistentry>
3486 <varlistentry id="libpq-pgres-copy-in">
3487 <term><literal>PGRES_COPY_IN</literal></term>
3488 <listitem>
3489 <para>
3490 Copy In (to server) data transfer started.
3491 </para>
3492 </listitem>
3493 </varlistentry>
3495 <varlistentry id="libpq-pgres-bad-response">
3496 <term><literal>PGRES_BAD_RESPONSE</literal></term>
3497 <listitem>
3498 <para>
3499 The server's response was not understood.
3500 </para>
3501 </listitem>
3502 </varlistentry>
3504 <varlistentry id="libpq-pgres-nonfatal-error">
3505 <term><literal>PGRES_NONFATAL_ERROR</literal></term>
3506 <listitem>
3507 <para>
3508 A nonfatal error (a notice or warning) occurred.
3509 </para>
3510 </listitem>
3511 </varlistentry>
3513 <varlistentry id="libpq-pgres-fatal-error">
3514 <term><literal>PGRES_FATAL_ERROR</literal></term>
3515 <listitem>
3516 <para>
3517 A fatal error occurred.
3518 </para>
3519 </listitem>
3520 </varlistentry>
3522 <varlistentry id="libpq-pgres-copy-both">
3523 <term><literal>PGRES_COPY_BOTH</literal></term>
3524 <listitem>
3525 <para>
3526 Copy In/Out (to and from server) data transfer started. This
3527 feature is currently used only for streaming replication,
3528 so this status should not occur in ordinary applications.
3529 </para>
3530 </listitem>
3531 </varlistentry>
3533 <varlistentry id="libpq-pgres-single-tuple">
3534 <term><literal>PGRES_SINGLE_TUPLE</literal></term>
3535 <listitem>
3536 <para>
3537 The <structname>PGresult</structname> contains a single result tuple
3538 from the current command. This status occurs only when
3539 single-row mode has been selected for the query
3540 (see <xref linkend="libpq-single-row-mode"/>).
3541 </para>
3542 </listitem>
3543 </varlistentry>
3545 <varlistentry id="libpq-pgres-pipeline-sync">
3546 <term><literal>PGRES_PIPELINE_SYNC</literal></term>
3547 <listitem>
3548 <para>
3549 The <structname>PGresult</structname> represents a
3550 synchronization point in pipeline mode, requested by
3551 <xref linkend="libpq-PQpipelineSync"/>.
3552 This status occurs only when pipeline mode has been selected.
3553 </para>
3554 </listitem>
3555 </varlistentry>
3557 <varlistentry id="libpq-pgres-pipeline-aborted">
3558 <term><literal>PGRES_PIPELINE_ABORTED</literal></term>
3559 <listitem>
3560 <para>
3561 The <structname>PGresult</structname> represents a pipeline that has
3562 received an error from the server. <function>PQgetResult</function>
3563 must be called repeatedly, and each time it will return this status code
3564 until the end of the current pipeline, at which point it will return
3565 <literal>PGRES_PIPELINE_SYNC</literal> and normal processing can
3566 resume.
3567 </para>
3568 </listitem>
3569 </varlistentry>
3571 </variablelist>
3573 If the result status is <literal>PGRES_TUPLES_OK</literal> or
3574 <literal>PGRES_SINGLE_TUPLE</literal>, then
3575 the functions described below can be used to retrieve the rows
3576 returned by the query. Note that a <command>SELECT</command>
3577 command that happens to retrieve zero rows still shows
3578 <literal>PGRES_TUPLES_OK</literal>.
3579 <literal>PGRES_COMMAND_OK</literal> is for commands that can never
3580 return rows (<command>INSERT</command> or <command>UPDATE</command>
3581 without a <literal>RETURNING</literal> clause,
3582 etc.). A response of <literal>PGRES_EMPTY_QUERY</literal> might
3583 indicate a bug in the client software.
3584 </para>
3586 <para>
3587 A result of status <symbol>PGRES_NONFATAL_ERROR</symbol> will
3588 never be returned directly by <xref linkend="libpq-PQexec"/> or other
3589 query execution functions; results of this kind are instead passed
3590 to the notice processor (see <xref
3591 linkend="libpq-notice-processing"/>).
3592 </para>
3593 </listitem>
3594 </varlistentry>
3596 <varlistentry id="libpq-PQresStatus">
3597 <term><function>PQresStatus</function><indexterm><primary>PQresStatus</primary></indexterm></term>
3599 <listitem>
3600 <para>
3601 Converts the enumerated type returned by
3602 <xref linkend="libpq-PQresultStatus"/> into a string constant describing the
3603 status code. The caller should not free the result.
3605 <synopsis>
3606 char *PQresStatus(ExecStatusType status);
3607 </synopsis>
3608 </para>
3609 </listitem>
3610 </varlistentry>
3612 <varlistentry id="libpq-PQresultErrorMessage">
3613 <term><function>PQresultErrorMessage</function><indexterm><primary>PQresultErrorMessage</primary></indexterm></term>
3615 <listitem>
3616 <para>
3617 Returns the error message associated with the command, or an empty string
3618 if there was no error.
3619 <synopsis>
3620 char *PQresultErrorMessage(const PGresult *res);
3621 </synopsis>
3622 If there was an error, the returned string will include a trailing
3623 newline. The caller should not free the result directly. It will
3624 be freed when the associated <structname>PGresult</structname> handle is
3625 passed to <xref linkend="libpq-PQclear"/>.
3626 </para>
3628 <para>
3629 Immediately following a <xref linkend="libpq-PQexec"/> or
3630 <xref linkend="libpq-PQgetResult"/> call,
3631 <xref linkend="libpq-PQerrorMessage"/> (on the connection) will return
3632 the same string as <xref linkend="libpq-PQresultErrorMessage"/> (on
3633 the result). However, a <structname>PGresult</structname> will
3634 retain its error message until destroyed, whereas the connection's
3635 error message will change when subsequent operations are done.
3636 Use <xref linkend="libpq-PQresultErrorMessage"/> when you want to
3637 know the status associated with a particular
3638 <structname>PGresult</structname>; use
3639 <xref linkend="libpq-PQerrorMessage"/> when you want to know the
3640 status from the latest operation on the connection.
3641 </para>
3642 </listitem>
3643 </varlistentry>
3645 <varlistentry id="libpq-PQresultVerboseErrorMessage">
3646 <term><function>PQresultVerboseErrorMessage</function><indexterm><primary>PQresultVerboseErrorMessage</primary></indexterm></term>
3648 <listitem>
3649 <para>
3650 Returns a reformatted version of the error message associated with
3651 a <structname>PGresult</structname> object.
3652 <synopsis>
3653 char *PQresultVerboseErrorMessage(const PGresult *res,
3654 PGVerbosity verbosity,
3655 PGContextVisibility show_context);
3656 </synopsis>
3657 In some situations a client might wish to obtain a more detailed
3658 version of a previously-reported error.
3659 <xref linkend="libpq-PQresultVerboseErrorMessage"/> addresses this need
3660 by computing the message that would have been produced
3661 by <xref linkend="libpq-PQresultErrorMessage"/> if the specified
3662 verbosity settings had been in effect for the connection when the
3663 given <structname>PGresult</structname> was generated. If
3664 the <structname>PGresult</structname> is not an error result,
3665 <quote>PGresult is not an error result</quote> is reported instead.
3666 The returned string includes a trailing newline.
3667 </para>
3669 <para>
3670 Unlike most other functions for extracting data from
3671 a <structname>PGresult</structname>, the result of this function is a freshly
3672 allocated string. The caller must free it
3673 using <function>PQfreemem()</function> when the string is no longer needed.
3674 </para>
3676 <para>
3677 A NULL return is possible if there is insufficient memory.
3678 </para>
3679 </listitem>
3680 </varlistentry>
3682 <varlistentry id="libpq-PQresultErrorField">
3683 <term><function>PQresultErrorField</function><indexterm><primary>PQresultErrorField</primary></indexterm></term>
3684 <listitem>
3685 <para>
3686 Returns an individual field of an error report.
3687 <synopsis>
3688 char *PQresultErrorField(const PGresult *res, int fieldcode);
3689 </synopsis>
3690 <parameter>fieldcode</parameter> is an error field identifier; see the symbols
3691 listed below. <symbol>NULL</symbol> is returned if the
3692 <structname>PGresult</structname> is not an error or warning result,
3693 or does not include the specified field. Field values will normally
3694 not include a trailing newline. The caller should not free the
3695 result directly. It will be freed when the
3696 associated <structname>PGresult</structname> handle is passed to
3697 <xref linkend="libpq-PQclear"/>.
3698 </para>
3700 <para>
3701 The following field codes are available:
3702 <variablelist>
3703 <varlistentry id="libpq-pg-diag-severity">
3704 <term><symbol>PG_DIAG_SEVERITY</symbol></term>
3705 <listitem>
3706 <para>
3707 The severity; the field contents are <literal>ERROR</literal>,
3708 <literal>FATAL</literal>, or <literal>PANIC</literal> (in an error message),
3709 or <literal>WARNING</literal>, <literal>NOTICE</literal>, <literal>DEBUG</literal>,
3710 <literal>INFO</literal>, or <literal>LOG</literal> (in a notice message), or
3711 a localized translation of one of these. Always present.
3712 </para>
3713 </listitem>
3714 </varlistentry>
3716 <varlistentry id="libpq-PG-diag-severity-nonlocalized">
3717 <term><symbol>PG_DIAG_SEVERITY_NONLOCALIZED</symbol></term>
3718 <listitem>
3719 <para>
3720 The severity; the field contents are <literal>ERROR</literal>,
3721 <literal>FATAL</literal>, or <literal>PANIC</literal> (in an error message),
3722 or <literal>WARNING</literal>, <literal>NOTICE</literal>, <literal>DEBUG</literal>,
3723 <literal>INFO</literal>, or <literal>LOG</literal> (in a notice message).
3724 This is identical to the <symbol>PG_DIAG_SEVERITY</symbol> field except
3725 that the contents are never localized. This is present only in
3726 reports generated by <productname>PostgreSQL</productname> versions 9.6
3727 and later.
3728 </para>
3729 </listitem>
3730 </varlistentry>
3732 <varlistentry id="libpq-pg-diag-sqlstate">
3733 <term><symbol>PG_DIAG_SQLSTATE</symbol><indexterm
3734 ><primary>error codes</primary><secondary>libpq</secondary></indexterm></term>
3735 <listitem>
3736 <para>
3737 The SQLSTATE code for the error. The SQLSTATE code identifies
3738 the type of error that has occurred; it can be used by
3739 front-end applications to perform specific operations (such
3740 as error handling) in response to a particular database error.
3741 For a list of the possible SQLSTATE codes, see <xref
3742 linkend="errcodes-appendix"/>. This field is not localizable,
3743 and is always present.
3744 </para>
3745 </listitem>
3746 </varlistentry>
3748 <varlistentry id="libpq-pg-diag-message-primary">
3749 <term><symbol>PG_DIAG_MESSAGE_PRIMARY</symbol></term>
3750 <listitem>
3751 <para>
3752 The primary human-readable error message (typically one line).
3753 Always present.
3754 </para>
3755 </listitem>
3756 </varlistentry>
3758 <varlistentry id="libpq-pg-diag-message-detail">
3759 <term><symbol>PG_DIAG_MESSAGE_DETAIL</symbol></term>
3760 <listitem>
3761 <para>
3762 Detail: an optional secondary error message carrying more
3763 detail about the problem. Might run to multiple lines.
3764 </para>
3765 </listitem>
3766 </varlistentry>
3768 <varlistentry id="libpq-pg-diag-message-hint">
3769 <term><symbol>PG_DIAG_MESSAGE_HINT</symbol></term>
3770 <listitem>
3771 <para>
3772 Hint: an optional suggestion what to do about the problem.
3773 This is intended to differ from detail in that it offers advice
3774 (potentially inappropriate) rather than hard facts. Might
3775 run to multiple lines.
3776 </para>
3777 </listitem>
3778 </varlistentry>
3780 <varlistentry id="libpq-pg-diag-statement-position">
3781 <term><symbol>PG_DIAG_STATEMENT_POSITION</symbol></term>
3782 <listitem>
3783 <para>
3784 A string containing a decimal integer indicating an error cursor
3785 position as an index into the original statement string. The
3786 first character has index 1, and positions are measured in
3787 characters not bytes.
3788 </para>
3789 </listitem>
3790 </varlistentry>
3792 <varlistentry id="libpq-pg-diag-internal-position">
3793 <term><symbol>PG_DIAG_INTERNAL_POSITION</symbol></term>
3794 <listitem>
3795 <para>
3796 This is defined the same as the
3797 <symbol>PG_DIAG_STATEMENT_POSITION</symbol> field, but it is used
3798 when the cursor position refers to an internally generated
3799 command rather than the one submitted by the client. The
3800 <symbol>PG_DIAG_INTERNAL_QUERY</symbol> field will always appear when
3801 this field appears.
3802 </para>
3803 </listitem>
3804 </varlistentry>
3806 <varlistentry id="libpq-pg-diag-internal-query">
3807 <term><symbol>PG_DIAG_INTERNAL_QUERY</symbol></term>
3808 <listitem>
3809 <para>
3810 The text of a failed internally-generated command. This could
3811 be, for example, an SQL query issued by a PL/pgSQL function.
3812 </para>
3813 </listitem>
3814 </varlistentry>
3816 <varlistentry id="libpq-pg-diag-context">
3817 <term><symbol>PG_DIAG_CONTEXT</symbol></term>
3818 <listitem>
3819 <para>
3820 An indication of the context in which the error occurred.
3821 Presently this includes a call stack traceback of active
3822 procedural language functions and internally-generated queries.
3823 The trace is one entry per line, most recent first.
3824 </para>
3825 </listitem>
3826 </varlistentry>
3828 <varlistentry id="libpq-pg-diag-schema-name">
3829 <term><symbol>PG_DIAG_SCHEMA_NAME</symbol></term>
3830 <listitem>
3831 <para>
3832 If the error was associated with a specific database object,
3833 the name of the schema containing that object, if any.
3834 </para>
3835 </listitem>
3836 </varlistentry>
3838 <varlistentry id="libpq-pg-diag-table-name">
3839 <term><symbol>PG_DIAG_TABLE_NAME</symbol></term>
3840 <listitem>
3841 <para>
3842 If the error was associated with a specific table, the name of the
3843 table. (Refer to the schema name field for the name of the
3844 table's schema.)
3845 </para>
3846 </listitem>
3847 </varlistentry>
3849 <varlistentry id="libpq-pg-diag-column-name">
3850 <term><symbol>PG_DIAG_COLUMN_NAME</symbol></term>
3851 <listitem>
3852 <para>
3853 If the error was associated with a specific table column, the name
3854 of the column. (Refer to the schema and table name fields to
3855 identify the table.)
3856 </para>
3857 </listitem>
3858 </varlistentry>
3860 <varlistentry id="libpq-pg-diag-datatype-name">
3861 <term><symbol>PG_DIAG_DATATYPE_NAME</symbol></term>
3862 <listitem>
3863 <para>
3864 If the error was associated with a specific data type, the name of
3865 the data type. (Refer to the schema name field for the name of
3866 the data type's schema.)
3867 </para>
3868 </listitem>
3869 </varlistentry>
3871 <varlistentry id="libpq-pg-diag-constraint-name">
3872 <term><symbol>PG_DIAG_CONSTRAINT_NAME</symbol></term>
3873 <listitem>
3874 <para>
3875 If the error was associated with a specific constraint, the name
3876 of the constraint. Refer to fields listed above for the
3877 associated table or domain. (For this purpose, indexes are
3878 treated as constraints, even if they weren't created with
3879 constraint syntax.)
3880 </para>
3881 </listitem>
3882 </varlistentry>
3884 <varlistentry id="libpq-pg-diag-source-file">
3885 <term><symbol>PG_DIAG_SOURCE_FILE</symbol></term>
3886 <listitem>
3887 <para>
3888 The file name of the source-code location where the error was
3889 reported.
3890 </para>
3891 </listitem>
3892 </varlistentry>
3894 <varlistentry id="libpq-pg-diag-source-line">
3895 <term><symbol>PG_DIAG_SOURCE_LINE</symbol></term>
3896 <listitem>
3897 <para>
3898 The line number of the source-code location where the error
3899 was reported.
3900 </para>
3901 </listitem>
3902 </varlistentry>
3904 <varlistentry id="libpq-pg-diag-source-function">
3905 <term><symbol>PG_DIAG_SOURCE_FUNCTION</symbol></term>
3906 <listitem>
3907 <para>
3908 The name of the source-code function reporting the error.
3909 </para>
3910 </listitem>
3911 </varlistentry>
3912 </variablelist>
3913 </para>
3915 <note>
3916 <para>
3917 The fields for schema name, table name, column name, data type name,
3918 and constraint name are supplied only for a limited number of error
3919 types; see <xref linkend="errcodes-appendix"/>. Do not assume that
3920 the presence of any of these fields guarantees the presence of
3921 another field. Core error sources observe the interrelationships
3922 noted above, but user-defined functions may use these fields in other
3923 ways. In the same vein, do not assume that these fields denote
3924 contemporary objects in the current database.
3925 </para>
3926 </note>
3928 <para>
3929 The client is responsible for formatting displayed information to meet
3930 its needs; in particular it should break long lines as needed.
3931 Newline characters appearing in the error message fields should be
3932 treated as paragraph breaks, not line breaks.
3933 </para>
3935 <para>
3936 Errors generated internally by <application>libpq</application> will
3937 have severity and primary message, but typically no other fields.
3938 </para>
3940 <para>
3941 Note that error fields are only available from
3942 <structname>PGresult</structname> objects, not
3943 <structname>PGconn</structname> objects; there is no
3944 <function>PQerrorField</function> function.
3945 </para>
3946 </listitem>
3947 </varlistentry>
3949 <varlistentry id="libpq-PQclear">
3950 <term><function>PQclear</function><indexterm><primary>PQclear</primary></indexterm></term>
3951 <listitem>
3952 <para>
3953 Frees the storage associated with a
3954 <structname>PGresult</structname>. Every command result should be
3955 freed via <xref linkend="libpq-PQclear"/> when it is no longer
3956 needed.
3958 <synopsis>
3959 void PQclear(PGresult *res);
3960 </synopsis>
3962 If the argument is a <symbol>NULL</symbol> pointer, no operation is
3963 performed.
3964 </para>
3966 <para>
3967 You can keep a <structname>PGresult</structname> object around for
3968 as long as you need it; it does not go away when you issue a new
3969 command, nor even if you close the connection. To get rid of it,
3970 you must call <xref linkend="libpq-PQclear"/>. Failure to do this
3971 will result in memory leaks in your application.
3972 </para>
3973 </listitem>
3974 </varlistentry>
3975 </variablelist>
3976 </para>
3977 </sect2>
3979 <sect2 id="libpq-exec-select-info">
3980 <title>Retrieving Query Result Information</title>
3982 <para>
3983 These functions are used to extract information from a
3984 <structname>PGresult</structname> object that represents a successful
3985 query result (that is, one that has status
3986 <literal>PGRES_TUPLES_OK</literal> or <literal>PGRES_SINGLE_TUPLE</literal>).
3987 They can also be used to extract
3988 information from a successful Describe operation: a Describe's result
3989 has all the same column information that actual execution of the query
3990 would provide, but it has zero rows. For objects with other status values,
3991 these functions will act as though the result has zero rows and zero columns.
3992 </para>
3994 <variablelist>
3995 <varlistentry id="libpq-PQntuples">
3996 <term><function>PQntuples</function><indexterm><primary>PQntuples</primary></indexterm></term>
3998 <listitem>
3999 <para>
4000 Returns the number of rows (tuples) in the query result.
4001 (Note that <structname>PGresult</structname> objects are limited to no more
4002 than <literal>INT_MAX</literal> rows, so an <type>int</type> result is
4003 sufficient.)
4005 <synopsis>
4006 int PQntuples(const PGresult *res);
4007 </synopsis>
4009 </para>
4010 </listitem>
4011 </varlistentry>
4013 <varlistentry id="libpq-PQnfields">
4014 <term><function>PQnfields</function><indexterm><primary>PQnfields</primary></indexterm></term>
4016 <listitem>
4017 <para>
4018 Returns the number of columns (fields) in each row of the query
4019 result.
4021 <synopsis>
4022 int PQnfields(const PGresult *res);
4023 </synopsis>
4024 </para>
4025 </listitem>
4026 </varlistentry>
4028 <varlistentry id="libpq-PQfname">
4029 <term><function>PQfname</function><indexterm><primary>PQfname</primary></indexterm></term>
4031 <listitem>
4032 <para>
4033 Returns the column name associated with the given column number.
4034 Column numbers start at 0. The caller should not free the result
4035 directly. It will be freed when the associated
4036 <structname>PGresult</structname> handle is passed to
4037 <xref linkend="libpq-PQclear"/>.
4038 <synopsis>
4039 char *PQfname(const PGresult *res,
4040 int column_number);
4041 </synopsis>
4042 </para>
4044 <para>
4045 <symbol>NULL</symbol> is returned if the column number is out of range.
4046 </para>
4047 </listitem>
4048 </varlistentry>
4050 <varlistentry id="libpq-PQfnumber">
4051 <term><function>PQfnumber</function><indexterm><primary>PQfnumber</primary></indexterm></term>
4053 <listitem>
4054 <para>
4055 Returns the column number associated with the given column name.
4056 <synopsis>
4057 int PQfnumber(const PGresult *res,
4058 const char *column_name);
4059 </synopsis>
4060 </para>
4062 <para>
4063 -1 is returned if the given name does not match any column.
4064 </para>
4066 <para>
4067 The given name is treated like an identifier in an SQL command,
4068 that is, it is downcased unless double-quoted. For example, given
4069 a query result generated from the SQL command:
4070 <programlisting>
4071 SELECT 1 AS FOO, 2 AS "BAR";
4072 </programlisting>
4073 we would have the results:
4074 <programlisting>
4075 PQfname(res, 0) <lineannotation>foo</lineannotation>
4076 PQfname(res, 1) <lineannotation>BAR</lineannotation>
4077 PQfnumber(res, "FOO") <lineannotation>0</lineannotation>
4078 PQfnumber(res, "foo") <lineannotation>0</lineannotation>
4079 PQfnumber(res, "BAR") <lineannotation>-1</lineannotation>
4080 PQfnumber(res, "\"BAR\"") <lineannotation>1</lineannotation>
4081 </programlisting>
4082 </para>
4083 </listitem>
4084 </varlistentry>
4086 <varlistentry id="libpq-PQftable">
4087 <term><function>PQftable</function><indexterm><primary>PQftable</primary></indexterm></term>
4089 <listitem>
4090 <para>
4091 Returns the OID of the table from which the given column was
4092 fetched. Column numbers start at 0.
4093 <synopsis>
4094 Oid PQftable(const PGresult *res,
4095 int column_number);
4096 </synopsis>
4097 </para>
4099 <para>
4100 <literal>InvalidOid</literal> is returned if the column number is out of range,
4101 or if the specified column is not a simple reference to a table column.
4102 You can query the system table <literal>pg_class</literal> to determine
4103 exactly which table is referenced.
4104 </para>
4106 <para>
4107 The type <type>Oid</type> and the constant
4108 <literal>InvalidOid</literal> will be defined when you include
4109 the <application>libpq</application> header file. They will both
4110 be some integer type.
4111 </para>
4112 </listitem>
4113 </varlistentry>
4115 <varlistentry id="libpq-PQftablecol">
4116 <term><function>PQftablecol</function><indexterm><primary>PQftablecol</primary></indexterm></term>
4118 <listitem>
4119 <para>
4120 Returns the column number (within its table) of the column making
4121 up the specified query result column. Query-result column numbers
4122 start at 0, but table columns have nonzero numbers.
4123 <synopsis>
4124 int PQftablecol(const PGresult *res,
4125 int column_number);
4126 </synopsis>
4127 </para>
4129 <para>
4130 Zero is returned if the column number is out of range, or if the
4131 specified column is not a simple reference to a table column.
4132 </para>
4133 </listitem>
4134 </varlistentry>
4136 <varlistentry id="libpq-PQfformat">
4137 <term><function>PQfformat</function><indexterm><primary>PQfformat</primary></indexterm></term>
4139 <listitem>
4140 <para>
4141 Returns the format code indicating the format of the given
4142 column. Column numbers start at 0.
4143 <synopsis>
4144 int PQfformat(const PGresult *res,
4145 int column_number);
4146 </synopsis>
4147 </para>
4149 <para>
4150 Format code zero indicates textual data representation, while format
4151 code one indicates binary representation. (Other codes are reserved
4152 for future definition.)
4153 </para>
4154 </listitem>
4155 </varlistentry>
4157 <varlistentry id="libpq-PQftype">
4158 <term><function>PQftype</function><indexterm><primary>PQftype</primary></indexterm></term>
4160 <listitem>
4161 <para>
4162 Returns the data type associated with the given column number.
4163 The integer returned is the internal OID number of the type.
4164 Column numbers start at 0.
4165 <synopsis>
4166 Oid PQftype(const PGresult *res,
4167 int column_number);
4168 </synopsis>
4169 </para>
4171 <para>
4172 You can query the system table <literal>pg_type</literal> to
4173 obtain the names and properties of the various data types. The
4174 <acronym>OID</acronym>s of the built-in data types are defined
4175 in the file <filename>catalog/pg_type_d.h</filename>
4176 in the <productname>PostgreSQL</productname>
4177 installation's <filename>include</filename> directory.
4178 </para>
4179 </listitem>
4180 </varlistentry>
4182 <varlistentry id="libpq-PQfmod">
4183 <term><function>PQfmod</function><indexterm><primary>PQfmod</primary></indexterm></term>
4185 <listitem>
4186 <para>
4187 Returns the type modifier of the column associated with the
4188 given column number. Column numbers start at 0.
4189 <synopsis>
4190 int PQfmod(const PGresult *res,
4191 int column_number);
4192 </synopsis>
4193 </para>
4195 <para>
4196 The interpretation of modifier values is type-specific; they
4197 typically indicate precision or size limits. The value -1 is
4198 used to indicate <quote>no information available</quote>. Most data
4199 types do not use modifiers, in which case the value is always
4201 </para>
4202 </listitem>
4203 </varlistentry>
4205 <varlistentry id="libpq-PQfsize">
4206 <term><function>PQfsize</function><indexterm><primary>PQfsize</primary></indexterm></term>
4208 <listitem>
4209 <para>
4210 Returns the size in bytes of the column associated with the
4211 given column number. Column numbers start at 0.
4212 <synopsis>
4213 int PQfsize(const PGresult *res,
4214 int column_number);
4215 </synopsis>
4216 </para>
4218 <para>
4219 <xref linkend="libpq-PQfsize"/> returns the space allocated for this column
4220 in a database row, in other words the size of the server's
4221 internal representation of the data type. (Accordingly, it is
4222 not really very useful to clients.) A negative value indicates
4223 the data type is variable-length.
4224 </para>
4225 </listitem>
4226 </varlistentry>
4228 <varlistentry id="libpq-PQbinaryTuples">
4229 <term><function>PQbinaryTuples</function><indexterm><primary>PQbinaryTuples</primary></indexterm></term>
4231 <listitem>
4232 <para>
4233 Returns 1 if the <structname>PGresult</structname> contains binary data
4234 and 0 if it contains text data.
4235 <synopsis>
4236 int PQbinaryTuples(const PGresult *res);
4237 </synopsis>
4238 </para>
4240 <para>
4241 This function is deprecated (except for its use in connection with
4242 <command>COPY</command>), because it is possible for a single
4243 <structname>PGresult</structname> to contain text data in some columns and
4244 binary data in others. <xref linkend="libpq-PQfformat"/> is preferred.
4245 <xref linkend="libpq-PQbinaryTuples"/> returns 1 only if all columns of the
4246 result are binary (format 1).
4247 </para>
4248 </listitem>
4249 </varlistentry>
4251 <varlistentry id="libpq-PQgetvalue">
4252 <term><function>PQgetvalue</function><indexterm><primary>PQgetvalue</primary></indexterm></term>
4254 <listitem>
4255 <para>
4256 Returns a single field value of one row of a
4257 <structname>PGresult</structname>. Row and column numbers start
4258 at 0. The caller should not free the result directly. It will
4259 be freed when the associated <structname>PGresult</structname> handle is
4260 passed to <xref linkend="libpq-PQclear"/>.
4261 <synopsis>
4262 char *PQgetvalue(const PGresult *res,
4263 int row_number,
4264 int column_number);
4265 </synopsis>
4266 </para>
4268 <para>
4269 For data in text format, the value returned by
4270 <xref linkend="libpq-PQgetvalue"/> is a null-terminated character
4271 string representation of the field value. For data in binary
4272 format, the value is in the binary representation determined by
4273 the data type's <function>typsend</function> and <function>typreceive</function>
4274 functions. (The value is actually followed by a zero byte in
4275 this case too, but that is not ordinarily useful, since the
4276 value is likely to contain embedded nulls.)
4277 </para>
4279 <para>
4280 An empty string is returned if the field value is null. See
4281 <xref linkend="libpq-PQgetisnull"/> to distinguish null values from
4282 empty-string values.
4283 </para>
4285 <para>
4286 The pointer returned by <xref linkend="libpq-PQgetvalue"/> points
4287 to storage that is part of the <structname>PGresult</structname>
4288 structure. One should not modify the data it points to, and one
4289 must explicitly copy the data into other storage if it is to be
4290 used past the lifetime of the <structname>PGresult</structname>
4291 structure itself.
4292 </para>
4293 </listitem>
4294 </varlistentry>
4296 <varlistentry id="libpq-PQgetisnull">
4297 <term><function>PQgetisnull</function><indexterm
4298 ><primary>PQgetisnull</primary></indexterm><indexterm
4299 ><primary>null value</primary><secondary sortas="libpq">in libpq</secondary></indexterm></term>
4301 <listitem>
4302 <para>
4303 Tests a field for a null value. Row and column numbers start
4304 at 0.
4305 <synopsis>
4306 int PQgetisnull(const PGresult *res,
4307 int row_number,
4308 int column_number);
4309 </synopsis>
4310 </para>
4312 <para>
4313 This function returns 1 if the field is null and 0 if it
4314 contains a non-null value. (Note that
4315 <xref linkend="libpq-PQgetvalue"/> will return an empty string,
4316 not a null pointer, for a null field.)
4317 </para>
4318 </listitem>
4319 </varlistentry>
4321 <varlistentry id="libpq-PQgetlength">
4322 <term><function>PQgetlength</function><indexterm><primary>PQgetlength</primary></indexterm></term>
4324 <listitem>
4325 <para>
4326 Returns the actual length of a field value in bytes. Row and
4327 column numbers start at 0.
4328 <synopsis>
4329 int PQgetlength(const PGresult *res,
4330 int row_number,
4331 int column_number);
4332 </synopsis>
4333 </para>
4335 <para>
4336 This is the actual data length for the particular data value,
4337 that is, the size of the object pointed to by
4338 <xref linkend="libpq-PQgetvalue"/>. For text data format this is
4339 the same as <function>strlen()</function>. For binary format this is
4340 essential information. Note that one should <emphasis>not</emphasis>
4341 rely on <xref linkend="libpq-PQfsize"/> to obtain the actual data
4342 length.
4343 </para>
4344 </listitem>
4345 </varlistentry>
4347 <varlistentry id="libpq-PQnparams">
4348 <term><function>PQnparams</function><indexterm><primary>PQnparams</primary></indexterm></term>
4350 <listitem>
4351 <para>
4352 Returns the number of parameters of a prepared statement.
4353 <synopsis>
4354 int PQnparams(const PGresult *res);
4355 </synopsis>
4356 </para>
4358 <para>
4359 This function is only useful when inspecting the result of
4360 <xref linkend="libpq-PQdescribePrepared"/>. For other types of results it
4361 will return zero.
4362 </para>
4363 </listitem>
4364 </varlistentry>
4366 <varlistentry id="libpq-PQparamtype">
4367 <term><function>PQparamtype</function><indexterm><primary>PQparamtype</primary></indexterm></term>
4369 <listitem>
4370 <para>
4371 Returns the data type of the indicated statement parameter.
4372 Parameter numbers start at 0.
4373 <synopsis>
4374 Oid PQparamtype(const PGresult *res, int param_number);
4375 </synopsis>
4376 </para>
4378 <para>
4379 This function is only useful when inspecting the result of
4380 <xref linkend="libpq-PQdescribePrepared"/>. For other types of results it
4381 will return zero.
4382 </para>
4383 </listitem>
4384 </varlistentry>
4386 <varlistentry id="libpq-PQprint">
4387 <term><function>PQprint</function><indexterm><primary>PQprint</primary></indexterm></term>
4389 <listitem>
4390 <para>
4391 Prints out all the rows and, optionally, the column names to
4392 the specified output stream.
4393 <synopsis>
4394 void PQprint(FILE *fout, /* output stream */
4395 const PGresult *res,
4396 const PQprintOpt *po);
4397 typedef struct
4399 pqbool header; /* print output field headings and row count */
4400 pqbool align; /* fill align the fields */
4401 pqbool standard; /* old brain dead format */
4402 pqbool html3; /* output HTML tables */
4403 pqbool expanded; /* expand tables */
4404 pqbool pager; /* use pager for output if needed */
4405 char *fieldSep; /* field separator */
4406 char *tableOpt; /* attributes for HTML table element */
4407 char *caption; /* HTML table caption */
4408 char **fieldName; /* null-terminated array of replacement field names */
4409 } PQprintOpt;
4410 </synopsis>
4411 </para>
4413 <para>
4414 This function was formerly used by <application>psql</application>
4415 to print query results, but this is no longer the case. Note
4416 that it assumes all the data is in text format.
4417 </para>
4418 </listitem>
4419 </varlistentry>
4420 </variablelist>
4421 </sect2>
4423 <sect2 id="libpq-exec-nonselect">
4424 <title>Retrieving Other Result Information</title>
4426 <para>
4427 These functions are used to extract other information from
4428 <structname>PGresult</structname> objects.
4429 </para>
4431 <variablelist>
4432 <varlistentry id="libpq-PQcmdStatus">
4433 <term><function>PQcmdStatus</function><indexterm><primary>PQcmdStatus</primary></indexterm></term>
4435 <listitem>
4436 <para>
4437 Returns the command status tag from the SQL command that generated
4438 the <structname>PGresult</structname>.
4439 <synopsis>
4440 char *PQcmdStatus(PGresult *res);
4441 </synopsis>
4442 </para>
4444 <para>
4445 Commonly this is just the name of the command, but it might include
4446 additional data such as the number of rows processed. The caller
4447 should not free the result directly. It will be freed when the
4448 associated <structname>PGresult</structname> handle is passed to
4449 <xref linkend="libpq-PQclear"/>.
4450 </para>
4451 </listitem>
4452 </varlistentry>
4454 <varlistentry id="libpq-PQcmdTuples">
4455 <term><function>PQcmdTuples</function><indexterm><primary>PQcmdTuples</primary></indexterm></term>
4457 <listitem>
4458 <para>
4459 Returns the number of rows affected by the SQL command.
4460 <synopsis>
4461 char *PQcmdTuples(PGresult *res);
4462 </synopsis>
4463 </para>
4465 <para>
4466 This function returns a string containing the number of rows
4467 affected by the <acronym>SQL</acronym> statement that generated the
4468 <structname>PGresult</structname>. This function can only be used following
4469 the execution of a <command>SELECT</command>, <command>CREATE TABLE AS</command>,
4470 <command>INSERT</command>, <command>UPDATE</command>, <command>DELETE</command>,
4471 <command>MERGE</command>, <command>MOVE</command>, <command>FETCH</command>,
4472 or <command>COPY</command> statement, or an <command>EXECUTE</command> of a
4473 prepared query that contains an <command>INSERT</command>,
4474 <command>UPDATE</command>, <command>DELETE</command>,
4475 or <command>MERGE</command> statement.
4476 If the command that generated the <structname>PGresult</structname> was anything
4477 else, <xref linkend="libpq-PQcmdTuples"/> returns an empty string. The caller
4478 should not free the return value directly. It will be freed when
4479 the associated <structname>PGresult</structname> handle is passed to
4480 <xref linkend="libpq-PQclear"/>.
4481 </para>
4482 </listitem>
4483 </varlistentry>
4485 <varlistentry id="libpq-PQoidValue">
4486 <term><function>PQoidValue</function><indexterm><primary>PQoidValue</primary></indexterm></term>
4488 <listitem>
4489 <para>
4490 Returns the OID<indexterm><primary>OID</primary><secondary>in libpq</secondary></indexterm>
4491 of the inserted row, if the <acronym>SQL</acronym> command was an
4492 <command>INSERT</command> that inserted exactly one row into a table that
4493 has OIDs, or a <command>EXECUTE</command> of a prepared query containing
4494 a suitable <command>INSERT</command> statement. Otherwise, this function
4495 returns <literal>InvalidOid</literal>. This function will also
4496 return <literal>InvalidOid</literal> if the table affected by the
4497 <command>INSERT</command> statement does not contain OIDs.
4498 <synopsis>
4499 Oid PQoidValue(const PGresult *res);
4500 </synopsis>
4501 </para>
4502 </listitem>
4503 </varlistentry>
4505 <varlistentry id="libpq-PQoidStatus">
4506 <term><function>PQoidStatus</function><indexterm><primary>PQoidStatus</primary></indexterm></term>
4508 <listitem>
4509 <para>
4510 This function is deprecated in favor of
4511 <xref linkend="libpq-PQoidValue"/> and is not thread-safe.
4512 It returns a string with the OID of the inserted row, while
4513 <xref linkend="libpq-PQoidValue"/> returns the OID value.
4514 <synopsis>
4515 char *PQoidStatus(const PGresult *res);
4516 </synopsis>
4517 </para>
4519 </listitem>
4520 </varlistentry>
4521 </variablelist>
4523 </sect2>
4525 <sect2 id="libpq-exec-escape-string">
4526 <title>Escaping Strings for Inclusion in SQL Commands</title>
4528 <indexterm zone="libpq-exec-escape-string">
4529 <primary>escaping strings</primary>
4530 <secondary>in libpq</secondary>
4531 </indexterm>
4533 <variablelist>
4534 <varlistentry id="libpq-PQescapeLiteral">
4535 <term><function>PQescapeLiteral</function><indexterm><primary>PQescapeLiteral</primary></indexterm></term>
4537 <listitem>
4538 <para>
4539 <synopsis>
4540 char *PQescapeLiteral(PGconn *conn, const char *str, size_t length);
4541 </synopsis>
4542 </para>
4544 <para>
4545 <xref linkend="libpq-PQescapeLiteral"/> escapes a string for
4546 use within an SQL command. This is useful when inserting data
4547 values as literal constants in SQL commands. Certain characters
4548 (such as quotes and backslashes) must be escaped to prevent them
4549 from being interpreted specially by the SQL parser.
4550 <xref linkend="libpq-PQescapeLiteral"/> performs this operation.
4551 </para>
4553 <para>
4554 <xref linkend="libpq-PQescapeLiteral"/> returns an escaped version of the
4555 <parameter>str</parameter> parameter in memory allocated with
4556 <function>malloc()</function>. This memory should be freed using
4557 <function>PQfreemem()</function> when the result is no longer needed.
4558 A terminating zero byte is not required, and should not be
4559 counted in <parameter>length</parameter>. (If a terminating zero byte is found
4560 before <parameter>length</parameter> bytes are processed,
4561 <xref linkend="libpq-PQescapeLiteral"/> stops at the zero; the behavior is
4562 thus rather like <function>strncpy</function>.) The
4563 return string has all special characters replaced so that they can
4564 be properly processed by the <productname>PostgreSQL</productname>
4565 string literal parser. A terminating zero byte is also added. The
4566 single quotes that must surround <productname>PostgreSQL</productname>
4567 string literals are included in the result string.
4568 </para>
4570 <para>
4571 On error, <xref linkend="libpq-PQescapeLiteral"/> returns <symbol>NULL</symbol> and a suitable
4572 message is stored in the <parameter>conn</parameter> object.
4573 </para>
4575 <tip>
4576 <para>
4577 It is especially important to do proper escaping when handling
4578 strings that were received from an untrustworthy source.
4579 Otherwise there is a security risk: you are vulnerable to
4580 <quote>SQL injection</quote> attacks wherein unwanted SQL commands are
4581 fed to your database.
4582 </para>
4583 </tip>
4585 <para>
4586 Note that it is neither necessary nor correct to do escaping when a data
4587 value is passed as a separate parameter in <xref linkend="libpq-PQexecParams"/> or
4588 its sibling routines.
4589 </para>
4590 </listitem>
4591 </varlistentry>
4593 <varlistentry id="libpq-PQescapeIdentifier">
4594 <term><function>PQescapeIdentifier</function><indexterm><primary>PQescapeIdentifier</primary></indexterm></term>
4596 <listitem>
4597 <para>
4598 <synopsis>
4599 char *PQescapeIdentifier(PGconn *conn, const char *str, size_t length);
4600 </synopsis>
4601 </para>
4603 <para>
4604 <xref linkend="libpq-PQescapeIdentifier"/> escapes a string for
4605 use as an SQL identifier, such as a table, column, or function name.
4606 This is useful when a user-supplied identifier might contain
4607 special characters that would otherwise not be interpreted as part
4608 of the identifier by the SQL parser, or when the identifier might
4609 contain upper case characters whose case should be preserved.
4610 </para>
4612 <para>
4613 <xref linkend="libpq-PQescapeIdentifier"/> returns a version of the
4614 <parameter>str</parameter> parameter escaped as an SQL identifier
4615 in memory allocated with <function>malloc()</function>. This memory must be
4616 freed using <function>PQfreemem()</function> when the result is no longer
4617 needed. A terminating zero byte is not required, and should not be
4618 counted in <parameter>length</parameter>. (If a terminating zero byte is found
4619 before <parameter>length</parameter> bytes are processed,
4620 <xref linkend="libpq-PQescapeIdentifier"/> stops at the zero; the behavior is
4621 thus rather like <function>strncpy</function>.) The
4622 return string has all special characters replaced so that it
4623 will be properly processed as an SQL identifier. A terminating zero byte
4624 is also added. The return string will also be surrounded by double
4625 quotes.
4626 </para>
4628 <para>
4629 On error, <xref linkend="libpq-PQescapeIdentifier"/> returns <symbol>NULL</symbol> and a suitable
4630 message is stored in the <parameter>conn</parameter> object.
4631 </para>
4633 <tip>
4634 <para>
4635 As with string literals, to prevent SQL injection attacks,
4636 SQL identifiers must be escaped when they are received from an
4637 untrustworthy source.
4638 </para>
4639 </tip>
4640 </listitem>
4641 </varlistentry>
4643 <varlistentry id="libpq-PQescapeStringConn">
4644 <term><function>PQescapeStringConn</function><indexterm><primary>PQescapeStringConn</primary></indexterm></term>
4646 <listitem>
4647 <para>
4648 <synopsis>
4649 size_t PQescapeStringConn(PGconn *conn,
4650 char *to, const char *from, size_t length,
4651 int *error);
4652 </synopsis>
4653 </para>
4655 <para>
4656 <xref linkend="libpq-PQescapeStringConn"/> escapes string literals, much like
4657 <xref linkend="libpq-PQescapeLiteral"/>. Unlike <xref linkend="libpq-PQescapeLiteral"/>,
4658 the caller is responsible for providing an appropriately sized buffer.
4659 Furthermore, <xref linkend="libpq-PQescapeStringConn"/> does not generate the
4660 single quotes that must surround <productname>PostgreSQL</productname> string
4661 literals; they should be provided in the SQL command that the
4662 result is inserted into. The parameter <parameter>from</parameter> points to
4663 the first character of the string that is to be escaped, and the
4664 <parameter>length</parameter> parameter gives the number of bytes in this
4665 string. A terminating zero byte is not required, and should not be
4666 counted in <parameter>length</parameter>. (If a terminating zero byte is found
4667 before <parameter>length</parameter> bytes are processed,
4668 <xref linkend="libpq-PQescapeStringConn"/> stops at the zero; the behavior is
4669 thus rather like <function>strncpy</function>.) <parameter>to</parameter> shall point
4670 to a buffer that is able to hold at least one more byte than twice
4671 the value of <parameter>length</parameter>, otherwise the behavior is undefined.
4672 Behavior is likewise undefined if the <parameter>to</parameter> and
4673 <parameter>from</parameter> strings overlap.
4674 </para>
4676 <para>
4677 If the <parameter>error</parameter> parameter is not <symbol>NULL</symbol>, then
4678 <literal>*error</literal> is set to zero on success, nonzero on error.
4679 Presently the only possible error conditions involve invalid multibyte
4680 encoding in the source string. The output string is still generated
4681 on error, but it can be expected that the server will reject it as
4682 malformed. On error, a suitable message is stored in the
4683 <parameter>conn</parameter> object, whether or not <parameter>error</parameter> is <symbol>NULL</symbol>.
4684 </para>
4686 <para>
4687 <xref linkend="libpq-PQescapeStringConn"/> returns the number of bytes written
4688 to <parameter>to</parameter>, not including the terminating zero byte.
4689 </para>
4690 </listitem>
4691 </varlistentry>
4693 <varlistentry id="libpq-PQescapeString">
4694 <term><function>PQescapeString</function><indexterm><primary>PQescapeString</primary></indexterm></term>
4696 <listitem>
4697 <para>
4698 <xref linkend="libpq-PQescapeString"/> is an older, deprecated version of
4699 <xref linkend="libpq-PQescapeStringConn"/>.
4700 <synopsis>
4701 size_t PQescapeString (char *to, const char *from, size_t length);
4702 </synopsis>
4703 </para>
4705 <para>
4706 The only difference from <xref linkend="libpq-PQescapeStringConn"/> is that
4707 <xref linkend="libpq-PQescapeString"/> does not take <structname>PGconn</structname>
4708 or <parameter>error</parameter> parameters.
4709 Because of this, it cannot adjust its behavior depending on the
4710 connection properties (such as character encoding) and therefore
4711 <emphasis>it might give the wrong results</emphasis>. Also, it has no way
4712 to report error conditions.
4713 </para>
4715 <para>
4716 <xref linkend="libpq-PQescapeString"/> can be used safely in
4717 client programs that work with only one <productname>PostgreSQL</productname>
4718 connection at a time (in this case it can find out what it needs to
4719 know <quote>behind the scenes</quote>). In other contexts it is a security
4720 hazard and should be avoided in favor of
4721 <xref linkend="libpq-PQescapeStringConn"/>.
4722 </para>
4723 </listitem>
4724 </varlistentry>
4726 <varlistentry id="libpq-PQescapeByteaConn">
4727 <term><function>PQescapeByteaConn</function><indexterm><primary>PQescapeByteaConn</primary></indexterm></term>
4729 <listitem>
4730 <para>
4731 Escapes binary data for use within an SQL command with the type
4732 <type>bytea</type>. As with <xref linkend="libpq-PQescapeStringConn"/>,
4733 this is only used when inserting data directly into an SQL command string.
4734 <synopsis>
4735 unsigned char *PQescapeByteaConn(PGconn *conn,
4736 const unsigned char *from,
4737 size_t from_length,
4738 size_t *to_length);
4739 </synopsis>
4740 </para>
4742 <para>
4743 Certain byte values must be escaped when used as part of a
4744 <type>bytea</type> literal in an <acronym>SQL</acronym> statement.
4745 <xref linkend="libpq-PQescapeByteaConn"/> escapes bytes using
4746 either hex encoding or backslash escaping. See <xref
4747 linkend="datatype-binary"/> for more information.
4748 </para>
4750 <para>
4751 The <parameter>from</parameter> parameter points to the first
4752 byte of the string that is to be escaped, and the
4753 <parameter>from_length</parameter> parameter gives the number of
4754 bytes in this binary string. (A terminating zero byte is
4755 neither necessary nor counted.) The <parameter>to_length</parameter>
4756 parameter points to a variable that will hold the resultant
4757 escaped string length. This result string length includes the terminating
4758 zero byte of the result.
4759 </para>
4761 <para>
4762 <xref linkend="libpq-PQescapeByteaConn"/> returns an escaped version of the
4763 <parameter>from</parameter> parameter binary string in memory
4764 allocated with <function>malloc()</function>. This memory should be freed using
4765 <function>PQfreemem()</function> when the result is no longer needed. The
4766 return string has all special characters replaced so that they can
4767 be properly processed by the <productname>PostgreSQL</productname>
4768 string literal parser, and the <type>bytea</type> input function. A
4769 terminating zero byte is also added. The single quotes that must
4770 surround <productname>PostgreSQL</productname> string literals are
4771 not part of the result string.
4772 </para>
4774 <para>
4775 On error, a null pointer is returned, and a suitable error message
4776 is stored in the <parameter>conn</parameter> object. Currently, the only
4777 possible error is insufficient memory for the result string.
4778 </para>
4779 </listitem>
4780 </varlistentry>
4782 <varlistentry id="libpq-PQescapeBytea">
4783 <term><function>PQescapeBytea</function><indexterm><primary>PQescapeBytea</primary></indexterm></term>
4785 <listitem>
4786 <para>
4787 <xref linkend="libpq-PQescapeBytea"/> is an older, deprecated version of
4788 <xref linkend="libpq-PQescapeByteaConn"/>.
4789 <synopsis>
4790 unsigned char *PQescapeBytea(const unsigned char *from,
4791 size_t from_length,
4792 size_t *to_length);
4793 </synopsis>
4794 </para>
4796 <para>
4797 The only difference from <xref linkend="libpq-PQescapeByteaConn"/> is that
4798 <xref linkend="libpq-PQescapeBytea"/> does not take a <structname>PGconn</structname>
4799 parameter. Because of this, <xref linkend="libpq-PQescapeBytea"/> can
4800 only be used safely in client programs that use a single
4801 <productname>PostgreSQL</productname> connection at a time (in this case
4802 it can find out what it needs to know <quote>behind the
4803 scenes</quote>). It <emphasis>might give the wrong results</emphasis> if
4804 used in programs that use multiple database connections (use
4805 <xref linkend="libpq-PQescapeByteaConn"/> in such cases).
4806 </para>
4807 </listitem>
4808 </varlistentry>
4810 <varlistentry id="libpq-PQunescapeBytea">
4811 <term><function>PQunescapeBytea</function><indexterm><primary>PQunescapeBytea</primary></indexterm></term>
4813 <listitem>
4814 <para>
4815 Converts a string representation of binary data into binary data
4816 &mdash; the reverse of <xref linkend="libpq-PQescapeBytea"/>. This
4817 is needed when retrieving <type>bytea</type> data in text format,
4818 but not when retrieving it in binary format.
4820 <synopsis>
4821 unsigned char *PQunescapeBytea(const unsigned char *from, size_t *to_length);
4822 </synopsis>
4823 </para>
4825 <para>
4826 The <parameter>from</parameter> parameter points to a string
4827 such as might be returned by <xref linkend="libpq-PQgetvalue"/> when applied
4828 to a <type>bytea</type> column. <xref linkend="libpq-PQunescapeBytea"/>
4829 converts this string representation into its binary representation.
4830 It returns a pointer to a buffer allocated with
4831 <function>malloc()</function>, or <symbol>NULL</symbol> on error, and puts the size of
4832 the buffer in <parameter>to_length</parameter>. The result must be
4833 freed using <xref linkend="libpq-PQfreemem"/> when it is no longer needed.
4834 </para>
4836 <para>
4837 This conversion is not exactly the inverse of
4838 <xref linkend="libpq-PQescapeBytea"/>, because the string is not expected
4839 to be <quote>escaped</quote> when received from <xref linkend="libpq-PQgetvalue"/>.
4840 In particular this means there is no need for string quoting considerations,
4841 and so no need for a <structname>PGconn</structname> parameter.
4842 </para>
4843 </listitem>
4844 </varlistentry>
4845 </variablelist>
4847 </sect2>
4849 </sect1>
4851 <sect1 id="libpq-async">
4852 <title>Asynchronous Command Processing</title>
4854 <indexterm zone="libpq-async">
4855 <primary>nonblocking connection</primary>
4856 </indexterm>
4858 <para>
4859 The <xref linkend="libpq-PQexec"/> function is adequate for submitting
4860 commands in normal, synchronous applications. It has a few
4861 deficiencies, however, that can be of importance to some users:
4863 <itemizedlist>
4864 <listitem>
4865 <para>
4866 <xref linkend="libpq-PQexec"/> waits for the command to be completed.
4867 The application might have other work to do (such as maintaining a
4868 user interface), in which case it won't want to block waiting for
4869 the response.
4870 </para>
4871 </listitem>
4873 <listitem>
4874 <para>
4875 Since the execution of the client application is suspended while it
4876 waits for the result, it is hard for the application to decide that
4877 it would like to try to cancel the ongoing command. (It can be done
4878 from a signal handler, but not otherwise.)
4879 </para>
4880 </listitem>
4882 <listitem>
4883 <para>
4884 <xref linkend="libpq-PQexec"/> can return only one
4885 <structname>PGresult</structname> structure. If the submitted command
4886 string contains multiple <acronym>SQL</acronym> commands, all but
4887 the last <structname>PGresult</structname> are discarded by
4888 <xref linkend="libpq-PQexec"/>.
4889 </para>
4890 </listitem>
4892 <listitem>
4893 <para>
4894 <xref linkend="libpq-PQexec"/> always collects the command's entire result,
4895 buffering it in a single <structname>PGresult</structname>. While
4896 this simplifies error-handling logic for the application, it can be
4897 impractical for results containing many rows.
4898 </para>
4899 </listitem>
4900 </itemizedlist>
4901 </para>
4903 <para>
4904 Applications that do not like these limitations can instead use the
4905 underlying functions that <xref linkend="libpq-PQexec"/> is built from:
4906 <xref linkend="libpq-PQsendQuery"/> and <xref linkend="libpq-PQgetResult"/>.
4907 There are also
4908 <xref linkend="libpq-PQsendQueryParams"/>,
4909 <xref linkend="libpq-PQsendPrepare"/>,
4910 <xref linkend="libpq-PQsendQueryPrepared"/>,
4911 <xref linkend="libpq-PQsendDescribePrepared"/>,
4912 <xref linkend="libpq-PQsendDescribePortal"/>,
4913 <xref linkend="libpq-PQsendClosePrepared"/>, and
4914 <xref linkend="libpq-PQsendClosePortal"/>,
4915 which can be used with <xref linkend="libpq-PQgetResult"/> to duplicate
4916 the functionality of
4917 <xref linkend="libpq-PQexecParams"/>,
4918 <xref linkend="libpq-PQprepare"/>,
4919 <xref linkend="libpq-PQexecPrepared"/>,
4920 <xref linkend="libpq-PQdescribePrepared"/>,
4921 <xref linkend="libpq-PQdescribePortal"/>
4922 <xref linkend="libpq-PQclosePrepared"/>, and
4923 <xref linkend="libpq-PQclosePortal"/>
4924 respectively.
4926 <variablelist>
4927 <varlistentry id="libpq-PQsendQuery">
4928 <term><function>PQsendQuery</function><indexterm><primary>PQsendQuery</primary></indexterm></term>
4930 <listitem>
4931 <para>
4932 Submits a command to the server without waiting for the result(s).
4933 1 is returned if the command was successfully dispatched and 0 if
4934 not (in which case, use <xref linkend="libpq-PQerrorMessage"/> to get more
4935 information about the failure).
4936 <synopsis>
4937 int PQsendQuery(PGconn *conn, const char *command);
4938 </synopsis>
4940 After successfully calling <xref linkend="libpq-PQsendQuery"/>, call
4941 <xref linkend="libpq-PQgetResult"/> one or more times to obtain the
4942 results. <xref linkend="libpq-PQsendQuery"/> cannot be called again
4943 (on the same connection) until <xref linkend="libpq-PQgetResult"/>
4944 has returned a null pointer, indicating that the command is done.
4945 </para>
4947 <para>
4948 In pipeline mode, this function is disallowed.
4949 </para>
4950 </listitem>
4951 </varlistentry>
4953 <varlistentry id="libpq-PQsendQueryParams">
4954 <term><function>PQsendQueryParams</function><indexterm><primary>PQsendQueryParams</primary></indexterm></term>
4956 <listitem>
4957 <para>
4958 Submits a command and separate parameters to the server without
4959 waiting for the result(s).
4960 <synopsis>
4961 int PQsendQueryParams(PGconn *conn,
4962 const char *command,
4963 int nParams,
4964 const Oid *paramTypes,
4965 const char * const *paramValues,
4966 const int *paramLengths,
4967 const int *paramFormats,
4968 int resultFormat);
4969 </synopsis>
4971 This is equivalent to <xref linkend="libpq-PQsendQuery"/> except that
4972 query parameters can be specified separately from the query string.
4973 The function's parameters are handled identically to
4974 <xref linkend="libpq-PQexecParams"/>. Like
4975 <xref linkend="libpq-PQexecParams"/>, it allows only one command in the
4976 query string.
4977 </para>
4978 </listitem>
4979 </varlistentry>
4981 <varlistentry id="libpq-PQsendPrepare">
4982 <term><function>PQsendPrepare</function><indexterm><primary>PQsendPrepare</primary></indexterm></term>
4984 <listitem>
4985 <para>
4986 Sends a request to create a prepared statement with the given
4987 parameters, without waiting for completion.
4988 <synopsis>
4989 int PQsendPrepare(PGconn *conn,
4990 const char *stmtName,
4991 const char *query,
4992 int nParams,
4993 const Oid *paramTypes);
4994 </synopsis>
4996 This is an asynchronous version of <xref linkend="libpq-PQprepare"/>: it
4997 returns 1 if it was able to dispatch the request, and 0 if not.
4998 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
4999 determine whether the server successfully created the prepared
5000 statement. The function's parameters are handled identically to
5001 <xref linkend="libpq-PQprepare"/>.
5002 </para>
5003 </listitem>
5004 </varlistentry>
5006 <varlistentry id="libpq-PQsendQueryPrepared">
5007 <term><function>PQsendQueryPrepared</function><indexterm><primary>PQsendQueryPrepared</primary></indexterm></term>
5009 <listitem>
5010 <para>
5011 Sends a request to execute a prepared statement with given
5012 parameters, without waiting for the result(s).
5013 <synopsis>
5014 int PQsendQueryPrepared(PGconn *conn,
5015 const char *stmtName,
5016 int nParams,
5017 const char * const *paramValues,
5018 const int *paramLengths,
5019 const int *paramFormats,
5020 int resultFormat);
5021 </synopsis>
5023 This is similar to <xref linkend="libpq-PQsendQueryParams"/>, but
5024 the command to be executed is specified by naming a
5025 previously-prepared statement, instead of giving a query string.
5026 The function's parameters are handled identically to
5027 <xref linkend="libpq-PQexecPrepared"/>.
5028 </para>
5029 </listitem>
5030 </varlistentry>
5032 <varlistentry id="libpq-PQsendDescribePrepared">
5033 <term><function>PQsendDescribePrepared</function><indexterm><primary>PQsendDescribePrepared</primary></indexterm></term>
5035 <listitem>
5036 <para>
5037 Submits a request to obtain information about the specified
5038 prepared statement, without waiting for completion.
5039 <synopsis>
5040 int PQsendDescribePrepared(PGconn *conn, const char *stmtName);
5041 </synopsis>
5043 This is an asynchronous version of <xref linkend="libpq-PQdescribePrepared"/>:
5044 it returns 1 if it was able to dispatch the request, and 0 if not.
5045 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
5046 obtain the results. The function's parameters are handled
5047 identically to <xref linkend="libpq-PQdescribePrepared"/>.
5048 </para>
5049 </listitem>
5050 </varlistentry>
5052 <varlistentry id="libpq-PQsendDescribePortal">
5053 <term><function>PQsendDescribePortal</function><indexterm><primary>PQsendDescribePortal</primary></indexterm></term>
5055 <listitem>
5056 <para>
5057 Submits a request to obtain information about the specified
5058 portal, without waiting for completion.
5059 <synopsis>
5060 int PQsendDescribePortal(PGconn *conn, const char *portalName);
5061 </synopsis>
5063 This is an asynchronous version of <xref linkend="libpq-PQdescribePortal"/>:
5064 it returns 1 if it was able to dispatch the request, and 0 if not.
5065 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
5066 obtain the results. The function's parameters are handled
5067 identically to <xref linkend="libpq-PQdescribePortal"/>.
5068 </para>
5069 </listitem>
5070 </varlistentry>
5072 <varlistentry id="libpq-PQsendClosePrepared">
5073 <term><function>PQsendClosePrepared</function><indexterm><primary>PQsendClosePrepared</primary></indexterm></term>
5075 <listitem>
5076 <para>
5077 Submits a request to close the specified prepared statement, without
5078 waiting for completion.
5079 <synopsis>
5080 int PQsendClosePrepared(PGconn *conn, const char *stmtName);
5081 </synopsis>
5083 This is an asynchronous version of <xref linkend="libpq-PQclosePrepared"/>:
5084 it returns 1 if it was able to dispatch the request, and 0 if not.
5085 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
5086 obtain the results. The function's parameters are handled
5087 identically to <xref linkend="libpq-PQclosePrepared"/>.
5088 </para>
5089 </listitem>
5090 </varlistentry>
5092 <varlistentry id="libpq-PQsendClosePortal">
5093 <term><function>PQsendClosePortal</function><indexterm><primary>PQsendClosePortal</primary></indexterm></term>
5095 <listitem>
5096 <para>
5097 Submits a request to close specified portal, without waiting for
5098 completion.
5099 <synopsis>
5100 int PQsendClosePortal(PGconn *conn, const char *portalName);
5101 </synopsis>
5103 This is an asynchronous version of <xref linkend="libpq-PQclosePortal"/>:
5104 it returns 1 if it was able to dispatch the request, and 0 if not.
5105 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
5106 obtain the results. The function's parameters are handled
5107 identically to <xref linkend="libpq-PQclosePortal"/>.
5108 </para>
5109 </listitem>
5110 </varlistentry>
5112 <varlistentry id="libpq-PQgetResult">
5113 <term><function>PQgetResult</function><indexterm><primary>PQgetResult</primary></indexterm></term>
5115 <listitem>
5116 <para>
5117 Waits for the next result from a prior
5118 <xref linkend="libpq-PQsendQuery"/>,
5119 <xref linkend="libpq-PQsendQueryParams"/>,
5120 <xref linkend="libpq-PQsendPrepare"/>,
5121 <xref linkend="libpq-PQsendQueryPrepared"/>,
5122 <xref linkend="libpq-PQsendDescribePrepared"/>,
5123 <xref linkend="libpq-PQsendDescribePortal"/>,
5124 <xref linkend="libpq-PQsendClosePrepared"/>,
5125 <xref linkend="libpq-PQsendClosePortal"/>, or
5126 <xref linkend="libpq-PQpipelineSync"/>
5127 call, and returns it.
5128 A null pointer is returned when the command is complete and there
5129 will be no more results.
5130 <synopsis>
5131 PGresult *PQgetResult(PGconn *conn);
5132 </synopsis>
5133 </para>
5135 <para>
5136 <xref linkend="libpq-PQgetResult"/> must be called repeatedly until
5137 it returns a null pointer, indicating that the command is done.
5138 (If called when no command is active,
5139 <xref linkend="libpq-PQgetResult"/> will just return a null pointer
5140 at once.) Each non-null result from
5141 <xref linkend="libpq-PQgetResult"/> should be processed using the
5142 same <structname>PGresult</structname> accessor functions previously
5143 described. Don't forget to free each result object with
5144 <xref linkend="libpq-PQclear"/> when done with it. Note that
5145 <xref linkend="libpq-PQgetResult"/> will block only if a command is
5146 active and the necessary response data has not yet been read by
5147 <xref linkend="libpq-PQconsumeInput"/>.
5148 </para>
5150 <para>
5151 In pipeline mode, <function>PQgetResult</function> will return normally
5152 unless an error occurs; for any subsequent query sent after the one
5153 that caused the error until (and excluding) the next synchronization point,
5154 a special result of type <literal>PGRES_PIPELINE_ABORTED</literal> will
5155 be returned, and a null pointer will be returned after it.
5156 When the pipeline synchronization point is reached, a result of type
5157 <literal>PGRES_PIPELINE_SYNC</literal> will be returned.
5158 The result of the next query after the synchronization point follows
5159 immediately (that is, no null pointer is returned after
5160 the synchronization point.)
5161 </para>
5163 <note>
5164 <para>
5165 Even when <xref linkend="libpq-PQresultStatus"/> indicates a fatal
5166 error, <xref linkend="libpq-PQgetResult"/> should be called until it
5167 returns a null pointer, to allow <application>libpq</application> to
5168 process the error information completely.
5169 </para>
5170 </note>
5171 </listitem>
5172 </varlistentry>
5173 </variablelist>
5174 </para>
5176 <para>
5177 Using <xref linkend="libpq-PQsendQuery"/> and
5178 <xref linkend="libpq-PQgetResult"/> solves one of
5179 <xref linkend="libpq-PQexec"/>'s problems: If a command string contains
5180 multiple <acronym>SQL</acronym> commands, the results of those commands
5181 can be obtained individually. (This allows a simple form of overlapped
5182 processing, by the way: the client can be handling the results of one
5183 command while the server is still working on later queries in the same
5184 command string.)
5185 </para>
5187 <para>
5188 Another frequently-desired feature that can be obtained with
5189 <xref linkend="libpq-PQsendQuery"/> and <xref linkend="libpq-PQgetResult"/>
5190 is retrieving large query results a row at a time. This is discussed
5191 in <xref linkend="libpq-single-row-mode"/>.
5192 </para>
5194 <para>
5195 By itself, calling <xref linkend="libpq-PQgetResult"/>
5196 will still cause the client to block until the server completes the
5197 next <acronym>SQL</acronym> command. This can be avoided by proper
5198 use of two more functions:
5200 <variablelist>
5201 <varlistentry id="libpq-PQconsumeInput">
5202 <term><function>PQconsumeInput</function><indexterm><primary>PQconsumeInput</primary></indexterm>
5203 </term>
5205 <listitem>
5206 <para>
5207 If input is available from the server, consume it.
5208 <synopsis>
5209 int PQconsumeInput(PGconn *conn);
5210 </synopsis>
5211 </para>
5213 <para>
5214 <xref linkend="libpq-PQconsumeInput"/> normally returns 1 indicating
5215 <quote>no error</quote>, but returns 0 if there was some kind of
5216 trouble (in which case <xref linkend="libpq-PQerrorMessage"/> can be
5217 consulted). Note that the result does not say whether any input
5218 data was actually collected. After calling
5219 <xref linkend="libpq-PQconsumeInput"/>, the application can check
5220 <xref linkend="libpq-PQisBusy"/> and/or
5221 <function>PQnotifies</function> to see if their state has changed.
5222 </para>
5224 <para>
5225 <xref linkend="libpq-PQconsumeInput"/> can be called even if the
5226 application is not prepared to deal with a result or notification
5227 just yet. The function will read available data and save it in
5228 a buffer, thereby causing a <function>select()</function>
5229 read-ready indication to go away. The application can thus use
5230 <xref linkend="libpq-PQconsumeInput"/> to clear the
5231 <function>select()</function> condition immediately, and then
5232 examine the results at leisure.
5233 </para>
5234 </listitem>
5235 </varlistentry>
5237 <varlistentry id="libpq-PQisBusy">
5238 <term><function>PQisBusy</function><indexterm><primary>PQisBusy</primary></indexterm></term>
5240 <listitem>
5241 <para>
5242 Returns 1 if a command is busy, that is,
5243 <xref linkend="libpq-PQgetResult"/> would block waiting for input.
5244 A 0 return indicates that <xref linkend="libpq-PQgetResult"/> can be
5245 called with assurance of not blocking.
5246 <synopsis>
5247 int PQisBusy(PGconn *conn);
5248 </synopsis>
5249 </para>
5251 <para>
5252 <xref linkend="libpq-PQisBusy"/> will not itself attempt to read data
5253 from the server; therefore <xref linkend="libpq-PQconsumeInput"/>
5254 must be invoked first, or the busy state will never end.
5255 </para>
5256 </listitem>
5257 </varlistentry>
5258 </variablelist>
5259 </para>
5261 <para>
5262 A typical application using these functions will have a main loop that
5263 uses <function>select()</function> or <function>poll()</function> to wait for
5264 all the conditions that it must respond to. One of the conditions
5265 will be input available from the server, which in terms of
5266 <function>select()</function> means readable data on the file
5267 descriptor identified by <xref linkend="libpq-PQsocket"/>. When the main
5268 loop detects input ready, it should call
5269 <xref linkend="libpq-PQconsumeInput"/> to read the input. It can then
5270 call <xref linkend="libpq-PQisBusy"/>, followed by
5271 <xref linkend="libpq-PQgetResult"/> if <xref linkend="libpq-PQisBusy"/>
5272 returns false (0). It can also call <function>PQnotifies</function>
5273 to detect <command>NOTIFY</command> messages (see <xref
5274 linkend="libpq-notify"/>).
5275 </para>
5277 <para>
5278 A client that uses
5279 <xref linkend="libpq-PQsendQuery"/>/<xref linkend="libpq-PQgetResult"/>
5280 can also attempt to cancel a command that is still being processed
5281 by the server; see <xref linkend="libpq-cancel"/>. But regardless of
5282 the return value of <xref linkend="libpq-PQcancel"/>, the application
5283 must continue with the normal result-reading sequence using
5284 <xref linkend="libpq-PQgetResult"/>. A successful cancellation will
5285 simply cause the command to terminate sooner than it would have
5286 otherwise.
5287 </para>
5289 <para>
5290 By using the functions described above, it is possible to avoid
5291 blocking while waiting for input from the database server. However,
5292 it is still possible that the application will block waiting to send
5293 output to the server. This is relatively uncommon but can happen if
5294 very long SQL commands or data values are sent. (It is much more
5295 probable if the application sends data via <command>COPY IN</command>,
5296 however.) To prevent this possibility and achieve completely
5297 nonblocking database operation, the following additional functions
5298 can be used.
5300 <variablelist>
5301 <varlistentry id="libpq-PQsetnonblocking">
5302 <term><function>PQsetnonblocking</function><indexterm><primary>PQsetnonblocking</primary></indexterm></term>
5304 <listitem>
5305 <para>
5306 Sets the nonblocking status of the connection.
5307 <synopsis>
5308 int PQsetnonblocking(PGconn *conn, int arg);
5309 </synopsis>
5310 </para>
5312 <para>
5313 Sets the state of the connection to nonblocking if
5314 <parameter>arg</parameter> is 1, or blocking if
5315 <parameter>arg</parameter> is 0. Returns 0 if OK, -1 if error.
5316 </para>
5318 <para>
5319 In the nonblocking state, successful calls to
5320 <xref linkend="libpq-PQsendQuery"/>, <xref linkend="libpq-PQputline"/>,
5321 <xref linkend="libpq-PQputnbytes"/>, <xref linkend="libpq-PQputCopyData"/>,
5322 and <xref linkend="libpq-PQendcopy"/> will not block; their changes
5323 are stored in the local output buffer until they are flushed.
5324 Unsuccessful calls will return an error and must be retried.
5325 </para>
5327 <para>
5328 Note that <xref linkend="libpq-PQexec"/> does not honor nonblocking
5329 mode; if it is called, it will act in blocking fashion anyway.
5330 </para>
5331 </listitem>
5332 </varlistentry>
5334 <varlistentry id="libpq-PQisnonblocking">
5335 <term><function>PQisnonblocking</function><indexterm><primary>PQisnonblocking</primary></indexterm></term>
5337 <listitem>
5338 <para>
5339 Returns the blocking status of the database connection.
5340 <synopsis>
5341 int PQisnonblocking(const PGconn *conn);
5342 </synopsis>
5343 </para>
5345 <para>
5346 Returns 1 if the connection is set to nonblocking mode and 0 if
5347 blocking.
5348 </para>
5349 </listitem>
5350 </varlistentry>
5352 <varlistentry id="libpq-PQflush">
5353 <term><function>PQflush</function><indexterm><primary>PQflush</primary></indexterm></term>
5355 <listitem>
5356 <para>
5357 Attempts to flush any queued output data to the server. Returns
5358 0 if successful (or if the send queue is empty), -1 if it failed
5359 for some reason, or 1 if it was unable to send all the data in
5360 the send queue yet (this case can only occur if the connection
5361 is nonblocking).
5362 <synopsis>
5363 int PQflush(PGconn *conn);
5364 </synopsis>
5365 </para>
5366 </listitem>
5367 </varlistentry>
5368 </variablelist>
5369 </para>
5371 <para>
5372 After sending any command or data on a nonblocking connection, call
5373 <xref linkend="libpq-PQflush"/>. If it returns 1, wait for the socket
5374 to become read- or write-ready. If it becomes write-ready, call
5375 <xref linkend="libpq-PQflush"/> again. If it becomes read-ready, call
5376 <xref linkend="libpq-PQconsumeInput"/>, then call
5377 <xref linkend="libpq-PQflush"/> again. Repeat until
5378 <xref linkend="libpq-PQflush"/> returns 0. (It is necessary to check for
5379 read-ready and drain the input with <xref linkend="libpq-PQconsumeInput"/>,
5380 because the server can block trying to send us data, e.g., NOTICE
5381 messages, and won't read our data until we read its.) Once
5382 <xref linkend="libpq-PQflush"/> returns 0, wait for the socket to be
5383 read-ready and then read the response as described above.
5384 </para>
5386 </sect1>
5388 <sect1 id="libpq-pipeline-mode">
5389 <title>Pipeline Mode</title>
5391 <indexterm zone="libpq-pipeline-mode">
5392 <primary>libpq</primary>
5393 <secondary>pipeline mode</secondary>
5394 </indexterm>
5396 <indexterm zone="libpq-pipeline-mode">
5397 <primary>pipelining</primary>
5398 <secondary>in libpq</secondary>
5399 </indexterm>
5401 <indexterm zone="libpq-pipeline-mode">
5402 <primary>batch mode</primary>
5403 <secondary>in libpq</secondary>
5404 </indexterm>
5406 <para>
5407 <application>libpq</application> pipeline mode allows applications to
5408 send a query without having to read the result of the previously
5409 sent query. Taking advantage of the pipeline mode, a client will wait
5410 less for the server, since multiple queries/results can be
5411 sent/received in a single network transaction.
5412 </para>
5414 <para>
5415 While pipeline mode provides a significant performance boost, writing
5416 clients using the pipeline mode is more complex because it involves
5417 managing a queue of pending queries and finding which result
5418 corresponds to which query in the queue.
5419 </para>
5421 <para>
5422 Pipeline mode also generally consumes more memory on both the client and server,
5423 though careful and aggressive management of the send/receive queue can mitigate
5424 this. This applies whether or not the connection is in blocking or non-blocking
5425 mode.
5426 </para>
5428 <para>
5429 While <application>libpq</application>'s pipeline API was introduced in
5430 <productname>PostgreSQL</productname> 14, it is a client-side feature
5431 which doesn't require special server support and works on any server
5432 that supports the v3 extended query protocol. For more information see
5433 <xref linkend="protocol-flow-pipelining"/>.
5434 </para>
5436 <sect2 id="libpq-pipeline-using">
5437 <title>Using Pipeline Mode</title>
5439 <para>
5440 To issue pipelines, the application must switch the connection
5441 into pipeline mode,
5442 which is done with <xref linkend="libpq-PQenterPipelineMode"/>.
5443 <xref linkend="libpq-PQpipelineStatus"/> can be used
5444 to test whether pipeline mode is active.
5445 In pipeline mode, only <link linkend="libpq-async">asynchronous operations</link>
5446 that utilize the extended query protocol
5447 are permitted, command strings containing multiple SQL commands are
5448 disallowed, and so is <literal>COPY</literal>.
5449 Using synchronous command execution functions
5450 such as <function>PQfn</function>,
5451 <function>PQexec</function>,
5452 <function>PQexecParams</function>,
5453 <function>PQprepare</function>,
5454 <function>PQexecPrepared</function>,
5455 <function>PQdescribePrepared</function>,
5456 <function>PQdescribePortal</function>,
5457 <function>PQclosePrepared</function>,
5458 <function>PQclosePortal</function>,
5459 is an error condition.
5460 <function>PQsendQuery</function> is
5461 also disallowed, because it uses the simple query protocol.
5462 Once all dispatched commands have had their results processed, and
5463 the end pipeline result has been consumed, the application may return
5464 to non-pipelined mode with <xref linkend="libpq-PQexitPipelineMode"/>.
5465 </para>
5467 <note>
5468 <para>
5469 It is best to use pipeline mode with <application>libpq</application> in
5470 <link linkend="libpq-PQsetnonblocking">non-blocking mode</link>. If used
5471 in blocking mode it is possible for a client/server deadlock to occur.
5472 <footnote>
5473 <para>
5474 The client will block trying to send queries to the server, but the
5475 server will block trying to send results to the client from queries
5476 it has already processed. This only occurs when the client sends
5477 enough queries to fill both its output buffer and the server's receive
5478 buffer before it switches to processing input from the server,
5479 but it's hard to predict exactly when that will happen.
5480 </para>
5481 </footnote>
5482 </para>
5483 </note>
5485 <sect3 id="libpq-pipeline-sending">
5486 <title>Issuing Queries</title>
5488 <para>
5489 After entering pipeline mode, the application dispatches requests using
5490 <xref linkend="libpq-PQsendQueryParams"/>
5491 or its prepared-query sibling
5492 <xref linkend="libpq-PQsendQueryPrepared"/>.
5493 These requests are queued on the client-side until flushed to the server;
5494 this occurs when <xref linkend="libpq-PQpipelineSync"/> is used to
5495 establish a synchronization point in the pipeline,
5496 or when <xref linkend="libpq-PQflush"/> is called.
5497 The functions <xref linkend="libpq-PQsendPrepare"/>,
5498 <xref linkend="libpq-PQsendDescribePrepared"/>,
5499 <xref linkend="libpq-PQsendDescribePortal"/>,
5500 <xref linkend="libpq-PQsendClosePrepared"/>, and
5501 <xref linkend="libpq-PQsendClosePortal"/> also work in pipeline mode.
5502 Result processing is described below.
5503 </para>
5505 <para>
5506 The server executes statements, and returns results, in the order the
5507 client sends them. The server will begin executing the commands in the
5508 pipeline immediately, not waiting for the end of the pipeline.
5509 Note that results are buffered on the server side; the server flushes
5510 that buffer when a synchronization point is established with
5511 <function>PQpipelineSync</function>, or when
5512 <function>PQsendFlushRequest</function> is called.
5513 If any statement encounters an error, the server aborts the current
5514 transaction and does not execute any subsequent command in the queue
5515 until the next synchronization point;
5516 a <literal>PGRES_PIPELINE_ABORTED</literal> result is produced for
5517 each such command.
5518 (This remains true even if the commands in the pipeline would rollback
5519 the transaction.)
5520 Query processing resumes after the synchronization point.
5521 </para>
5523 <para>
5524 It's fine for one operation to depend on the results of a
5525 prior one; for example, one query may define a table that the next
5526 query in the same pipeline uses. Similarly, an application may
5527 create a named prepared statement and execute it with later
5528 statements in the same pipeline.
5529 </para>
5530 </sect3>
5532 <sect3 id="libpq-pipeline-results">
5533 <title>Processing Results</title>
5535 <para>
5536 To process the result of one query in a pipeline, the application calls
5537 <function>PQgetResult</function> repeatedly and handles each result
5538 until <function>PQgetResult</function> returns null.
5539 The result from the next query in the pipeline may then be retrieved using
5540 <function>PQgetResult</function> again and the cycle repeated.
5541 The application handles individual statement results as normal.
5542 When the results of all the queries in the pipeline have been
5543 returned, <function>PQgetResult</function> returns a result
5544 containing the status value <literal>PGRES_PIPELINE_SYNC</literal>
5545 </para>
5547 <para>
5548 The client may choose to defer result processing until the complete
5549 pipeline has been sent, or interleave that with sending further
5550 queries in the pipeline; see <xref linkend="libpq-pipeline-interleave"/>.
5551 </para>
5553 <para>
5554 To enter single-row mode, call <function>PQsetSingleRowMode</function>
5555 before retrieving results with <function>PQgetResult</function>.
5556 This mode selection is effective only for the query currently
5557 being processed. For more information on the use of
5558 <function>PQsetSingleRowMode</function>,
5559 refer to <xref linkend="libpq-single-row-mode"/>.
5560 </para>
5562 <para>
5563 <function>PQgetResult</function> behaves the same as for normal
5564 asynchronous processing except that it may contain the new
5565 <type>PGresult</type> types <literal>PGRES_PIPELINE_SYNC</literal>
5566 and <literal>PGRES_PIPELINE_ABORTED</literal>.
5567 <literal>PGRES_PIPELINE_SYNC</literal> is reported exactly once for each
5568 <function>PQpipelineSync</function> at the corresponding point
5569 in the pipeline.
5570 <literal>PGRES_PIPELINE_ABORTED</literal> is emitted in place of a normal
5571 query result for the first error and all subsequent results
5572 until the next <literal>PGRES_PIPELINE_SYNC</literal>;
5573 see <xref linkend="libpq-pipeline-errors"/>.
5574 </para>
5576 <para>
5577 <function>PQisBusy</function>, <function>PQconsumeInput</function>, etc
5578 operate as normal when processing pipeline results. In particular,
5579 a call to <function>PQisBusy</function> in the middle of a pipeline
5580 returns 0 if the results for all the queries issued so far have been
5581 consumed.
5582 </para>
5584 <para>
5585 <application>libpq</application> does not provide any information to the
5586 application about the query currently being processed (except that
5587 <function>PQgetResult</function> returns null to indicate that we start
5588 returning the results of next query). The application must keep track
5589 of the order in which it sent queries, to associate them with their
5590 corresponding results.
5591 Applications will typically use a state machine or a FIFO queue for this.
5592 </para>
5594 </sect3>
5596 <sect3 id="libpq-pipeline-errors">
5597 <title>Error Handling</title>
5599 <para>
5600 From the client's perspective, after <function>PQresultStatus</function>
5601 returns <literal>PGRES_FATAL_ERROR</literal>,
5602 the pipeline is flagged as aborted.
5603 <function>PQresultStatus</function> will report a
5604 <literal>PGRES_PIPELINE_ABORTED</literal> result for each remaining queued
5605 operation in an aborted pipeline. The result for
5606 <function>PQpipelineSync</function> is reported as
5607 <literal>PGRES_PIPELINE_SYNC</literal> to signal the end of the aborted pipeline
5608 and resumption of normal result processing.
5609 </para>
5611 <para>
5612 The client <emphasis>must</emphasis> process results with
5613 <function>PQgetResult</function> during error recovery.
5614 </para>
5616 <para>
5617 If the pipeline used an implicit transaction, then operations that have
5618 already executed are rolled back and operations that were queued to follow
5619 the failed operation are skipped entirely. The same behavior holds if the
5620 pipeline starts and commits a single explicit transaction (i.e. the first
5621 statement is <literal>BEGIN</literal> and the last is
5622 <literal>COMMIT</literal>) except that the session remains in an aborted
5623 transaction state at the end of the pipeline. If a pipeline contains
5624 <emphasis>multiple explicit transactions</emphasis>, all transactions that
5625 committed prior to the error remain committed, the currently in-progress
5626 transaction is aborted, and all subsequent operations are skipped completely,
5627 including subsequent transactions. If a pipeline synchronization point
5628 occurs with an explicit transaction block in aborted state, the next pipeline
5629 will become aborted immediately unless the next command puts the transaction
5630 in normal mode with <command>ROLLBACK</command>.
5631 </para>
5633 <note>
5634 <para>
5635 The client must not assume that work is committed when it
5636 <emphasis>sends</emphasis> a <literal>COMMIT</literal> &mdash; only when the
5637 corresponding result is received to confirm the commit is complete.
5638 Because errors arrive asynchronously, the application needs to be able to
5639 restart from the last <emphasis>received</emphasis> committed change and
5640 resend work done after that point if something goes wrong.
5641 </para>
5642 </note>
5643 </sect3>
5645 <sect3 id="libpq-pipeline-interleave">
5646 <title>Interleaving Result Processing and Query Dispatch</title>
5648 <para>
5649 To avoid deadlocks on large pipelines the client should be structured
5650 around a non-blocking event loop using operating system facilities
5651 such as <function>select</function>, <function>poll</function>,
5652 <function>WaitForMultipleObjectEx</function>, etc.
5653 </para>
5655 <para>
5656 The client application should generally maintain a queue of work
5657 remaining to be dispatched and a queue of work that has been dispatched
5658 but not yet had its results processed. When the socket is writable
5659 it should dispatch more work. When the socket is readable it should
5660 read results and process them, matching them up to the next entry in
5661 its corresponding results queue. Based on available memory, results from the
5662 socket should be read frequently: there's no need to wait until the
5663 pipeline end to read the results. Pipelines should be scoped to logical
5664 units of work, usually (but not necessarily) one transaction per pipeline.
5665 There's no need to exit pipeline mode and re-enter it between pipelines,
5666 or to wait for one pipeline to finish before sending the next.
5667 </para>
5669 <para>
5670 An example using <function>select()</function> and a simple state
5671 machine to track sent and received work is in
5672 <filename>src/test/modules/libpq_pipeline/libpq_pipeline.c</filename>
5673 in the PostgreSQL source distribution.
5674 </para>
5675 </sect3>
5676 </sect2>
5678 <sect2 id="libpq-pipeline-functions">
5679 <title>Functions Associated with Pipeline Mode</title>
5681 <variablelist>
5683 <varlistentry id="libpq-PQpipelineStatus">
5684 <term><function>PQpipelineStatus</function><indexterm><primary>PQpipelineStatus</primary></indexterm></term>
5686 <listitem>
5687 <para>
5688 Returns the current pipeline mode status of the
5689 <application>libpq</application> connection.
5690 <synopsis>
5691 PGpipelineStatus PQpipelineStatus(const PGconn *conn);
5692 </synopsis>
5693 </para>
5695 <para>
5696 <function>PQpipelineStatus</function> can return one of the following values:
5698 <variablelist>
5699 <varlistentry>
5700 <term>
5701 <literal>PQ_PIPELINE_ON</literal>
5702 </term>
5703 <listitem>
5704 <para>
5705 The <application>libpq</application> connection is in
5706 pipeline mode.
5707 </para>
5708 </listitem>
5709 </varlistentry>
5711 <varlistentry>
5712 <term>
5713 <literal>PQ_PIPELINE_OFF</literal>
5714 </term>
5715 <listitem>
5716 <para>
5717 The <application>libpq</application> connection is
5718 <emphasis>not</emphasis> in pipeline mode.
5719 </para>
5720 </listitem>
5721 </varlistentry>
5723 <varlistentry>
5724 <term>
5725 <literal>PQ_PIPELINE_ABORTED</literal>
5726 </term>
5727 <listitem>
5728 <para>
5729 The <application>libpq</application> connection is in pipeline
5730 mode and an error occurred while processing the current pipeline.
5731 The aborted flag is cleared when <function>PQgetResult</function>
5732 returns a result of type <literal>PGRES_PIPELINE_SYNC</literal>.
5733 </para>
5734 </listitem>
5735 </varlistentry>
5737 </variablelist>
5738 </para>
5739 </listitem>
5740 </varlistentry>
5742 <varlistentry id="libpq-PQenterPipelineMode">
5743 <term><function>PQenterPipelineMode</function><indexterm><primary>PQenterPipelineMode</primary></indexterm></term>
5745 <listitem>
5746 <para>
5747 Causes a connection to enter pipeline mode if it is currently idle or
5748 already in pipeline mode.
5750 <synopsis>
5751 int PQenterPipelineMode(PGconn *conn);
5752 </synopsis>
5754 </para>
5755 <para>
5756 Returns 1 for success.
5757 Returns 0 and has no effect if the connection is not currently
5758 idle, i.e., it has a result ready, or it is waiting for more
5759 input from the server, etc.
5760 This function does not actually send anything to the server,
5761 it just changes the <application>libpq</application> connection
5762 state.
5763 </para>
5764 </listitem>
5765 </varlistentry>
5767 <varlistentry id="libpq-PQexitPipelineMode">
5768 <term><function>PQexitPipelineMode</function><indexterm><primary>PQexitPipelineMode</primary></indexterm></term>
5770 <listitem>
5771 <para>
5772 Causes a connection to exit pipeline mode if it is currently in pipeline mode
5773 with an empty queue and no pending results.
5774 <synopsis>
5775 int PQexitPipelineMode(PGconn *conn);
5776 </synopsis>
5777 </para>
5778 <para>
5779 Returns 1 for success. Returns 1 and takes no action if not in
5780 pipeline mode. If the current statement isn't finished processing,
5781 or <function>PQgetResult</function> has not been called to collect
5782 results from all previously sent query, returns 0 (in which case,
5783 use <xref linkend="libpq-PQerrorMessage"/> to get more information
5784 about the failure).
5785 </para>
5786 </listitem>
5787 </varlistentry>
5789 <varlistentry id="libpq-PQpipelineSync">
5790 <term><function>PQpipelineSync</function><indexterm><primary>PQpipelineSync</primary></indexterm></term>
5792 <listitem>
5793 <para>
5794 Marks a synchronization point in a pipeline by sending a
5795 <link linkend="protocol-flow-ext-query">sync message</link>
5796 and flushing the send buffer. This serves as
5797 the delimiter of an implicit transaction and an error recovery
5798 point; see <xref linkend="libpq-pipeline-errors"/>.
5800 <synopsis>
5801 int PQpipelineSync(PGconn *conn);
5802 </synopsis>
5803 </para>
5804 <para>
5805 Returns 1 for success. Returns 0 if the connection is not in
5806 pipeline mode or sending a
5807 <link linkend="protocol-flow-ext-query">sync message</link>
5808 failed.
5809 </para>
5810 </listitem>
5811 </varlistentry>
5813 <varlistentry id="libpq-PQsendFlushRequest">
5814 <term><function>PQsendFlushRequest</function><indexterm><primary>PQsendFlushRequest</primary></indexterm></term>
5816 <listitem>
5817 <para>
5818 Sends a request for the server to flush its output buffer.
5819 <synopsis>
5820 int PQsendFlushRequest(PGconn *conn);
5821 </synopsis>
5822 </para>
5824 <para>
5825 Returns 1 for success. Returns 0 on any failure.
5826 </para>
5827 <para>
5828 The server flushes its output buffer automatically as a result of
5829 <function>PQpipelineSync</function> being called, or
5830 on any request when not in pipeline mode; this function is useful
5831 to cause the server to flush its output buffer in pipeline mode
5832 without establishing a synchronization point.
5833 Note that the request is not itself flushed to the server automatically;
5834 use <function>PQflush</function> if necessary.
5835 </para>
5836 </listitem>
5837 </varlistentry>
5838 </variablelist>
5839 </sect2>
5841 <sect2 id="libpq-pipeline-tips">
5842 <title>When to Use Pipeline Mode</title>
5844 <para>
5845 Much like asynchronous query mode, there is no meaningful performance
5846 overhead when using pipeline mode. It increases client application complexity,
5847 and extra caution is required to prevent client/server deadlocks, but
5848 pipeline mode can offer considerable performance improvements, in exchange for
5849 increased memory usage from leaving state around longer.
5850 </para>
5852 <para>
5853 Pipeline mode is most useful when the server is distant, i.e., network latency
5854 (<quote>ping time</quote>) is high, and also when many small operations
5855 are being performed in rapid succession. There is usually less benefit
5856 in using pipelined commands when each query takes many multiples of the client/server
5857 round-trip time to execute. A 100-statement operation run on a server
5858 300 ms round-trip-time away would take 30 seconds in network latency alone
5859 without pipelining; with pipelining it may spend as little as 0.3 s waiting for
5860 results from the server.
5861 </para>
5863 <para>
5864 Use pipelined commands when your application does lots of small
5865 <literal>INSERT</literal>, <literal>UPDATE</literal> and
5866 <literal>DELETE</literal> operations that can't easily be transformed
5867 into operations on sets, or into a <literal>COPY</literal> operation.
5868 </para>
5870 <para>
5871 Pipeline mode is not useful when information from one operation is required by
5872 the client to produce the next operation. In such cases, the client
5873 would have to introduce a synchronization point and wait for a full client/server
5874 round-trip to get the results it needs. However, it's often possible to
5875 adjust the client design to exchange the required information server-side.
5876 Read-modify-write cycles are especially good candidates; for example:
5877 <programlisting>
5878 BEGIN;
5879 SELECT x FROM mytable WHERE id = 42 FOR UPDATE;
5880 -- result: x=2
5881 -- client adds 1 to x:
5882 UPDATE mytable SET x = 3 WHERE id = 42;
5883 COMMIT;
5884 </programlisting>
5885 could be much more efficiently done with:
5886 <programlisting>
5887 UPDATE mytable SET x = x + 1 WHERE id = 42;
5888 </programlisting>
5889 </para>
5891 <para>
5892 Pipelining is less useful, and more complex, when a single pipeline contains
5893 multiple transactions (see <xref linkend="libpq-pipeline-errors"/>).
5894 </para>
5895 </sect2>
5896 </sect1>
5898 <sect1 id="libpq-single-row-mode">
5899 <title>Retrieving Query Results Row-by-Row</title>
5901 <indexterm zone="libpq-single-row-mode">
5902 <primary>libpq</primary>
5903 <secondary>single-row mode</secondary>
5904 </indexterm>
5906 <para>
5907 Ordinarily, <application>libpq</application> collects an SQL command's
5908 entire result and returns it to the application as a single
5909 <structname>PGresult</structname>. This can be unworkable for commands
5910 that return a large number of rows. For such cases, applications can use
5911 <xref linkend="libpq-PQsendQuery"/> and <xref linkend="libpq-PQgetResult"/> in
5912 <firstterm>single-row mode</firstterm>. In this mode, the result row(s) are
5913 returned to the application one at a time, as they are received from the
5914 server.
5915 </para>
5917 <para>
5918 To enter single-row mode, call <xref linkend="libpq-PQsetSingleRowMode"/>
5919 immediately after a successful call of <xref linkend="libpq-PQsendQuery"/>
5920 (or a sibling function). This mode selection is effective only for the
5921 currently executing query. Then call <xref linkend="libpq-PQgetResult"/>
5922 repeatedly, until it returns null, as documented in <xref
5923 linkend="libpq-async"/>. If the query returns any rows, they are returned
5924 as individual <structname>PGresult</structname> objects, which look like
5925 normal query results except for having status code
5926 <literal>PGRES_SINGLE_TUPLE</literal> instead of
5927 <literal>PGRES_TUPLES_OK</literal>. After the last row, or immediately if
5928 the query returns zero rows, a zero-row object with status
5929 <literal>PGRES_TUPLES_OK</literal> is returned; this is the signal that no
5930 more rows will arrive. (But note that it is still necessary to continue
5931 calling <xref linkend="libpq-PQgetResult"/> until it returns null.) All of
5932 these <structname>PGresult</structname> objects will contain the same row
5933 description data (column names, types, etc.) that an ordinary
5934 <structname>PGresult</structname> object for the query would have.
5935 Each object should be freed with <xref linkend="libpq-PQclear"/> as usual.
5936 </para>
5938 <para>
5939 When using pipeline mode, single-row mode needs to be activated for each
5940 query in the pipeline before retrieving results for that query
5941 with <function>PQgetResult</function>.
5942 See <xref linkend="libpq-pipeline-mode"/> for more information.
5943 </para>
5945 <para>
5946 <variablelist>
5947 <varlistentry id="libpq-PQsetSingleRowMode">
5948 <term><function>PQsetSingleRowMode</function><indexterm><primary>PQsetSingleRowMode</primary></indexterm></term>
5950 <listitem>
5951 <para>
5952 Select single-row mode for the currently-executing query.
5954 <synopsis>
5955 int PQsetSingleRowMode(PGconn *conn);
5956 </synopsis>
5957 </para>
5959 <para>
5960 This function can only be called immediately after
5961 <xref linkend="libpq-PQsendQuery"/> or one of its sibling functions,
5962 before any other operation on the connection such as
5963 <xref linkend="libpq-PQconsumeInput"/> or
5964 <xref linkend="libpq-PQgetResult"/>. If called at the correct time,
5965 the function activates single-row mode for the current query and
5966 returns 1. Otherwise the mode stays unchanged and the function
5967 returns 0. In any case, the mode reverts to normal after
5968 completion of the current query.
5969 </para>
5970 </listitem>
5971 </varlistentry>
5972 </variablelist>
5973 </para>
5975 <caution>
5976 <para>
5977 While processing a query, the server may return some rows and then
5978 encounter an error, causing the query to be aborted. Ordinarily,
5979 <application>libpq</application> discards any such rows and reports only the
5980 error. But in single-row mode, those rows will have already been
5981 returned to the application. Hence, the application will see some
5982 <literal>PGRES_SINGLE_TUPLE</literal> <structname>PGresult</structname>
5983 objects followed by a <literal>PGRES_FATAL_ERROR</literal> object. For
5984 proper transactional behavior, the application must be designed to
5985 discard or undo whatever has been done with the previously-processed
5986 rows, if the query ultimately fails.
5987 </para>
5988 </caution>
5990 </sect1>
5992 <sect1 id="libpq-cancel">
5993 <title>Canceling Queries in Progress</title>
5995 <indexterm zone="libpq-cancel">
5996 <primary>canceling</primary>
5997 <secondary>SQL command</secondary>
5998 </indexterm>
6000 <para>
6001 A client application can request cancellation of a command that is
6002 still being processed by the server, using the functions described in
6003 this section.
6005 <variablelist>
6006 <varlistentry id="libpq-PQgetCancel">
6007 <term><function>PQgetCancel</function><indexterm><primary>PQgetCancel</primary></indexterm></term>
6009 <listitem>
6010 <para>
6011 Creates a data structure containing the information needed to cancel
6012 a command issued through a particular database connection.
6013 <synopsis>
6014 PGcancel *PQgetCancel(PGconn *conn);
6015 </synopsis>
6016 </para>
6018 <para>
6019 <xref linkend="libpq-PQgetCancel"/> creates a
6020 <structname>PGcancel</structname><indexterm><primary>PGcancel</primary></indexterm> object
6021 given a <structname>PGconn</structname> connection object. It will return
6022 <symbol>NULL</symbol> if the given <parameter>conn</parameter> is <symbol>NULL</symbol> or an invalid
6023 connection. The <structname>PGcancel</structname> object is an opaque
6024 structure that is not meant to be accessed directly by the
6025 application; it can only be passed to <xref linkend="libpq-PQcancel"/>
6026 or <xref linkend="libpq-PQfreeCancel"/>.
6027 </para>
6028 </listitem>
6029 </varlistentry>
6031 <varlistentry id="libpq-PQfreeCancel">
6032 <term><function>PQfreeCancel</function><indexterm><primary>PQfreeCancel</primary></indexterm></term>
6034 <listitem>
6035 <para>
6036 Frees a data structure created by <xref linkend="libpq-PQgetCancel"/>.
6037 <synopsis>
6038 void PQfreeCancel(PGcancel *cancel);
6039 </synopsis>
6040 </para>
6042 <para>
6043 <xref linkend="libpq-PQfreeCancel"/> frees a data object previously created
6044 by <xref linkend="libpq-PQgetCancel"/>.
6045 </para>
6046 </listitem>
6047 </varlistentry>
6049 <varlistentry id="libpq-PQcancel">
6050 <term><function>PQcancel</function><indexterm><primary>PQcancel</primary></indexterm></term>
6052 <listitem>
6053 <para>
6054 Requests that the server abandon processing of the current command.
6055 <synopsis>
6056 int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize);
6057 </synopsis>
6058 </para>
6060 <para>
6061 The return value is 1 if the cancel request was successfully
6062 dispatched and 0 if not. If not, <parameter>errbuf</parameter> is filled
6063 with an explanatory error message. <parameter>errbuf</parameter>
6064 must be a char array of size <parameter>errbufsize</parameter> (the
6065 recommended size is 256 bytes).
6066 </para>
6068 <para>
6069 Successful dispatch is no guarantee that the request will have
6070 any effect, however. If the cancellation is effective, the current
6071 command will terminate early and return an error result. If the
6072 cancellation fails (say, because the server was already done
6073 processing the command), then there will be no visible result at
6074 all.
6075 </para>
6077 <para>
6078 <xref linkend="libpq-PQcancel"/> can safely be invoked from a signal
6079 handler, if the <parameter>errbuf</parameter> is a local variable in the
6080 signal handler. The <structname>PGcancel</structname> object is read-only
6081 as far as <xref linkend="libpq-PQcancel"/> is concerned, so it can
6082 also be invoked from a thread that is separate from the one
6083 manipulating the <structname>PGconn</structname> object.
6084 </para>
6085 </listitem>
6086 </varlistentry>
6087 </variablelist>
6089 <variablelist>
6090 <varlistentry id="libpq-PQrequestCancel">
6091 <term><function>PQrequestCancel</function><indexterm><primary>PQrequestCancel</primary></indexterm></term>
6093 <listitem>
6094 <para>
6095 <xref linkend="libpq-PQrequestCancel"/> is a deprecated variant of
6096 <xref linkend="libpq-PQcancel"/>.
6097 <synopsis>
6098 int PQrequestCancel(PGconn *conn);
6099 </synopsis>
6100 </para>
6102 <para>
6103 Requests that the server abandon processing of the current
6104 command. It operates directly on the
6105 <structname>PGconn</structname> object, and in case of failure stores the
6106 error message in the <structname>PGconn</structname> object (whence it can
6107 be retrieved by <xref linkend="libpq-PQerrorMessage"/>). Although
6108 the functionality is the same, this approach is not safe within
6109 multiple-thread programs or signal handlers, since it is possible
6110 that overwriting the <structname>PGconn</structname>'s error message will
6111 mess up the operation currently in progress on the connection.
6112 </para>
6113 </listitem>
6114 </varlistentry>
6115 </variablelist>
6116 </para>
6118 </sect1>
6120 <sect1 id="libpq-fastpath">
6121 <title>The Fast-Path Interface</title>
6123 <indexterm zone="libpq-fastpath">
6124 <primary>fast path</primary>
6125 </indexterm>
6127 <para>
6128 <productname>PostgreSQL</productname> provides a fast-path interface
6129 to send simple function calls to the server.
6130 </para>
6132 <tip>
6133 <para>
6134 This interface is somewhat obsolete, as one can achieve similar
6135 performance and greater functionality by setting up a prepared
6136 statement to define the function call. Then, executing the statement
6137 with binary transmission of parameters and results substitutes for a
6138 fast-path function call.
6139 </para>
6140 </tip>
6142 <para>
6143 The function <function id="libpq-PQfn">PQfn</function><indexterm><primary>PQfn</primary></indexterm>
6144 requests execution of a server function via the fast-path interface:
6145 <synopsis>
6146 PGresult *PQfn(PGconn *conn,
6147 int fnid,
6148 int *result_buf,
6149 int *result_len,
6150 int result_is_int,
6151 const PQArgBlock *args,
6152 int nargs);
6154 typedef struct
6156 int len;
6157 int isint;
6158 union
6160 int *ptr;
6161 int integer;
6162 } u;
6163 } PQArgBlock;
6164 </synopsis>
6165 </para>
6167 <para>
6168 The <parameter>fnid</parameter> argument is the OID of the function to be
6169 executed. <parameter>args</parameter> and <parameter>nargs</parameter> define the
6170 parameters to be passed to the function; they must match the declared
6171 function argument list. When the <parameter>isint</parameter> field of a
6172 parameter structure is true, the <parameter>u.integer</parameter> value is sent
6173 to the server as an integer of the indicated length (this must be
6174 2 or 4 bytes); proper byte-swapping occurs. When <parameter>isint</parameter>
6175 is false, the indicated number of bytes at <parameter>*u.ptr</parameter> are
6176 sent with no processing; the data must be in the format expected by
6177 the server for binary transmission of the function's argument data
6178 type. (The declaration of <parameter>u.ptr</parameter> as being of
6179 type <type>int *</type> is historical; it would be better to consider
6180 it <type>void *</type>.)
6181 <parameter>result_buf</parameter> points to the buffer in which to place
6182 the function's return value. The caller must have allocated sufficient
6183 space to store the return value. (There is no check!) The actual result
6184 length in bytes will be returned in the integer pointed to by
6185 <parameter>result_len</parameter>. If a 2- or 4-byte integer result
6186 is expected, set <parameter>result_is_int</parameter> to 1, otherwise
6187 set it to 0. Setting <parameter>result_is_int</parameter> to 1 causes
6188 <application>libpq</application> to byte-swap the value if necessary, so that it
6189 is delivered as a proper <type>int</type> value for the client machine;
6190 note that a 4-byte integer is delivered into <parameter>*result_buf</parameter>
6191 for either allowed result size.
6192 When <parameter>result_is_int</parameter> is 0, the binary-format byte string
6193 sent by the server is returned unmodified. (In this case it's better
6194 to consider <parameter>result_buf</parameter> as being of
6195 type <type>void *</type>.)
6196 </para>
6198 <para>
6199 <function>PQfn</function> always returns a valid
6200 <structname>PGresult</structname> pointer, with
6201 status <literal>PGRES_COMMAND_OK</literal> for success
6202 or <literal>PGRES_FATAL_ERROR</literal> if some problem was encountered.
6203 The result status should be
6204 checked before the result is used. The caller is responsible for
6205 freeing the <structname>PGresult</structname> with
6206 <xref linkend="libpq-PQclear"/> when it is no longer needed.
6207 </para>
6209 <para>
6210 To pass a NULL argument to the function, set
6211 the <parameter>len</parameter> field of that parameter structure
6212 to <literal>-1</literal>; the <parameter>isint</parameter>
6213 and <parameter>u</parameter> fields are then irrelevant.
6214 </para>
6216 <para>
6217 If the function returns NULL, <parameter>*result_len</parameter> is set
6218 to <literal>-1</literal>, and <parameter>*result_buf</parameter> is not
6219 modified.
6220 </para>
6222 <para>
6223 Note that it is not possible to handle set-valued results when using
6224 this interface. Also, the function must be a plain function, not an
6225 aggregate, window function, or procedure.
6226 </para>
6228 </sect1>
6230 <sect1 id="libpq-notify">
6231 <title>Asynchronous Notification</title>
6233 <indexterm zone="libpq-notify">
6234 <primary>NOTIFY</primary>
6235 <secondary>in libpq</secondary>
6236 </indexterm>
6238 <para>
6239 <productname>PostgreSQL</productname> offers asynchronous notification
6240 via the <command>LISTEN</command> and <command>NOTIFY</command>
6241 commands. A client session registers its interest in a particular
6242 notification channel with the <command>LISTEN</command> command (and
6243 can stop listening with the <command>UNLISTEN</command> command). All
6244 sessions listening on a particular channel will be notified
6245 asynchronously when a <command>NOTIFY</command> command with that
6246 channel name is executed by any session. A <quote>payload</quote> string can
6247 be passed to communicate additional data to the listeners.
6248 </para>
6250 <para>
6251 <application>libpq</application> applications submit
6252 <command>LISTEN</command>, <command>UNLISTEN</command>,
6253 and <command>NOTIFY</command> commands as
6254 ordinary SQL commands. The arrival of <command>NOTIFY</command>
6255 messages can subsequently be detected by calling
6256 <function id="libpq-PQnotifies">PQnotifies</function>.<indexterm><primary>PQnotifies</primary></indexterm>
6257 </para>
6259 <para>
6260 The function <function>PQnotifies</function> returns the next notification
6261 from a list of unhandled notification messages received from the server.
6262 It returns a null pointer if there are no pending notifications. Once a
6263 notification is returned from <function>PQnotifies</function>, it is considered
6264 handled and will be removed from the list of notifications.
6266 <synopsis>
6267 PGnotify *PQnotifies(PGconn *conn);
6269 typedef struct pgNotify
6271 char *relname; /* notification channel name */
6272 int be_pid; /* process ID of notifying server process */
6273 char *extra; /* notification payload string */
6274 } PGnotify;
6275 </synopsis>
6277 After processing a <structname>PGnotify</structname> object returned
6278 by <function>PQnotifies</function>, be sure to free it with
6279 <xref linkend="libpq-PQfreemem"/>. It is sufficient to free the
6280 <structname>PGnotify</structname> pointer; the
6281 <structfield>relname</structfield> and <structfield>extra</structfield>
6282 fields do not represent separate allocations. (The names of these fields
6283 are historical; in particular, channel names need not have anything to
6284 do with relation names.)
6285 </para>
6287 <para>
6288 <xref linkend="libpq-example-2"/> gives a sample program that illustrates
6289 the use of asynchronous notification.
6290 </para>
6292 <para>
6293 <function>PQnotifies</function> does not actually read data from the
6294 server; it just returns messages previously absorbed by another
6295 <application>libpq</application> function. In ancient releases of
6296 <application>libpq</application>, the only way to ensure timely receipt
6297 of <command>NOTIFY</command> messages was to constantly submit commands, even
6298 empty ones, and then check <function>PQnotifies</function> after each
6299 <xref linkend="libpq-PQexec"/>. While this still works, it is deprecated
6300 as a waste of processing power.
6301 </para>
6303 <para>
6304 A better way to check for <command>NOTIFY</command> messages when you have no
6305 useful commands to execute is to call
6306 <xref linkend="libpq-PQconsumeInput"/>, then check
6307 <function>PQnotifies</function>. You can use
6308 <function>select()</function> to wait for data to arrive from the
6309 server, thereby using no <acronym>CPU</acronym> power unless there is
6310 something to do. (See <xref linkend="libpq-PQsocket"/> to obtain the file
6311 descriptor number to use with <function>select()</function>.) Note that
6312 this will work OK whether you submit commands with
6313 <xref linkend="libpq-PQsendQuery"/>/<xref linkend="libpq-PQgetResult"/> or
6314 simply use <xref linkend="libpq-PQexec"/>. You should, however, remember
6315 to check <function>PQnotifies</function> after each
6316 <xref linkend="libpq-PQgetResult"/> or <xref linkend="libpq-PQexec"/>, to
6317 see if any notifications came in during the processing of the command.
6318 </para>
6320 </sect1>
6322 <sect1 id="libpq-copy">
6323 <title>Functions Associated with the <command>COPY</command> Command</title>
6325 <indexterm zone="libpq-copy">
6326 <primary>COPY</primary>
6327 <secondary>with libpq</secondary>
6328 </indexterm>
6330 <para>
6331 The <command>COPY</command> command in
6332 <productname>PostgreSQL</productname> has options to read from or write
6333 to the network connection used by <application>libpq</application>.
6334 The functions described in this section allow applications to take
6335 advantage of this capability by supplying or consuming copied data.
6336 </para>
6338 <para>
6339 The overall process is that the application first issues the SQL
6340 <command>COPY</command> command via <xref linkend="libpq-PQexec"/> or one
6341 of the equivalent functions. The response to this (if there is no
6342 error in the command) will be a <structname>PGresult</structname> object bearing
6343 a status code of <literal>PGRES_COPY_OUT</literal> or
6344 <literal>PGRES_COPY_IN</literal> (depending on the specified copy
6345 direction). The application should then use the functions of this
6346 section to receive or transmit data rows. When the data transfer is
6347 complete, another <structname>PGresult</structname> object is returned to indicate
6348 success or failure of the transfer. Its status will be
6349 <literal>PGRES_COMMAND_OK</literal> for success or
6350 <literal>PGRES_FATAL_ERROR</literal> if some problem was encountered.
6351 At this point further SQL commands can be issued via
6352 <xref linkend="libpq-PQexec"/>. (It is not possible to execute other SQL
6353 commands using the same connection while the <command>COPY</command>
6354 operation is in progress.)
6355 </para>
6357 <para>
6358 If a <command>COPY</command> command is issued via
6359 <xref linkend="libpq-PQexec"/> in a string that could contain additional
6360 commands, the application must continue fetching results via
6361 <xref linkend="libpq-PQgetResult"/> after completing the <command>COPY</command>
6362 sequence. Only when <xref linkend="libpq-PQgetResult"/> returns
6363 <symbol>NULL</symbol> is it certain that the <xref linkend="libpq-PQexec"/>
6364 command string is done and it is safe to issue more commands.
6365 </para>
6367 <para>
6368 The functions of this section should be executed only after obtaining
6369 a result status of <literal>PGRES_COPY_OUT</literal> or
6370 <literal>PGRES_COPY_IN</literal> from <xref linkend="libpq-PQexec"/> or
6371 <xref linkend="libpq-PQgetResult"/>.
6372 </para>
6374 <para>
6375 A <structname>PGresult</structname> object bearing one of these status values
6376 carries some additional data about the <command>COPY</command> operation
6377 that is starting. This additional data is available using functions
6378 that are also used in connection with query results:
6380 <variablelist>
6381 <varlistentry id="libpq-PQnfields-1">
6382 <term><function>PQnfields</function><indexterm
6383 ><primary>PQnfields</primary><secondary>with COPY</secondary></indexterm></term>
6385 <listitem>
6386 <para>
6387 Returns the number of columns (fields) to be copied.
6388 </para>
6389 </listitem>
6390 </varlistentry>
6392 <varlistentry id="libpq-PQbinaryTuples-1">
6393 <term><function>PQbinaryTuples</function><indexterm
6394 ><primary>PQbinaryTuples</primary><secondary>with COPY</secondary></indexterm></term>
6396 <listitem>
6397 <para>
6398 0 indicates the overall copy format is textual (rows separated by
6399 newlines, columns separated by separator characters, etc.). 1
6400 indicates the overall copy format is binary. See <xref
6401 linkend="sql-copy"/> for more information.
6402 </para>
6403 </listitem>
6404 </varlistentry>
6406 <varlistentry id="libpq-PQfformat-1">
6407 <term><function>PQfformat</function><indexterm
6408 ><primary>PQfformat</primary><secondary>with COPY</secondary></indexterm></term>
6410 <listitem>
6411 <para>
6412 Returns the format code (0 for text, 1 for binary) associated with
6413 each column of the copy operation. The per-column format codes
6414 will always be zero when the overall copy format is textual, but
6415 the binary format can support both text and binary columns.
6416 (However, as of the current implementation of <command>COPY</command>,
6417 only binary columns appear in a binary copy; so the per-column
6418 formats always match the overall format at present.)
6419 </para>
6420 </listitem>
6421 </varlistentry>
6422 </variablelist>
6423 </para>
6425 <sect2 id="libpq-copy-send">
6426 <title>Functions for Sending <command>COPY</command> Data</title>
6428 <para>
6429 These functions are used to send data during <literal>COPY FROM
6430 STDIN</literal>. They will fail if called when the connection is not in
6431 <literal>COPY_IN</literal> state.
6432 </para>
6434 <variablelist>
6435 <varlistentry id="libpq-PQputCopyData">
6436 <term><function>PQputCopyData</function><indexterm><primary>PQputCopyData</primary></indexterm></term>
6438 <listitem>
6439 <para>
6440 Sends data to the server during <literal>COPY_IN</literal> state.
6441 <synopsis>
6442 int PQputCopyData(PGconn *conn,
6443 const char *buffer,
6444 int nbytes);
6445 </synopsis>
6446 </para>
6448 <para>
6449 Transmits the <command>COPY</command> data in the specified
6450 <parameter>buffer</parameter>, of length <parameter>nbytes</parameter>, to the server.
6451 The result is 1 if the data was queued, zero if it was not queued
6452 because of full buffers (this will only happen in nonblocking mode),
6453 or -1 if an error occurred.
6454 (Use <xref linkend="libpq-PQerrorMessage"/> to retrieve details if
6455 the return value is -1. If the value is zero, wait for write-ready
6456 and try again.)
6457 </para>
6459 <para>
6460 The application can divide the <command>COPY</command> data stream
6461 into buffer loads of any convenient size. Buffer-load boundaries
6462 have no semantic significance when sending. The contents of the
6463 data stream must match the data format expected by the
6464 <command>COPY</command> command; see <xref linkend="sql-copy"/> for details.
6465 </para>
6466 </listitem>
6467 </varlistentry>
6469 <varlistentry id="libpq-PQputCopyEnd">
6470 <term><function>PQputCopyEnd</function><indexterm><primary>PQputCopyEnd</primary></indexterm></term>
6472 <listitem>
6473 <para>
6474 Sends end-of-data indication to the server during <literal>COPY_IN</literal> state.
6475 <synopsis>
6476 int PQputCopyEnd(PGconn *conn,
6477 const char *errormsg);
6478 </synopsis>
6479 </para>
6481 <para>
6482 Ends the <literal>COPY_IN</literal> operation successfully if
6483 <parameter>errormsg</parameter> is <symbol>NULL</symbol>. If
6484 <parameter>errormsg</parameter> is not <symbol>NULL</symbol> then the
6485 <command>COPY</command> is forced to fail, with the string pointed to by
6486 <parameter>errormsg</parameter> used as the error message. (One should not
6487 assume that this exact error message will come back from the server,
6488 however, as the server might have already failed the
6489 <command>COPY</command> for its own reasons.)
6490 </para>
6492 <para>
6493 The result is 1 if the termination message was sent; or in
6494 nonblocking mode, this may only indicate that the termination
6495 message was successfully queued. (In nonblocking mode, to be
6496 certain that the data has been sent, you should next wait for
6497 write-ready and call <xref linkend="libpq-PQflush"/>, repeating until it
6498 returns zero.) Zero indicates that the function could not queue
6499 the termination message because of full buffers; this will only
6500 happen in nonblocking mode. (In this case, wait for
6501 write-ready and try the <xref linkend="libpq-PQputCopyEnd"/> call
6502 again.) If a hard error occurs, -1 is returned; you can use
6503 <xref linkend="libpq-PQerrorMessage"/> to retrieve details.
6504 </para>
6506 <para>
6507 After successfully calling <xref linkend="libpq-PQputCopyEnd"/>, call
6508 <xref linkend="libpq-PQgetResult"/> to obtain the final result status of the
6509 <command>COPY</command> command. One can wait for this result to be
6510 available in the usual way. Then return to normal operation.
6511 </para>
6512 </listitem>
6513 </varlistentry>
6514 </variablelist>
6516 </sect2>
6518 <sect2 id="libpq-copy-receive">
6519 <title>Functions for Receiving <command>COPY</command> Data</title>
6521 <para>
6522 These functions are used to receive data during <literal>COPY TO
6523 STDOUT</literal>. They will fail if called when the connection is not in
6524 <literal>COPY_OUT</literal> state.
6525 </para>
6527 <variablelist>
6528 <varlistentry id="libpq-PQgetCopyData">
6529 <term><function>PQgetCopyData</function><indexterm><primary>PQgetCopyData</primary></indexterm></term>
6531 <listitem>
6532 <para>
6533 Receives data from the server during <literal>COPY_OUT</literal> state.
6534 <synopsis>
6535 int PQgetCopyData(PGconn *conn,
6536 char **buffer,
6537 int async);
6538 </synopsis>
6539 </para>
6541 <para>
6542 Attempts to obtain another row of data from the server during a
6543 <command>COPY</command>. Data is always returned one data row at
6544 a time; if only a partial row is available, it is not returned.
6545 Successful return of a data row involves allocating a chunk of
6546 memory to hold the data. The <parameter>buffer</parameter> parameter must
6547 be non-<symbol>NULL</symbol>. <parameter>*buffer</parameter> is set to
6548 point to the allocated memory, or to <symbol>NULL</symbol> in cases
6549 where no buffer is returned. A non-<symbol>NULL</symbol> result
6550 buffer should be freed using <xref linkend="libpq-PQfreemem"/> when no longer
6551 needed.
6552 </para>
6554 <para>
6555 When a row is successfully returned, the return value is the number
6556 of data bytes in the row (this will always be greater than zero).
6557 The returned string is always null-terminated, though this is
6558 probably only useful for textual <command>COPY</command>. A result
6559 of zero indicates that the <command>COPY</command> is still in
6560 progress, but no row is yet available (this is only possible when
6561 <parameter>async</parameter> is true). A result of -1 indicates that the
6562 <command>COPY</command> is done. A result of -2 indicates that an
6563 error occurred (consult <xref linkend="libpq-PQerrorMessage"/> for the reason).
6564 </para>
6566 <para>
6567 When <parameter>async</parameter> is true (not zero),
6568 <xref linkend="libpq-PQgetCopyData"/> will not block waiting for input; it
6569 will return zero if the <command>COPY</command> is still in progress
6570 but no complete row is available. (In this case wait for read-ready
6571 and then call <xref linkend="libpq-PQconsumeInput"/> before calling
6572 <xref linkend="libpq-PQgetCopyData"/> again.) When <parameter>async</parameter> is
6573 false (zero), <xref linkend="libpq-PQgetCopyData"/> will block until data is
6574 available or the operation completes.
6575 </para>
6577 <para>
6578 After <xref linkend="libpq-PQgetCopyData"/> returns -1, call
6579 <xref linkend="libpq-PQgetResult"/> to obtain the final result status of the
6580 <command>COPY</command> command. One can wait for this result to be
6581 available in the usual way. Then return to normal operation.
6582 </para>
6583 </listitem>
6584 </varlistentry>
6585 </variablelist>
6587 </sect2>
6589 <sect2 id="libpq-copy-deprecated">
6590 <title>Obsolete Functions for <command>COPY</command></title>
6592 <para>
6593 These functions represent older methods of handling <command>COPY</command>.
6594 Although they still work, they are deprecated due to poor error handling,
6595 inconvenient methods of detecting end-of-data, and lack of support for binary
6596 or nonblocking transfers.
6597 </para>
6599 <variablelist>
6600 <varlistentry id="libpq-PQgetline">
6601 <term><function>PQgetline</function><indexterm><primary>PQgetline</primary></indexterm></term>
6603 <listitem>
6604 <para>
6605 Reads a newline-terminated line of characters (transmitted
6606 by the server) into a buffer string of size <parameter>length</parameter>.
6607 <synopsis>
6608 int PQgetline(PGconn *conn,
6609 char *buffer,
6610 int length);
6611 </synopsis>
6612 </para>
6614 <para>
6615 This function copies up to <parameter>length</parameter>-1 characters into
6616 the buffer and converts the terminating newline into a zero byte.
6617 <xref linkend="libpq-PQgetline"/> returns <symbol>EOF</symbol> at the
6618 end of input, 0 if the entire line has been read, and 1 if the
6619 buffer is full but the terminating newline has not yet been read.
6620 </para>
6621 <para>
6622 Note that the application must check to see if a new line consists
6623 of the two characters <literal>\.</literal>, which indicates
6624 that the server has finished sending the results of the
6625 <command>COPY</command> command. If the application might receive
6626 lines that are more than <parameter>length</parameter>-1 characters long,
6627 care is needed to be sure it recognizes the <literal>\.</literal>
6628 line correctly (and does not, for example, mistake the end of a
6629 long data line for a terminator line).
6630 </para>
6631 </listitem>
6632 </varlistentry>
6634 <varlistentry id="libpq-PQgetlineAsync">
6635 <term><function>PQgetlineAsync</function><indexterm><primary>PQgetlineAsync</primary></indexterm></term>
6637 <listitem>
6638 <para>
6639 Reads a row of <command>COPY</command> data (transmitted by the
6640 server) into a buffer without blocking.
6641 <synopsis>
6642 int PQgetlineAsync(PGconn *conn,
6643 char *buffer,
6644 int bufsize);
6645 </synopsis>
6646 </para>
6648 <para>
6649 This function is similar to <xref linkend="libpq-PQgetline"/>, but it can be used
6650 by applications
6651 that must read <command>COPY</command> data asynchronously, that is, without blocking.
6652 Having issued the <command>COPY</command> command and gotten a <literal>PGRES_COPY_OUT</literal>
6653 response, the
6654 application should call <xref linkend="libpq-PQconsumeInput"/> and
6655 <xref linkend="libpq-PQgetlineAsync"/> until the
6656 end-of-data signal is detected.
6657 </para>
6658 <para>
6659 Unlike <xref linkend="libpq-PQgetline"/>, this function takes
6660 responsibility for detecting end-of-data.
6661 </para>
6663 <para>
6664 On each call, <xref linkend="libpq-PQgetlineAsync"/> will return data if a
6665 complete data row is available in <application>libpq</application>'s input buffer.
6666 Otherwise, no data is returned until the rest of the row arrives.
6667 The function returns -1 if the end-of-copy-data marker has been recognized,
6668 or 0 if no data is available, or a positive number giving the number of
6669 bytes of data returned. If -1 is returned, the caller must next call
6670 <xref linkend="libpq-PQendcopy"/>, and then return to normal processing.
6671 </para>
6673 <para>
6674 The data returned will not extend beyond a data-row boundary. If possible
6675 a whole row will be returned at one time. But if the buffer offered by
6676 the caller is too small to hold a row sent by the server, then a partial
6677 data row will be returned. With textual data this can be detected by testing
6678 whether the last returned byte is <literal>\n</literal> or not. (In a binary
6679 <command>COPY</command>, actual parsing of the <command>COPY</command> data format will be needed to make the
6680 equivalent determination.)
6681 The returned string is not null-terminated. (If you want to add a
6682 terminating null, be sure to pass a <parameter>bufsize</parameter> one smaller
6683 than the room actually available.)
6684 </para>
6685 </listitem>
6686 </varlistentry>
6688 <varlistentry id="libpq-PQputline">
6689 <term><function>PQputline</function><indexterm><primary>PQputline</primary></indexterm></term>
6691 <listitem>
6692 <para>
6693 Sends a null-terminated string to the server. Returns 0 if
6694 OK and <symbol>EOF</symbol> if unable to send the string.
6695 <synopsis>
6696 int PQputline(PGconn *conn,
6697 const char *string);
6698 </synopsis>
6699 </para>
6701 <para>
6702 The <command>COPY</command> data stream sent by a series of calls
6703 to <xref linkend="libpq-PQputline"/> has the same format as that
6704 returned by <xref linkend="libpq-PQgetlineAsync"/>, except that
6705 applications are not obliged to send exactly one data row per
6706 <xref linkend="libpq-PQputline"/> call; it is okay to send a partial
6707 line or multiple lines per call.
6708 </para>
6710 <note>
6711 <para>
6712 Before <productname>PostgreSQL</productname> protocol 3.0, it was necessary
6713 for the application to explicitly send the two characters
6714 <literal>\.</literal> as a final line to indicate to the server that it had
6715 finished sending <command>COPY</command> data. While this still works, it is deprecated and the
6716 special meaning of <literal>\.</literal> can be expected to be removed in a
6717 future release. It is sufficient to call <xref linkend="libpq-PQendcopy"/> after
6718 having sent the actual data.
6719 </para>
6720 </note>
6721 </listitem>
6722 </varlistentry>
6724 <varlistentry id="libpq-PQputnbytes">
6725 <term><function>PQputnbytes</function><indexterm><primary>PQputnbytes</primary></indexterm></term>
6727 <listitem>
6728 <para>
6729 Sends a non-null-terminated string to the server. Returns
6730 0 if OK and <symbol>EOF</symbol> if unable to send the string.
6731 <synopsis>
6732 int PQputnbytes(PGconn *conn,
6733 const char *buffer,
6734 int nbytes);
6735 </synopsis>
6736 </para>
6738 <para>
6739 This is exactly like <xref linkend="libpq-PQputline"/>, except that the data
6740 buffer need not be null-terminated since the number of bytes to send is
6741 specified directly. Use this procedure when sending binary data.
6742 </para>
6743 </listitem>
6744 </varlistentry>
6746 <varlistentry id="libpq-PQendcopy">
6747 <term><function>PQendcopy</function><indexterm><primary>PQendcopy</primary></indexterm></term>
6749 <listitem>
6750 <para>
6751 Synchronizes with the server.
6752 <synopsis>
6753 int PQendcopy(PGconn *conn);
6754 </synopsis>
6755 This function waits until the server has finished the copying.
6756 It should either be issued when the last string has been sent
6757 to the server using <xref linkend="libpq-PQputline"/> or when the
6758 last string has been received from the server using
6759 <function>PQgetline</function>. It must be issued or the server
6760 will get <quote>out of sync</quote> with the client. Upon return
6761 from this function, the server is ready to receive the next SQL
6762 command. The return value is 0 on successful completion,
6763 nonzero otherwise. (Use <xref linkend="libpq-PQerrorMessage"/> to
6764 retrieve details if the return value is nonzero.)
6765 </para>
6767 <para>
6768 When using <xref linkend="libpq-PQgetResult"/>, the application should
6769 respond to a <literal>PGRES_COPY_OUT</literal> result by executing
6770 <xref linkend="libpq-PQgetline"/> repeatedly, followed by
6771 <xref linkend="libpq-PQendcopy"/> after the terminator line is seen.
6772 It should then return to the <xref linkend="libpq-PQgetResult"/> loop
6773 until <xref linkend="libpq-PQgetResult"/> returns a null pointer.
6774 Similarly a <literal>PGRES_COPY_IN</literal> result is processed
6775 by a series of <xref linkend="libpq-PQputline"/> calls followed by
6776 <xref linkend="libpq-PQendcopy"/>, then return to the
6777 <xref linkend="libpq-PQgetResult"/> loop. This arrangement will
6778 ensure that a <command>COPY</command> command embedded in a series
6779 of <acronym>SQL</acronym> commands will be executed correctly.
6780 </para>
6782 <para>
6783 Older applications are likely to submit a <command>COPY</command>
6784 via <xref linkend="libpq-PQexec"/> and assume that the transaction
6785 is done after <xref linkend="libpq-PQendcopy"/>. This will work
6786 correctly only if the <command>COPY</command> is the only
6787 <acronym>SQL</acronym> command in the command string.
6788 </para>
6789 </listitem>
6790 </varlistentry>
6791 </variablelist>
6793 </sect2>
6795 </sect1>
6797 <sect1 id="libpq-control">
6798 <title>Control Functions</title>
6800 <para>
6801 These functions control miscellaneous details of <application>libpq</application>'s
6802 behavior.
6803 </para>
6805 <variablelist>
6806 <varlistentry id="libpq-PQclientEncoding">
6807 <term><function>PQclientEncoding</function><indexterm><primary>PQclientEncoding</primary></indexterm></term>
6809 <listitem>
6810 <para>
6811 Returns the client encoding.
6812 <synopsis>
6813 int PQclientEncoding(const PGconn *<replaceable>conn</replaceable>);
6814 </synopsis>
6816 Note that it returns the encoding ID, not a symbolic string
6817 such as <literal>EUC_JP</literal>. If unsuccessful, it returns -1.
6818 To convert an encoding ID to an encoding name, you
6819 can use:
6821 <synopsis>
6822 char *pg_encoding_to_char(int <replaceable>encoding_id</replaceable>);
6823 </synopsis>
6824 </para>
6825 </listitem>
6826 </varlistentry>
6828 <varlistentry id="libpq-PQsetClientEncoding">
6829 <term><function>PQsetClientEncoding</function><indexterm><primary>PQsetClientEncoding</primary></indexterm></term>
6831 <listitem>
6832 <para>
6833 Sets the client encoding.
6834 <synopsis>
6835 int PQsetClientEncoding(PGconn *<replaceable>conn</replaceable>, const char *<replaceable>encoding</replaceable>);
6836 </synopsis>
6838 <replaceable>conn</replaceable> is a connection to the server,
6839 and <replaceable>encoding</replaceable> is the encoding you want to
6840 use. If the function successfully sets the encoding, it returns 0,
6841 otherwise -1. The current encoding for this connection can be
6842 determined by using <xref linkend="libpq-PQclientEncoding"/>.
6843 </para>
6844 </listitem>
6845 </varlistentry>
6847 <varlistentry id="libpq-PQsetErrorVerbosity">
6848 <term><function>PQsetErrorVerbosity</function><indexterm><primary>PQsetErrorVerbosity</primary></indexterm></term>
6850 <listitem>
6851 <para>
6852 Determines the verbosity of messages returned by
6853 <xref linkend="libpq-PQerrorMessage"/> and <xref linkend="libpq-PQresultErrorMessage"/>.
6854 <synopsis>
6855 typedef enum
6857 PQERRORS_TERSE,
6858 PQERRORS_DEFAULT,
6859 PQERRORS_VERBOSE,
6860 PQERRORS_SQLSTATE
6861 } PGVerbosity;
6863 PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity);
6864 </synopsis>
6866 <xref linkend="libpq-PQsetErrorVerbosity"/> sets the verbosity mode,
6867 returning the connection's previous setting.
6868 In <firstterm>TERSE</firstterm> mode, returned messages include
6869 severity, primary text, and position only; this will normally fit on a
6870 single line. The <firstterm>DEFAULT</firstterm> mode produces messages
6871 that include the above plus any detail, hint, or context fields (these
6872 might span multiple lines). The <firstterm>VERBOSE</firstterm> mode
6873 includes all available fields. The <firstterm>SQLSTATE</firstterm>
6874 mode includes only the error severity and the <symbol>SQLSTATE</symbol>
6875 error code, if one is available (if not, the output is like
6876 <firstterm>TERSE</firstterm> mode).
6877 </para>
6879 <para>
6880 Changing the verbosity setting does not affect the messages available
6881 from already-existing <structname>PGresult</structname> objects, only
6882 subsequently-created ones.
6883 (But see <xref linkend="libpq-PQresultVerboseErrorMessage"/> if you
6884 want to print a previous error with a different verbosity.)
6885 </para>
6886 </listitem>
6887 </varlistentry>
6889 <varlistentry id="libpq-PQsetErrorContextVisibility">
6890 <term><function>PQsetErrorContextVisibility</function><indexterm><primary>PQsetErrorContextVisibility</primary></indexterm></term>
6892 <listitem>
6893 <para>
6894 Determines the handling of <literal>CONTEXT</literal> fields in messages
6895 returned by <xref linkend="libpq-PQerrorMessage"/>
6896 and <xref linkend="libpq-PQresultErrorMessage"/>.
6897 <synopsis>
6898 typedef enum
6900 PQSHOW_CONTEXT_NEVER,
6901 PQSHOW_CONTEXT_ERRORS,
6902 PQSHOW_CONTEXT_ALWAYS
6903 } PGContextVisibility;
6905 PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context);
6906 </synopsis>
6908 <xref linkend="libpq-PQsetErrorContextVisibility"/> sets the context display mode,
6909 returning the connection's previous setting. This mode controls
6910 whether the <literal>CONTEXT</literal> field is included in messages.
6911 The <firstterm>NEVER</firstterm> mode
6912 never includes <literal>CONTEXT</literal>, while <firstterm>ALWAYS</firstterm> always
6913 includes it if available. In <firstterm>ERRORS</firstterm> mode (the
6914 default), <literal>CONTEXT</literal> fields are included only in error
6915 messages, not in notices and warnings.
6916 (However, if the verbosity setting is <firstterm>TERSE</firstterm>
6917 or <firstterm>SQLSTATE</firstterm>, <literal>CONTEXT</literal> fields
6918 are omitted regardless of the context display mode.)
6919 </para>
6921 <para>
6922 Changing this mode does not
6923 affect the messages available from
6924 already-existing <structname>PGresult</structname> objects, only
6925 subsequently-created ones.
6926 (But see <xref linkend="libpq-PQresultVerboseErrorMessage"/> if you
6927 want to print a previous error with a different display mode.)
6928 </para>
6929 </listitem>
6930 </varlistentry>
6932 <varlistentry id="libpq-PQtrace">
6933 <term><function>PQtrace</function><indexterm><primary>PQtrace</primary></indexterm></term>
6935 <listitem>
6936 <para>
6937 Enables tracing of the client/server communication to a debugging file
6938 stream.
6939 <synopsis>
6940 void PQtrace(PGconn *conn, FILE *stream);
6941 </synopsis>
6942 </para>
6944 <para>
6945 Each line consists of: an optional timestamp, a direction indicator
6946 (<literal>F</literal> for messages from client to server
6947 or <literal>B</literal> for messages from server to client),
6948 message length, message type, and message contents.
6949 Non-message contents fields (timestamp, direction, length and message type)
6950 are separated by a tab. Message contents are separated by a space.
6951 Protocol strings are enclosed in double quotes, while strings used as data
6952 values are enclosed in single quotes. Non-printable chars are printed as
6953 hexadecimal escapes.
6954 Further message-type-specific detail can be found in
6955 <xref linkend="protocol-message-formats"/>.
6956 </para>
6958 <note>
6959 <para>
6960 On Windows, if the <application>libpq</application> library and an application are
6961 compiled with different flags, this function call will crash the
6962 application because the internal representation of the <literal>FILE</literal>
6963 pointers differ. Specifically, multithreaded/single-threaded,
6964 release/debug, and static/dynamic flags should be the same for the
6965 library and all applications using that library.
6966 </para>
6967 </note>
6969 </listitem>
6970 </varlistentry>
6972 <varlistentry id="libpq-PQsetTraceFlags">
6973 <term><function>PQsetTraceFlags</function><indexterm><primary>PQsetTraceFlags</primary></indexterm></term>
6975 <listitem>
6976 <para>
6977 Controls the tracing behavior of client/server communication.
6978 <synopsis>
6979 void PQsetTraceFlags(PGconn *conn, int flags);
6980 </synopsis>
6981 </para>
6983 <para>
6984 <literal>flags</literal> contains flag bits describing the operating mode
6985 of tracing.
6986 If <literal>flags</literal> contains <literal>PQTRACE_SUPPRESS_TIMESTAMPS</literal>,
6987 then the timestamp is not included when printing each message.
6988 If <literal>flags</literal> contains <literal>PQTRACE_REGRESS_MODE</literal>,
6989 then some fields are redacted when printing each message, such as object
6990 OIDs, to make the output more convenient to use in testing frameworks.
6991 This function must be called after calling <function>PQtrace</function>.
6992 </para>
6994 </listitem>
6995 </varlistentry>
6997 <varlistentry id="libpq-PQuntrace">
6998 <term><function>PQuntrace</function><indexterm><primary>PQuntrace</primary></indexterm></term>
7000 <listitem>
7001 <para>
7002 Disables tracing started by <xref linkend="libpq-PQtrace"/>.
7003 <synopsis>
7004 void PQuntrace(PGconn *conn);
7005 </synopsis>
7006 </para>
7007 </listitem>
7008 </varlistentry>
7009 </variablelist>
7011 </sect1>
7013 <sect1 id="libpq-misc">
7014 <title>Miscellaneous Functions</title>
7016 <para>
7017 As always, there are some functions that just don't fit anywhere.
7018 </para>
7020 <variablelist>
7021 <varlistentry id="libpq-PQfreemem">
7022 <term><function>PQfreemem</function><indexterm><primary>PQfreemem</primary></indexterm></term>
7024 <listitem>
7025 <para>
7026 Frees memory allocated by <application>libpq</application>.
7027 <synopsis>
7028 void PQfreemem(void *ptr);
7029 </synopsis>
7030 </para>
7032 <para>
7033 Frees memory allocated by <application>libpq</application>, particularly
7034 <xref linkend="libpq-PQescapeByteaConn"/>,
7035 <xref linkend="libpq-PQescapeBytea"/>,
7036 <xref linkend="libpq-PQunescapeBytea"/>,
7037 and <function>PQnotifies</function>.
7038 It is particularly important that this function, rather than
7039 <function>free()</function>, be used on Microsoft Windows. This is because
7040 allocating memory in a DLL and releasing it in the application works
7041 only if multithreaded/single-threaded, release/debug, and static/dynamic
7042 flags are the same for the DLL and the application. On non-Microsoft
7043 Windows platforms, this function is the same as the standard library
7044 function <function>free()</function>.
7045 </para>
7046 </listitem>
7047 </varlistentry>
7049 <varlistentry id="libpq-PQconninfoFree">
7050 <term><function>PQconninfoFree</function><indexterm><primary>PQconninfoFree</primary></indexterm></term>
7052 <listitem>
7053 <para>
7054 Frees the data structures allocated by
7055 <xref linkend="libpq-PQconndefaults"/> or <xref linkend="libpq-PQconninfoParse"/>.
7056 <synopsis>
7057 void PQconninfoFree(PQconninfoOption *connOptions);
7058 </synopsis>
7059 If the argument is a <symbol>NULL</symbol> pointer, no operation is
7060 performed.
7061 </para>
7063 <para>
7064 A simple <xref linkend="libpq-PQfreemem"/> will not do for this, since
7065 the array contains references to subsidiary strings.
7066 </para>
7067 </listitem>
7068 </varlistentry>
7070 <varlistentry id="libpq-PQencryptPasswordConn">
7071 <term><function>PQencryptPasswordConn</function><indexterm><primary>PQencryptPasswordConn</primary></indexterm></term>
7073 <listitem>
7074 <para>
7075 Prepares the encrypted form of a <productname>PostgreSQL</productname> password.
7076 <synopsis>
7077 char *PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm);
7078 </synopsis>
7079 This function is intended to be used by client applications that
7080 wish to send commands like <literal>ALTER USER joe PASSWORD
7081 'pwd'</literal>. It is good practice not to send the original cleartext
7082 password in such a command, because it might be exposed in command
7083 logs, activity displays, and so on. Instead, use this function to
7084 convert the password to encrypted form before it is sent.
7085 </para>
7087 <para>
7088 The <parameter>passwd</parameter> and <parameter>user</parameter> arguments
7089 are the cleartext password, and the SQL name of the user it is for.
7090 <parameter>algorithm</parameter> specifies the encryption algorithm
7091 to use to encrypt the password. Currently supported algorithms are
7092 <literal>md5</literal> and <literal>scram-sha-256</literal> (<literal>on</literal> and
7093 <literal>off</literal> are also accepted as aliases for <literal>md5</literal>, for
7094 compatibility with older server versions). Note that support for
7095 <literal>scram-sha-256</literal> was introduced in <productname>PostgreSQL</productname>
7096 version 10, and will not work correctly with older server versions. If
7097 <parameter>algorithm</parameter> is <symbol>NULL</symbol>, this function will query
7098 the server for the current value of the
7099 <xref linkend="guc-password-encryption"/> setting. That can block, and
7100 will fail if the current transaction is aborted, or if the connection
7101 is busy executing another query. If you wish to use the default
7102 algorithm for the server but want to avoid blocking, query
7103 <varname>password_encryption</varname> yourself before calling
7104 <xref linkend="libpq-PQencryptPasswordConn"/>, and pass that value as the
7105 <parameter>algorithm</parameter>.
7106 </para>
7108 <para>
7109 The return value is a string allocated by <function>malloc</function>.
7110 The caller can assume the string doesn't contain any special characters
7111 that would require escaping. Use <xref linkend="libpq-PQfreemem"/> to free the
7112 result when done with it. On error, returns <symbol>NULL</symbol>, and
7113 a suitable message is stored in the connection object.
7114 </para>
7116 </listitem>
7117 </varlistentry>
7119 <varlistentry id="libpq-PQencryptPassword">
7120 <term><function>PQencryptPassword</function><indexterm><primary>PQencryptPassword</primary></indexterm></term>
7122 <listitem>
7123 <para>
7124 Prepares the md5-encrypted form of a <productname>PostgreSQL</productname> password.
7125 <synopsis>
7126 char *PQencryptPassword(const char *passwd, const char *user);
7127 </synopsis>
7128 <xref linkend="libpq-PQencryptPassword"/> is an older, deprecated version of
7129 <xref linkend="libpq-PQencryptPasswordConn"/>. The difference is that
7130 <xref linkend="libpq-PQencryptPassword"/> does not
7131 require a connection object, and <literal>md5</literal> is always used as the
7132 encryption algorithm.
7133 </para>
7134 </listitem>
7135 </varlistentry>
7137 <varlistentry id="libpq-PQmakeEmptyPGresult">
7138 <term><function>PQmakeEmptyPGresult</function><indexterm><primary>PQmakeEmptyPGresult</primary></indexterm></term>
7140 <listitem>
7141 <para>
7142 Constructs an empty <structname>PGresult</structname> object with the given status.
7143 <synopsis>
7144 PGresult *PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status);
7145 </synopsis>
7146 </para>
7148 <para>
7149 This is <application>libpq</application>'s internal function to allocate and
7150 initialize an empty <structname>PGresult</structname> object. This
7151 function returns <symbol>NULL</symbol> if memory could not be allocated. It is
7152 exported because some applications find it useful to generate result
7153 objects (particularly objects with error status) themselves. If
7154 <parameter>conn</parameter> is not null and <parameter>status</parameter>
7155 indicates an error, the current error message of the specified
7156 connection is copied into the <structname>PGresult</structname>.
7157 Also, if <parameter>conn</parameter> is not null, any event procedures
7158 registered in the connection are copied into the
7159 <structname>PGresult</structname>. (They do not get
7160 <literal>PGEVT_RESULTCREATE</literal> calls, but see
7161 <xref linkend="libpq-PQfireResultCreateEvents"/>.)
7162 Note that <xref linkend="libpq-PQclear"/> should eventually be called
7163 on the object, just as with a <structname>PGresult</structname>
7164 returned by <application>libpq</application> itself.
7165 </para>
7166 </listitem>
7167 </varlistentry>
7169 <varlistentry id="libpq-PQfireResultCreateEvents">
7170 <term><function>PQfireResultCreateEvents</function><indexterm><primary>PQfireResultCreateEvents</primary></indexterm></term>
7171 <listitem>
7172 <para>
7173 Fires a <literal>PGEVT_RESULTCREATE</literal> event (see <xref
7174 linkend="libpq-events"/>) for each event procedure registered in the
7175 <structname>PGresult</structname> object. Returns non-zero for success,
7176 zero if any event procedure fails.
7178 <synopsis>
7179 int PQfireResultCreateEvents(PGconn *conn, PGresult *res);
7180 </synopsis>
7181 </para>
7183 <para>
7184 The <literal>conn</literal> argument is passed through to event procedures
7185 but not used directly. It can be <symbol>NULL</symbol> if the event
7186 procedures won't use it.
7187 </para>
7189 <para>
7190 Event procedures that have already received a
7191 <literal>PGEVT_RESULTCREATE</literal> or <literal>PGEVT_RESULTCOPY</literal> event
7192 for this object are not fired again.
7193 </para>
7195 <para>
7196 The main reason that this function is separate from
7197 <xref linkend="libpq-PQmakeEmptyPGresult"/> is that it is often appropriate
7198 to create a <structname>PGresult</structname> and fill it with data
7199 before invoking the event procedures.
7200 </para>
7201 </listitem>
7202 </varlistentry>
7204 <varlistentry id="libpq-PQcopyResult">
7205 <term><function>PQcopyResult</function><indexterm><primary>PQcopyResult</primary></indexterm></term>
7207 <listitem>
7208 <para>
7209 Makes a copy of a <structname>PGresult</structname> object. The copy is
7210 not linked to the source result in any way and
7211 <xref linkend="libpq-PQclear"/> must be called when the copy is no longer
7212 needed. If the function fails, <symbol>NULL</symbol> is returned.
7214 <synopsis>
7215 PGresult *PQcopyResult(const PGresult *src, int flags);
7216 </synopsis>
7217 </para>
7219 <para>
7220 This is not intended to make an exact copy. The returned result is
7221 always put into <literal>PGRES_TUPLES_OK</literal> status, and does not
7222 copy any error message in the source. (It does copy the command status
7223 string, however.) The <parameter>flags</parameter> argument determines
7224 what else is copied. It is a bitwise OR of several flags.
7225 <literal>PG_COPYRES_ATTRS</literal> specifies copying the source
7226 result's attributes (column definitions).
7227 <literal>PG_COPYRES_TUPLES</literal> specifies copying the source
7228 result's tuples. (This implies copying the attributes, too.)
7229 <literal>PG_COPYRES_NOTICEHOOKS</literal> specifies
7230 copying the source result's notify hooks.
7231 <literal>PG_COPYRES_EVENTS</literal> specifies copying the source
7232 result's events. (But any instance data associated with the source
7233 is not copied.)
7234 The event procedures receive <literal>PGEVT_RESULTCOPY</literal> events.
7235 </para>
7236 </listitem>
7237 </varlistentry>
7239 <varlistentry id="libpq-PQsetResultAttrs">
7240 <term><function>PQsetResultAttrs</function><indexterm><primary>PQsetResultAttrs</primary></indexterm></term>
7242 <listitem>
7243 <para>
7244 Sets the attributes of a <structname>PGresult</structname> object.
7245 <synopsis>
7246 int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs);
7247 </synopsis>
7248 </para>
7250 <para>
7251 The provided <parameter>attDescs</parameter> are copied into the result.
7252 If the <parameter>attDescs</parameter> pointer is <symbol>NULL</symbol> or
7253 <parameter>numAttributes</parameter> is less than one, the request is
7254 ignored and the function succeeds. If <parameter>res</parameter>
7255 already contains attributes, the function will fail. If the function
7256 fails, the return value is zero. If the function succeeds, the return
7257 value is non-zero.
7258 </para>
7259 </listitem>
7260 </varlistentry>
7262 <varlistentry id="libpq-PQsetvalue">
7263 <term><function>PQsetvalue</function><indexterm><primary>PQsetvalue</primary></indexterm></term>
7265 <listitem>
7266 <para>
7267 Sets a tuple field value of a <structname>PGresult</structname> object.
7268 <synopsis>
7269 int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len);
7270 </synopsis>
7271 </para>
7273 <para>
7274 The function will automatically grow the result's internal tuples array
7275 as needed. However, the <parameter>tup_num</parameter> argument must be
7276 less than or equal to <xref linkend="libpq-PQntuples"/>, meaning this
7277 function can only grow the tuples array one tuple at a time. But any
7278 field of any existing tuple can be modified in any order. If a value at
7279 <parameter>field_num</parameter> already exists, it will be overwritten.
7280 If <parameter>len</parameter> is -1 or
7281 <parameter>value</parameter> is <symbol>NULL</symbol>, the field value
7282 will be set to an SQL null value. The
7283 <parameter>value</parameter> is copied into the result's private storage,
7284 thus is no longer needed after the function
7285 returns. If the function fails, the return value is zero. If the
7286 function succeeds, the return value is non-zero.
7287 </para>
7288 </listitem>
7289 </varlistentry>
7291 <varlistentry id="libpq-PQresultAlloc">
7292 <term><function>PQresultAlloc</function><indexterm><primary>PQresultAlloc</primary></indexterm></term>
7294 <listitem>
7295 <para>
7296 Allocate subsidiary storage for a <structname>PGresult</structname> object.
7297 <synopsis>
7298 void *PQresultAlloc(PGresult *res, size_t nBytes);
7299 </synopsis>
7300 </para>
7302 <para>
7303 Any memory allocated with this function will be freed when
7304 <parameter>res</parameter> is cleared. If the function fails,
7305 the return value is <symbol>NULL</symbol>. The result is
7306 guaranteed to be adequately aligned for any type of data,
7307 just as for <function>malloc</function>.
7308 </para>
7309 </listitem>
7310 </varlistentry>
7312 <varlistentry id="libpq-PQresultMemorySize">
7313 <term><function>PQresultMemorySize</function><indexterm><primary>PQresultMemorySize</primary></indexterm></term>
7315 <listitem>
7316 <para>
7317 Retrieves the number of bytes allocated for
7318 a <structname>PGresult</structname> object.
7319 <synopsis>
7320 size_t PQresultMemorySize(const PGresult *res);
7321 </synopsis>
7322 </para>
7324 <para>
7325 This value is the sum of all <function>malloc</function> requests
7326 associated with the <structname>PGresult</structname> object, that is,
7327 all the memory that will be freed by <xref linkend="libpq-PQclear"/>.
7328 This information can be useful for managing memory consumption.
7329 </para>
7330 </listitem>
7331 </varlistentry>
7333 <varlistentry id="libpq-PQlibVersion">
7334 <term><function>PQlibVersion</function><indexterm
7335 ><primary>PQlibVersion</primary><seealso>PQserverVersion</seealso></indexterm></term>
7337 <listitem>
7338 <para>
7339 Return the version of <productname>libpq</productname> that is being used.
7340 <synopsis>
7341 int PQlibVersion(void);
7342 </synopsis>
7343 </para>
7345 <para>
7346 The result of this function can be used to determine, at
7347 run time, whether specific functionality is available in the currently
7348 loaded version of libpq. The function can be used, for example,
7349 to determine which connection options are available in
7350 <xref linkend="libpq-PQconnectdb"/>.
7351 </para>
7353 <para>
7354 The result is formed by multiplying the library's major version
7355 number by 10000 and adding the minor version number. For example,
7356 version 10.1 will be returned as 100001, and version 11.0 will be
7357 returned as 110000.
7358 </para>
7360 <para>
7361 Prior to major version 10, <productname>PostgreSQL</productname> used
7362 three-part version numbers in which the first two parts together
7363 represented the major version. For those
7364 versions, <xref linkend="libpq-PQlibVersion"/> uses two digits for each
7365 part; for example version 9.1.5 will be returned as 90105, and
7366 version 9.2.0 will be returned as 90200.
7367 </para>
7369 <para>
7370 Therefore, for purposes of determining feature compatibility,
7371 applications should divide the result of <xref linkend="libpq-PQlibVersion"/>
7372 by 100 not 10000 to determine a logical major version number.
7373 In all release series, only the last two digits differ between
7374 minor releases (bug-fix releases).
7375 </para>
7377 <note>
7378 <para>
7379 This function appeared in <productname>PostgreSQL</productname> version 9.1, so
7380 it cannot be used to detect required functionality in earlier
7381 versions, since calling it will create a link dependency
7382 on version 9.1 or later.
7383 </para>
7384 </note>
7385 </listitem>
7386 </varlistentry>
7388 </variablelist>
7390 </sect1>
7392 <sect1 id="libpq-notice-processing">
7393 <title>Notice Processing</title>
7395 <indexterm zone="libpq-notice-processing">
7396 <primary>notice processing</primary>
7397 <secondary>in libpq</secondary>
7398 </indexterm>
7400 <para>
7401 Notice and warning messages generated by the server are not returned
7402 by the query execution functions, since they do not imply failure of
7403 the query. Instead they are passed to a notice handling function, and
7404 execution continues normally after the handler returns. The default
7405 notice handling function prints the message on
7406 <filename>stderr</filename>, but the application can override this
7407 behavior by supplying its own handling function.
7408 </para>
7410 <para>
7411 For historical reasons, there are two levels of notice handling, called
7412 the notice receiver and notice processor. The default behavior is for
7413 the notice receiver to format the notice and pass a string to the notice
7414 processor for printing. However, an application that chooses to provide
7415 its own notice receiver will typically ignore the notice processor
7416 layer and just do all the work in the notice receiver.
7417 </para>
7419 <para>
7420 The function <function id="libpq-PQsetNoticeReceiver">PQsetNoticeReceiver</function>
7421 <indexterm><primary>notice receiver</primary></indexterm>
7422 <indexterm><primary>PQsetNoticeReceiver</primary></indexterm> sets or
7423 examines the current notice receiver for a connection object.
7424 Similarly, <function id="libpq-PQsetNoticeProcessor">PQsetNoticeProcessor</function>
7425 <indexterm><primary>notice processor</primary></indexterm>
7426 <indexterm><primary>PQsetNoticeProcessor</primary></indexterm> sets or
7427 examines the current notice processor.
7429 <synopsis>
7430 typedef void (*PQnoticeReceiver) (void *arg, const PGresult *res);
7432 PQnoticeReceiver
7433 PQsetNoticeReceiver(PGconn *conn,
7434 PQnoticeReceiver proc,
7435 void *arg);
7437 typedef void (*PQnoticeProcessor) (void *arg, const char *message);
7439 PQnoticeProcessor
7440 PQsetNoticeProcessor(PGconn *conn,
7441 PQnoticeProcessor proc,
7442 void *arg);
7443 </synopsis>
7445 Each of these functions returns the previous notice receiver or
7446 processor function pointer, and sets the new value. If you supply a
7447 null function pointer, no action is taken, but the current pointer is
7448 returned.
7449 </para>
7451 <para>
7452 When a notice or warning message is received from the server, or
7453 generated internally by <application>libpq</application>, the notice
7454 receiver function is called. It is passed the message in the form of
7455 a <symbol>PGRES_NONFATAL_ERROR</symbol>
7456 <structname>PGresult</structname>. (This allows the receiver to extract
7457 individual fields using <xref linkend="libpq-PQresultErrorField"/>, or obtain a
7458 complete preformatted message using <xref linkend="libpq-PQresultErrorMessage"/>
7459 or <xref linkend="libpq-PQresultVerboseErrorMessage"/>.) The same
7460 void pointer passed to <function>PQsetNoticeReceiver</function> is also
7461 passed. (This pointer can be used to access application-specific state
7462 if needed.)
7463 </para>
7465 <para>
7466 The default notice receiver simply extracts the message (using
7467 <xref linkend="libpq-PQresultErrorMessage"/>) and passes it to the notice
7468 processor.
7469 </para>
7471 <para>
7472 The notice processor is responsible for handling a notice or warning
7473 message given in text form. It is passed the string text of the message
7474 (including a trailing newline), plus a void pointer that is the same
7475 one passed to <function>PQsetNoticeProcessor</function>. (This pointer
7476 can be used to access application-specific state if needed.)
7477 </para>
7479 <para>
7480 The default notice processor is simply:
7481 <programlisting>
7482 static void
7483 defaultNoticeProcessor(void *arg, const char *message)
7485 fprintf(stderr, "%s", message);
7487 </programlisting>
7488 </para>
7490 <para>
7491 Once you have set a notice receiver or processor, you should expect
7492 that that function could be called as long as either the
7493 <structname>PGconn</structname> object or <structname>PGresult</structname> objects made
7494 from it exist. At creation of a <structname>PGresult</structname>, the
7495 <structname>PGconn</structname>'s current notice handling pointers are copied
7496 into the <structname>PGresult</structname> for possible use by functions like
7497 <xref linkend="libpq-PQgetvalue"/>.
7498 </para>
7500 </sect1>
7502 <sect1 id="libpq-events">
7503 <title>Event System</title>
7505 <para>
7506 <application>libpq</application>'s event system is designed to notify
7507 registered event handlers about interesting
7508 <application>libpq</application> events, such as the creation or
7509 destruction of <structname>PGconn</structname> and
7510 <structname>PGresult</structname> objects. A principal use case is that
7511 this allows applications to associate their own data with a
7512 <structname>PGconn</structname> or <structname>PGresult</structname>
7513 and ensure that that data is freed at an appropriate time.
7514 </para>
7516 <para>
7517 Each registered event handler is associated with two pieces of data,
7518 known to <application>libpq</application> only as opaque <literal>void *</literal>
7519 pointers. There is a <firstterm>pass-through</firstterm> pointer that is provided
7520 by the application when the event handler is registered with a
7521 <structname>PGconn</structname>. The pass-through pointer never changes for the
7522 life of the <structname>PGconn</structname> and all <structname>PGresult</structname>s
7523 generated from it; so if used, it must point to long-lived data.
7524 In addition there is an <firstterm>instance data</firstterm> pointer, which starts
7525 out <symbol>NULL</symbol> in every <structname>PGconn</structname> and <structname>PGresult</structname>.
7526 This pointer can be manipulated using the
7527 <xref linkend="libpq-PQinstanceData"/>,
7528 <xref linkend="libpq-PQsetInstanceData"/>,
7529 <xref linkend="libpq-PQresultInstanceData"/> and
7530 <xref linkend="libpq-PQresultSetInstanceData"/> functions. Note that
7531 unlike the pass-through pointer, instance data of a <structname>PGconn</structname>
7532 is not automatically inherited by <structname>PGresult</structname>s created from
7533 it. <application>libpq</application> does not know what pass-through
7534 and instance data pointers point to (if anything) and will never attempt
7535 to free them &mdash; that is the responsibility of the event handler.
7536 </para>
7538 <sect2 id="libpq-events-types">
7539 <title>Event Types</title>
7541 <para>
7542 The enum <literal>PGEventId</literal> names the types of events handled by
7543 the event system. All its values have names beginning with
7544 <literal>PGEVT</literal>. For each event type, there is a corresponding
7545 event info structure that carries the parameters passed to the event
7546 handlers. The event types are:
7547 </para>
7549 <variablelist>
7550 <varlistentry id="libpq-pgevt-register">
7551 <term><literal>PGEVT_REGISTER</literal></term>
7552 <listitem>
7553 <para>
7554 The register event occurs when <xref linkend="libpq-PQregisterEventProc"/>
7555 is called. It is the ideal time to initialize any
7556 <literal>instanceData</literal> an event procedure may need. Only one
7557 register event will be fired per event handler per connection. If the
7558 event procedure fails (returns zero), the registration is cancelled.
7560 <synopsis>
7561 typedef struct
7563 PGconn *conn;
7564 } PGEventRegister;
7565 </synopsis>
7567 When a <literal>PGEVT_REGISTER</literal> event is received, the
7568 <parameter>evtInfo</parameter> pointer should be cast to a
7569 <structname>PGEventRegister *</structname>. This structure contains a
7570 <structname>PGconn</structname> that should be in the
7571 <literal>CONNECTION_OK</literal> status; guaranteed if one calls
7572 <xref linkend="libpq-PQregisterEventProc"/> right after obtaining a good
7573 <structname>PGconn</structname>. When returning a failure code, all
7574 cleanup must be performed as no <literal>PGEVT_CONNDESTROY</literal>
7575 event will be sent.
7576 </para>
7577 </listitem>
7578 </varlistentry>
7580 <varlistentry id="libpq-pgevt-connreset">
7581 <term><literal>PGEVT_CONNRESET</literal></term>
7582 <listitem>
7583 <para>
7584 The connection reset event is fired on completion of
7585 <xref linkend="libpq-PQreset"/> or <function>PQresetPoll</function>. In
7586 both cases, the event is only fired if the reset was successful.
7587 The return value of the event procedure is ignored
7588 in <productname>PostgreSQL</productname> v15 and later.
7589 With earlier versions, however, it's important to return success
7590 (nonzero) or the connection will be aborted.
7592 <synopsis>
7593 typedef struct
7595 PGconn *conn;
7596 } PGEventConnReset;
7597 </synopsis>
7599 When a <literal>PGEVT_CONNRESET</literal> event is received, the
7600 <parameter>evtInfo</parameter> pointer should be cast to a
7601 <structname>PGEventConnReset *</structname>. Although the contained
7602 <structname>PGconn</structname> was just reset, all event data remains
7603 unchanged. This event should be used to reset/reload/requery any
7604 associated <literal>instanceData</literal>. Note that even if the
7605 event procedure fails to process <literal>PGEVT_CONNRESET</literal>, it will
7606 still receive a <literal>PGEVT_CONNDESTROY</literal> event when the connection
7607 is closed.
7608 </para>
7609 </listitem>
7610 </varlistentry>
7612 <varlistentry id="libpq-pgevt-conndestroy">
7613 <term><literal>PGEVT_CONNDESTROY</literal></term>
7614 <listitem>
7615 <para>
7616 The connection destroy event is fired in response to
7617 <xref linkend="libpq-PQfinish"/>. It is the event procedure's
7618 responsibility to properly clean up its event data as libpq has no
7619 ability to manage this memory. Failure to clean up will lead
7620 to memory leaks.
7622 <synopsis>
7623 typedef struct
7625 PGconn *conn;
7626 } PGEventConnDestroy;
7627 </synopsis>
7629 When a <literal>PGEVT_CONNDESTROY</literal> event is received, the
7630 <parameter>evtInfo</parameter> pointer should be cast to a
7631 <structname>PGEventConnDestroy *</structname>. This event is fired
7632 prior to <xref linkend="libpq-PQfinish"/> performing any other cleanup.
7633 The return value of the event procedure is ignored since there is no
7634 way of indicating a failure from <xref linkend="libpq-PQfinish"/>. Also,
7635 an event procedure failure should not abort the process of cleaning up
7636 unwanted memory.
7637 </para>
7638 </listitem>
7639 </varlistentry>
7641 <varlistentry id="libpq-pgevt-resultcreate">
7642 <term><literal>PGEVT_RESULTCREATE</literal></term>
7643 <listitem>
7644 <para>
7645 The result creation event is fired in response to any query execution
7646 function that generates a result, including
7647 <xref linkend="libpq-PQgetResult"/>. This event will only be fired after
7648 the result has been created successfully.
7650 <synopsis>
7651 typedef struct
7653 PGconn *conn;
7654 PGresult *result;
7655 } PGEventResultCreate;
7656 </synopsis>
7658 When a <literal>PGEVT_RESULTCREATE</literal> event is received, the
7659 <parameter>evtInfo</parameter> pointer should be cast to a
7660 <structname>PGEventResultCreate *</structname>. The
7661 <parameter>conn</parameter> is the connection used to generate the
7662 result. This is the ideal place to initialize any
7663 <literal>instanceData</literal> that needs to be associated with the
7664 result. If an event procedure fails (returns zero), that event
7665 procedure will be ignored for the remaining lifetime of the result;
7666 that is, it will not receive <literal>PGEVT_RESULTCOPY</literal>
7667 or <literal>PGEVT_RESULTDESTROY</literal> events for this result or
7668 results copied from it.
7669 </para>
7670 </listitem>
7671 </varlistentry>
7673 <varlistentry id="libpq-pgevt-resultcopy">
7674 <term><literal>PGEVT_RESULTCOPY</literal></term>
7675 <listitem>
7676 <para>
7677 The result copy event is fired in response to
7678 <xref linkend="libpq-PQcopyResult"/>. This event will only be fired after
7679 the copy is complete. Only event procedures that have
7680 successfully handled the <literal>PGEVT_RESULTCREATE</literal>
7681 or <literal>PGEVT_RESULTCOPY</literal> event for the source result
7682 will receive <literal>PGEVT_RESULTCOPY</literal> events.
7684 <synopsis>
7685 typedef struct
7687 const PGresult *src;
7688 PGresult *dest;
7689 } PGEventResultCopy;
7690 </synopsis>
7692 When a <literal>PGEVT_RESULTCOPY</literal> event is received, the
7693 <parameter>evtInfo</parameter> pointer should be cast to a
7694 <structname>PGEventResultCopy *</structname>. The
7695 <parameter>src</parameter> result is what was copied while the
7696 <parameter>dest</parameter> result is the copy destination. This event
7697 can be used to provide a deep copy of <literal>instanceData</literal>,
7698 since <literal>PQcopyResult</literal> cannot do that. If an event
7699 procedure fails (returns zero), that event procedure will be
7700 ignored for the remaining lifetime of the new result; that is, it
7701 will not receive <literal>PGEVT_RESULTCOPY</literal>
7702 or <literal>PGEVT_RESULTDESTROY</literal> events for that result or
7703 results copied from it.
7704 </para>
7705 </listitem>
7706 </varlistentry>
7708 <varlistentry id="libpq-pgevt-resultdestroy">
7709 <term><literal>PGEVT_RESULTDESTROY</literal></term>
7710 <listitem>
7711 <para>
7712 The result destroy event is fired in response to a
7713 <xref linkend="libpq-PQclear"/>. It is the event procedure's
7714 responsibility to properly clean up its event data as libpq has no
7715 ability to manage this memory. Failure to clean up will lead
7716 to memory leaks.
7718 <synopsis>
7719 typedef struct
7721 PGresult *result;
7722 } PGEventResultDestroy;
7723 </synopsis>
7725 When a <literal>PGEVT_RESULTDESTROY</literal> event is received, the
7726 <parameter>evtInfo</parameter> pointer should be cast to a
7727 <structname>PGEventResultDestroy *</structname>. This event is fired
7728 prior to <xref linkend="libpq-PQclear"/> performing any other cleanup.
7729 The return value of the event procedure is ignored since there is no
7730 way of indicating a failure from <xref linkend="libpq-PQclear"/>. Also,
7731 an event procedure failure should not abort the process of cleaning up
7732 unwanted memory.
7733 </para>
7734 </listitem>
7735 </varlistentry>
7736 </variablelist>
7737 </sect2>
7739 <sect2 id="libpq-events-proc">
7740 <title>Event Callback Procedure</title>
7742 <variablelist>
7743 <varlistentry id="libpq-PGEventProc">
7744 <term><literal>PGEventProc</literal><indexterm><primary>PGEventProc</primary></indexterm></term>
7746 <listitem>
7747 <para>
7748 <literal>PGEventProc</literal> is a typedef for a pointer to an
7749 event procedure, that is, the user callback function that receives
7750 events from libpq. The signature of an event procedure must be
7752 <synopsis>
7753 int eventproc(PGEventId evtId, void *evtInfo, void *passThrough)
7754 </synopsis>
7756 The <parameter>evtId</parameter> parameter indicates which
7757 <literal>PGEVT</literal> event occurred. The
7758 <parameter>evtInfo</parameter> pointer must be cast to the appropriate
7759 structure type to obtain further information about the event.
7760 The <parameter>passThrough</parameter> parameter is the pointer
7761 provided to <xref linkend="libpq-PQregisterEventProc"/> when the event
7762 procedure was registered. The function should return a non-zero value
7763 if it succeeds and zero if it fails.
7764 </para>
7766 <para>
7767 A particular event procedure can be registered only once in any
7768 <structname>PGconn</structname>. This is because the address of the procedure
7769 is used as a lookup key to identify the associated instance data.
7770 </para>
7772 <caution>
7773 <para>
7774 On Windows, functions can have two different addresses: one visible
7775 from outside a DLL and another visible from inside the DLL. One
7776 should be careful that only one of these addresses is used with
7777 <application>libpq</application>'s event-procedure functions, else confusion will
7778 result. The simplest rule for writing code that will work is to
7779 ensure that event procedures are declared <literal>static</literal>. If the
7780 procedure's address must be available outside its own source file,
7781 expose a separate function to return the address.
7782 </para>
7783 </caution>
7784 </listitem>
7785 </varlistentry>
7786 </variablelist>
7787 </sect2>
7789 <sect2 id="libpq-events-funcs">
7790 <title>Event Support Functions</title>
7792 <variablelist>
7793 <varlistentry id="libpq-PQregisterEventProc">
7794 <term><function>PQregisterEventProc</function><indexterm><primary>PQregisterEventProc</primary></indexterm></term>
7796 <listitem>
7797 <para>
7798 Registers an event callback procedure with libpq.
7800 <synopsis>
7801 int PQregisterEventProc(PGconn *conn, PGEventProc proc,
7802 const char *name, void *passThrough);
7803 </synopsis>
7804 </para>
7806 <para>
7807 An event procedure must be registered once on each
7808 <structname>PGconn</structname> you want to receive events about. There is no
7809 limit, other than memory, on the number of event procedures that
7810 can be registered with a connection. The function returns a non-zero
7811 value if it succeeds and zero if it fails.
7812 </para>
7814 <para>
7815 The <parameter>proc</parameter> argument will be called when a libpq
7816 event is fired. Its memory address is also used to lookup
7817 <literal>instanceData</literal>. The <parameter>name</parameter>
7818 argument is used to refer to the event procedure in error messages.
7819 This value cannot be <symbol>NULL</symbol> or a zero-length string. The name string is
7820 copied into the <structname>PGconn</structname>, so what is passed need not be
7821 long-lived. The <parameter>passThrough</parameter> pointer is passed
7822 to the <parameter>proc</parameter> whenever an event occurs. This
7823 argument can be <symbol>NULL</symbol>.
7824 </para>
7825 </listitem>
7826 </varlistentry>
7828 <varlistentry id="libpq-PQsetInstanceData">
7829 <term><function>PQsetInstanceData</function><indexterm><primary>PQsetInstanceData</primary></indexterm></term>
7830 <listitem>
7831 <para>
7832 Sets the connection <parameter>conn</parameter>'s <literal>instanceData</literal>
7833 for procedure <parameter>proc</parameter> to <parameter>data</parameter>. This
7834 returns non-zero for success and zero for failure. (Failure is
7835 only possible if <parameter>proc</parameter> has not been properly
7836 registered in <parameter>conn</parameter>.)
7838 <synopsis>
7839 int PQsetInstanceData(PGconn *conn, PGEventProc proc, void *data);
7840 </synopsis>
7841 </para>
7842 </listitem>
7843 </varlistentry>
7845 <varlistentry id="libpq-PQinstanceData">
7846 <term><function>PQinstanceData</function><indexterm><primary>PQinstanceData</primary></indexterm></term>
7847 <listitem>
7848 <para>
7849 Returns the
7850 connection <parameter>conn</parameter>'s <literal>instanceData</literal>
7851 associated with procedure <parameter>proc</parameter>,
7852 or <symbol>NULL</symbol> if there is none.
7854 <synopsis>
7855 void *PQinstanceData(const PGconn *conn, PGEventProc proc);
7856 </synopsis>
7857 </para>
7858 </listitem>
7859 </varlistentry>
7861 <varlistentry id="libpq-PQresultSetInstanceData">
7862 <term><function>PQresultSetInstanceData</function><indexterm><primary>PQresultSetInstanceData</primary></indexterm></term>
7863 <listitem>
7864 <para>
7865 Sets the result's <literal>instanceData</literal>
7866 for <parameter>proc</parameter> to <parameter>data</parameter>. This returns
7867 non-zero for success and zero for failure. (Failure is only
7868 possible if <parameter>proc</parameter> has not been properly registered
7869 in the result.)
7871 <synopsis>
7872 int PQresultSetInstanceData(PGresult *res, PGEventProc proc, void *data);
7873 </synopsis>
7874 </para>
7876 <para>
7877 Beware that any storage represented by <parameter>data</parameter>
7878 will not be accounted for by <xref linkend="libpq-PQresultMemorySize"/>,
7879 unless it is allocated using <xref linkend="libpq-PQresultAlloc"/>.
7880 (Doing so is recommendable because it eliminates the need to free
7881 such storage explicitly when the result is destroyed.)
7882 </para>
7883 </listitem>
7884 </varlistentry>
7886 <varlistentry id="libpq-PQresultInstanceData">
7887 <term><function>PQresultInstanceData</function><indexterm><primary>PQresultInstanceData</primary></indexterm></term>
7888 <listitem>
7889 <para>
7890 Returns the result's <literal>instanceData</literal> associated with <parameter>proc</parameter>, or <symbol>NULL</symbol>
7891 if there is none.
7893 <synopsis>
7894 void *PQresultInstanceData(const PGresult *res, PGEventProc proc);
7895 </synopsis>
7896 </para>
7897 </listitem>
7898 </varlistentry>
7899 </variablelist>
7900 </sect2>
7902 <sect2 id="libpq-events-example">
7903 <title>Event Example</title>
7905 <para>
7906 Here is a skeleton example of managing private data associated with
7907 libpq connections and results.
7908 </para>
7910 <programlisting>
7911 <![CDATA[
7912 /* required header for libpq events (note: includes libpq-fe.h) */
7913 #include <libpq-events.h>
7915 /* The instanceData */
7916 typedef struct
7918 int n;
7919 char *str;
7920 } mydata;
7922 /* PGEventProc */
7923 static int myEventProc(PGEventId evtId, void *evtInfo, void *passThrough);
7926 main(void)
7928 mydata *data;
7929 PGresult *res;
7930 PGconn *conn =
7931 PQconnectdb("dbname=postgres options=-csearch_path=");
7933 if (PQstatus(conn) != CONNECTION_OK)
7935 /* PQerrorMessage's result includes a trailing newline */
7936 fprintf(stderr, "%s", PQerrorMessage(conn));
7937 PQfinish(conn);
7938 return 1;
7941 /* called once on any connection that should receive events.
7942 * Sends a PGEVT_REGISTER to myEventProc.
7944 if (!PQregisterEventProc(conn, myEventProc, "mydata_proc", NULL))
7946 fprintf(stderr, "Cannot register PGEventProc\n");
7947 PQfinish(conn);
7948 return 1;
7951 /* conn instanceData is available */
7952 data = PQinstanceData(conn, myEventProc);
7954 /* Sends a PGEVT_RESULTCREATE to myEventProc */
7955 res = PQexec(conn, "SELECT 1 + 1");
7957 /* result instanceData is available */
7958 data = PQresultInstanceData(res, myEventProc);
7960 /* If PG_COPYRES_EVENTS is used, sends a PGEVT_RESULTCOPY to myEventProc */
7961 res_copy = PQcopyResult(res, PG_COPYRES_TUPLES | PG_COPYRES_EVENTS);
7963 /* result instanceData is available if PG_COPYRES_EVENTS was
7964 * used during the PQcopyResult call.
7966 data = PQresultInstanceData(res_copy, myEventProc);
7968 /* Both clears send a PGEVT_RESULTDESTROY to myEventProc */
7969 PQclear(res);
7970 PQclear(res_copy);
7972 /* Sends a PGEVT_CONNDESTROY to myEventProc */
7973 PQfinish(conn);
7975 return 0;
7978 static int
7979 myEventProc(PGEventId evtId, void *evtInfo, void *passThrough)
7981 switch (evtId)
7983 case PGEVT_REGISTER:
7985 PGEventRegister *e = (PGEventRegister *)evtInfo;
7986 mydata *data = get_mydata(e->conn);
7988 /* associate app specific data with connection */
7989 PQsetInstanceData(e->conn, myEventProc, data);
7990 break;
7993 case PGEVT_CONNRESET:
7995 PGEventConnReset *e = (PGEventConnReset *)evtInfo;
7996 mydata *data = PQinstanceData(e->conn, myEventProc);
7998 if (data)
7999 memset(data, 0, sizeof(mydata));
8000 break;
8003 case PGEVT_CONNDESTROY:
8005 PGEventConnDestroy *e = (PGEventConnDestroy *)evtInfo;
8006 mydata *data = PQinstanceData(e->conn, myEventProc);
8008 /* free instance data because the conn is being destroyed */
8009 if (data)
8010 free_mydata(data);
8011 break;
8014 case PGEVT_RESULTCREATE:
8016 PGEventResultCreate *e = (PGEventResultCreate *)evtInfo;
8017 mydata *conn_data = PQinstanceData(e->conn, myEventProc);
8018 mydata *res_data = dup_mydata(conn_data);
8020 /* associate app specific data with result (copy it from conn) */
8021 PQresultSetInstanceData(e->result, myEventProc, res_data);
8022 break;
8025 case PGEVT_RESULTCOPY:
8027 PGEventResultCopy *e = (PGEventResultCopy *)evtInfo;
8028 mydata *src_data = PQresultInstanceData(e->src, myEventProc);
8029 mydata *dest_data = dup_mydata(src_data);
8031 /* associate app specific data with result (copy it from a result) */
8032 PQresultSetInstanceData(e->dest, myEventProc, dest_data);
8033 break;
8036 case PGEVT_RESULTDESTROY:
8038 PGEventResultDestroy *e = (PGEventResultDestroy *)evtInfo;
8039 mydata *data = PQresultInstanceData(e->result, myEventProc);
8041 /* free instance data because the result is being destroyed */
8042 if (data)
8043 free_mydata(data);
8044 break;
8047 /* unknown event ID, just return true. */
8048 default:
8049 break;
8052 return true; /* event processing succeeded */
8055 </programlisting>
8056 </sect2>
8057 </sect1>
8059 <sect1 id="libpq-envars">
8060 <title>Environment Variables</title>
8062 <indexterm zone="libpq-envars">
8063 <primary>environment variable</primary>
8064 </indexterm>
8066 <para>
8067 The following environment variables can be used to select default
8068 connection parameter values, which will be used by
8069 <xref linkend="libpq-PQconnectdb"/>, <xref linkend="libpq-PQsetdbLogin"/> and
8070 <xref linkend="libpq-PQsetdb"/> if no value is directly specified by the calling
8071 code. These are useful to avoid hard-coding database connection
8072 information into simple client applications, for example.
8074 <itemizedlist>
8075 <listitem>
8076 <para>
8077 <indexterm>
8078 <primary><envar>PGHOST</envar></primary>
8079 </indexterm>
8080 <envar>PGHOST</envar> behaves the same as the <xref
8081 linkend="libpq-connect-host"/> connection parameter.
8082 </para>
8083 </listitem>
8085 <listitem>
8086 <para>
8087 <indexterm>
8088 <primary><envar>PGHOSTADDR</envar></primary>
8089 </indexterm>
8090 <envar>PGHOSTADDR</envar> behaves the same as the <xref
8091 linkend="libpq-connect-hostaddr"/> connection parameter.
8092 This can be set instead of or in addition to <envar>PGHOST</envar>
8093 to avoid DNS lookup overhead.
8094 </para>
8095 </listitem>
8097 <listitem>
8098 <para>
8099 <indexterm>
8100 <primary><envar>PGPORT</envar></primary>
8101 </indexterm>
8102 <envar>PGPORT</envar> behaves the same as the <xref
8103 linkend="libpq-connect-port"/> connection parameter.
8104 </para>
8105 </listitem>
8107 <listitem>
8108 <para>
8109 <indexterm>
8110 <primary><envar>PGDATABASE</envar></primary>
8111 </indexterm>
8112 <envar>PGDATABASE</envar> behaves the same as the <xref
8113 linkend="libpq-connect-dbname"/> connection parameter.
8114 </para>
8115 </listitem>
8117 <listitem>
8118 <para>
8119 <indexterm>
8120 <primary><envar>PGUSER</envar></primary>
8121 </indexterm>
8122 <envar>PGUSER</envar> behaves the same as the <xref
8123 linkend="libpq-connect-user"/> connection parameter.
8124 </para>
8125 </listitem>
8127 <listitem>
8128 <para>
8129 <indexterm>
8130 <primary><envar>PGPASSWORD</envar></primary>
8131 </indexterm>
8132 <envar>PGPASSWORD</envar> behaves the same as the <xref
8133 linkend="libpq-connect-password"/> connection parameter.
8134 Use of this environment variable
8135 is not recommended for security reasons, as some operating systems
8136 allow non-root users to see process environment variables via
8137 <application>ps</application>; instead consider using a password file
8138 (see <xref linkend="libpq-pgpass"/>).
8139 </para>
8140 </listitem>
8142 <listitem>
8143 <para>
8144 <indexterm>
8145 <primary><envar>PGPASSFILE</envar></primary>
8146 </indexterm>
8147 <envar>PGPASSFILE</envar> behaves the same as the <xref
8148 linkend="libpq-connect-passfile"/> connection parameter.
8149 </para>
8150 </listitem>
8152 <listitem>
8153 <para>
8154 <indexterm>
8155 <primary><envar>PGREQUIREAUTH</envar></primary>
8156 </indexterm>
8157 <envar>PGREQUIREAUTH</envar> behaves the same as the <xref
8158 linkend="libpq-connect-require-auth"/> connection parameter.
8159 </para>
8160 </listitem>
8162 <listitem>
8163 <para>
8164 <indexterm>
8165 <primary><envar>PGCHANNELBINDING</envar></primary>
8166 </indexterm>
8167 <envar>PGCHANNELBINDING</envar> behaves the same as the <xref
8168 linkend="libpq-connect-channel-binding"/> connection parameter.
8169 </para>
8170 </listitem>
8172 <listitem>
8173 <para>
8174 <indexterm>
8175 <primary><envar>PGSERVICE</envar></primary>
8176 </indexterm>
8177 <envar>PGSERVICE</envar> behaves the same as the <xref
8178 linkend="libpq-connect-service"/> connection parameter.
8179 </para>
8180 </listitem>
8182 <listitem>
8183 <para>
8184 <indexterm>
8185 <primary><envar>PGSERVICEFILE</envar></primary>
8186 </indexterm>
8187 <envar>PGSERVICEFILE</envar> specifies the name of the per-user
8188 connection service file
8189 (see <xref linkend="libpq-pgservice"/>).
8190 Defaults to <filename>~/.pg_service.conf</filename>, or
8191 <filename>%APPDATA%\postgresql\.pg_service.conf</filename> on
8192 Microsoft Windows.
8193 </para>
8194 </listitem>
8196 <listitem>
8197 <para>
8198 <indexterm>
8199 <primary><envar>PGOPTIONS</envar></primary>
8200 </indexterm>
8201 <envar>PGOPTIONS</envar> behaves the same as the <xref
8202 linkend="libpq-connect-options"/> connection parameter.
8203 </para>
8204 </listitem>
8206 <listitem>
8207 <para>
8208 <indexterm>
8209 <primary><envar>PGAPPNAME</envar></primary>
8210 </indexterm>
8211 <envar>PGAPPNAME</envar> behaves the same as the <xref
8212 linkend="libpq-connect-application-name"/> connection parameter.
8213 </para>
8214 </listitem>
8216 <listitem>
8217 <para>
8218 <indexterm>
8219 <primary><envar>PGSSLMODE</envar></primary>
8220 </indexterm>
8221 <envar>PGSSLMODE</envar> behaves the same as the <xref
8222 linkend="libpq-connect-sslmode"/> connection parameter.
8223 </para>
8224 </listitem>
8226 <listitem>
8227 <para>
8228 <indexterm>
8229 <primary><envar>PGREQUIRESSL</envar></primary>
8230 </indexterm>
8231 <envar>PGREQUIRESSL</envar> behaves the same as the <xref
8232 linkend="libpq-connect-requiressl"/> connection parameter.
8233 This environment variable is deprecated in favor of the
8234 <envar>PGSSLMODE</envar> variable; setting both variables suppresses the
8235 effect of this one.
8236 </para>
8237 </listitem>
8239 <listitem>
8240 <para>
8241 <indexterm>
8242 <primary><envar>PGSSLCOMPRESSION</envar></primary>
8243 </indexterm>
8244 <envar>PGSSLCOMPRESSION</envar> behaves the same as the <xref
8245 linkend="libpq-connect-sslcompression"/> connection parameter.
8246 </para>
8247 </listitem>
8249 <listitem>
8250 <para>
8251 <indexterm>
8252 <primary><envar>PGSSLCERT</envar></primary>
8253 </indexterm>
8254 <envar>PGSSLCERT</envar> behaves the same as the <xref
8255 linkend="libpq-connect-sslcert"/> connection parameter.
8256 </para>
8257 </listitem>
8259 <listitem>
8260 <para>
8261 <indexterm>
8262 <primary><envar>PGSSLKEY</envar></primary>
8263 </indexterm>
8264 <envar>PGSSLKEY</envar> behaves the same as the <xref
8265 linkend="libpq-connect-sslkey"/> connection parameter.
8266 </para>
8267 </listitem>
8269 <listitem>
8270 <para>
8271 <indexterm>
8272 <primary><envar>PGSSLCERTMODE</envar></primary>
8273 </indexterm>
8274 <envar>PGSSLCERTMODE</envar> behaves the same as the <xref
8275 linkend="libpq-connect-sslcertmode"/> connection parameter.
8276 </para>
8277 </listitem>
8279 <listitem>
8280 <para>
8281 <indexterm>
8282 <primary><envar>PGSSLROOTCERT</envar></primary>
8283 </indexterm>
8284 <envar>PGSSLROOTCERT</envar> behaves the same as the <xref
8285 linkend="libpq-connect-sslrootcert"/> connection parameter.
8286 </para>
8287 </listitem>
8289 <listitem>
8290 <para>
8291 <indexterm>
8292 <primary><envar>PGSSLCRL</envar></primary>
8293 </indexterm>
8294 <envar>PGSSLCRL</envar> behaves the same as the <xref
8295 linkend="libpq-connect-sslcrl"/> connection parameter.
8296 </para>
8297 </listitem>
8299 <listitem>
8300 <para>
8301 <indexterm>
8302 <primary><envar>PGSSLCRLDIR</envar></primary>
8303 </indexterm>
8304 <envar>PGSSLCRLDIR</envar> behaves the same as the <xref
8305 linkend="libpq-connect-sslcrldir"/> connection parameter.
8306 </para>
8307 </listitem>
8309 <listitem>
8310 <para>
8311 <indexterm>
8312 <primary><envar>PGSSLSNI</envar></primary>
8313 </indexterm>
8314 <envar>PGSSLSNI</envar> behaves the same as the <xref
8315 linkend="libpq-connect-sslsni"/> connection parameter.
8316 </para>
8317 </listitem>
8319 <listitem>
8320 <para>
8321 <indexterm>
8322 <primary><envar>PGREQUIREPEER</envar></primary>
8323 </indexterm>
8324 <envar>PGREQUIREPEER</envar> behaves the same as the <xref
8325 linkend="libpq-connect-requirepeer"/> connection parameter.
8326 </para>
8327 </listitem>
8329 <listitem>
8330 <para>
8331 <indexterm>
8332 <primary><envar>PGSSLMINPROTOCOLVERSION</envar></primary>
8333 </indexterm>
8334 <envar>PGSSLMINPROTOCOLVERSION</envar> behaves the same as the <xref
8335 linkend="libpq-connect-ssl-min-protocol-version"/> connection parameter.
8336 </para>
8337 </listitem>
8339 <listitem>
8340 <para>
8341 <indexterm>
8342 <primary><envar>PGSSLMAXPROTOCOLVERSION</envar></primary>
8343 </indexterm>
8344 <envar>PGSSLMAXPROTOCOLVERSION</envar> behaves the same as the <xref
8345 linkend="libpq-connect-ssl-max-protocol-version"/> connection parameter.
8346 </para>
8347 </listitem>
8349 <listitem>
8350 <para>
8351 <indexterm>
8352 <primary><envar>PGGSSENCMODE</envar></primary>
8353 </indexterm>
8354 <envar>PGGSSENCMODE</envar> behaves the same as the <xref
8355 linkend="libpq-connect-gssencmode"/> connection parameter.
8356 </para>
8357 </listitem>
8359 <listitem>
8360 <para>
8361 <indexterm>
8362 <primary><envar>PGKRBSRVNAME</envar></primary>
8363 </indexterm>
8364 <envar>PGKRBSRVNAME</envar> behaves the same as the <xref
8365 linkend="libpq-connect-krbsrvname"/> connection parameter.
8366 </para>
8367 </listitem>
8369 <listitem>
8370 <para>
8371 <indexterm>
8372 <primary><envar>PGGSSLIB</envar></primary>
8373 </indexterm>
8374 <envar>PGGSSLIB</envar> behaves the same as the <xref
8375 linkend="libpq-connect-gsslib"/> connection parameter.
8376 </para>
8377 </listitem>
8379 <listitem>
8380 <para>
8381 <indexterm>
8382 <primary><envar>PGGSSDELEGATION</envar></primary>
8383 </indexterm>
8384 <envar>PGGSSDELEGATION</envar> behaves the same as the <xref
8385 linkend="libpq-connect-gssdelegation"/> connection parameter.
8386 </para>
8387 </listitem>
8389 <listitem>
8390 <para>
8391 <indexterm>
8392 <primary><envar>PGCONNECT_TIMEOUT</envar></primary>
8393 </indexterm>
8394 <envar>PGCONNECT_TIMEOUT</envar> behaves the same as the <xref
8395 linkend="libpq-connect-connect-timeout"/> connection parameter.
8396 </para>
8397 </listitem>
8399 <listitem>
8400 <para>
8401 <indexterm>
8402 <primary><envar>PGCLIENTENCODING</envar></primary>
8403 </indexterm>
8404 <envar>PGCLIENTENCODING</envar> behaves the same as the <xref
8405 linkend="libpq-connect-client-encoding"/> connection parameter.
8406 </para>
8407 </listitem>
8409 <listitem>
8410 <para>
8411 <indexterm>
8412 <primary><envar>PGTARGETSESSIONATTRS</envar></primary>
8413 </indexterm>
8414 <envar>PGTARGETSESSIONATTRS</envar> behaves the same as the <xref
8415 linkend="libpq-connect-target-session-attrs"/> connection parameter.
8416 </para>
8417 </listitem>
8419 <listitem>
8420 <para>
8421 <indexterm>
8422 <primary><envar>PGLOADBALANCEHOSTS</envar></primary>
8423 </indexterm>
8424 <envar>PGLOADBALANCEHOSTS</envar> behaves the same as the <xref
8425 linkend="libpq-connect-load-balance-hosts"/> connection parameter.
8426 </para>
8427 </listitem>
8428 </itemizedlist>
8429 </para>
8431 <para>
8432 The following environment variables can be used to specify default
8433 behavior for each <productname>PostgreSQL</productname> session. (See
8434 also the <xref linkend="sql-alterrole"/>
8435 and <xref linkend="sql-alterdatabase"/>
8436 commands for ways to set default behavior on a per-user or per-database
8437 basis.)
8439 <itemizedlist>
8440 <listitem>
8441 <para>
8442 <indexterm>
8443 <primary><envar>PGDATESTYLE</envar></primary>
8444 </indexterm>
8445 <envar>PGDATESTYLE</envar> sets the default style of date/time
8446 representation. (Equivalent to <literal>SET datestyle TO
8447 ...</literal>.)
8448 </para>
8449 </listitem>
8451 <listitem>
8452 <para>
8453 <indexterm>
8454 <primary><envar>PGTZ</envar></primary>
8455 </indexterm>
8456 <envar>PGTZ</envar> sets the default time zone. (Equivalent to
8457 <literal>SET timezone TO ...</literal>.)
8458 </para>
8459 </listitem>
8461 <listitem>
8462 <para>
8463 <indexterm>
8464 <primary><envar>PGGEQO</envar></primary>
8465 </indexterm>
8466 <envar>PGGEQO</envar> sets the default mode for the genetic query
8467 optimizer. (Equivalent to <literal>SET geqo TO ...</literal>.)
8468 </para>
8469 </listitem>
8470 </itemizedlist>
8472 Refer to the <acronym>SQL</acronym> command <xref linkend="sql-set"/>
8473 for information on correct values for these
8474 environment variables.
8475 </para>
8477 <para>
8478 The following environment variables determine internal behavior of
8479 <application>libpq</application>; they override compiled-in defaults.
8481 <itemizedlist>
8482 <listitem>
8483 <para>
8484 <indexterm>
8485 <primary><envar>PGSYSCONFDIR</envar></primary>
8486 </indexterm>
8487 <envar>PGSYSCONFDIR</envar> sets the directory containing the
8488 <filename>pg_service.conf</filename> file and in a future version
8489 possibly other system-wide configuration files.
8490 </para>
8491 </listitem>
8493 <listitem>
8494 <para>
8495 <indexterm>
8496 <primary><envar>PGLOCALEDIR</envar></primary>
8497 </indexterm>
8498 <envar>PGLOCALEDIR</envar> sets the directory containing the
8499 <literal>locale</literal> files for message localization.
8500 </para>
8501 </listitem>
8502 </itemizedlist>
8503 </para>
8505 </sect1>
8508 <sect1 id="libpq-pgpass">
8509 <title>The Password File</title>
8511 <indexterm zone="libpq-pgpass">
8512 <primary>password file</primary>
8513 </indexterm>
8514 <indexterm zone="libpq-pgpass">
8515 <primary>.pgpass</primary>
8516 </indexterm>
8518 <para>
8519 The file <filename>.pgpass</filename> in a user's home directory can
8520 contain passwords to
8521 be used if the connection requires a password (and no password has been
8522 specified otherwise). On Microsoft Windows the file is named
8523 <filename>%APPDATA%\postgresql\pgpass.conf</filename> (where
8524 <filename>%APPDATA%</filename> refers to the Application Data subdirectory in
8525 the user's profile).
8526 Alternatively, the password file to use can be specified
8527 using the connection parameter <xref linkend="libpq-connect-passfile"/>
8528 or the environment variable <envar>PGPASSFILE</envar>.
8529 </para>
8531 <para>
8532 This file should contain lines of the following format:
8533 <synopsis>
8534 <replaceable>hostname</replaceable>:<replaceable>port</replaceable>:<replaceable>database</replaceable>:<replaceable>username</replaceable>:<replaceable>password</replaceable>
8535 </synopsis>
8536 (You can add a reminder comment to the file by copying the line above and
8537 preceding it with <literal>#</literal>.)
8538 Each of the first four fields can be a literal value, or
8539 <literal>*</literal>, which matches anything. The password field from
8540 the first line that matches the current connection parameters will be
8541 used. (Therefore, put more-specific entries first when you are using
8542 wildcards.) If an entry needs to contain <literal>:</literal> or
8543 <literal>\</literal>, escape this character with <literal>\</literal>.
8544 The host name field is matched to the <literal>host</literal> connection
8545 parameter if that is specified, otherwise to
8546 the <literal>hostaddr</literal> parameter if that is specified; if neither
8547 are given then the host name <literal>localhost</literal> is searched for.
8548 The host name <literal>localhost</literal> is also searched for when
8549 the connection is a Unix-domain socket connection and
8550 the <literal>host</literal> parameter
8551 matches <application>libpq</application>'s default socket directory path.
8552 In a standby server, a database field of <literal>replication</literal>
8553 matches streaming replication connections made to the primary server.
8554 The database field is of limited usefulness otherwise, because users have
8555 the same password for all databases in the same cluster.
8556 </para>
8558 <para>
8559 On Unix systems, the permissions on a password file must
8560 disallow any access to world or group; achieve this by a command such as
8561 <command>chmod 0600 ~/.pgpass</command>. If the permissions are less
8562 strict than this, the file will be ignored. On Microsoft Windows, it
8563 is assumed that the file is stored in a directory that is secure, so
8564 no special permissions check is made.
8565 </para>
8566 </sect1>
8569 <sect1 id="libpq-pgservice">
8570 <title>The Connection Service File</title>
8572 <indexterm zone="libpq-pgservice">
8573 <primary>connection service file</primary>
8574 </indexterm>
8575 <indexterm zone="libpq-pgservice">
8576 <primary>pg_service.conf</primary>
8577 </indexterm>
8578 <indexterm zone="libpq-pgservice">
8579 <primary>.pg_service.conf</primary>
8580 </indexterm>
8582 <para>
8583 The connection service file allows libpq connection parameters to be
8584 associated with a single service name. That service name can then be
8585 specified in a libpq connection string, and the associated settings will be
8586 used. This allows connection parameters to be modified without requiring
8587 a recompile of the libpq-using application. The service name can also be
8588 specified using the <envar>PGSERVICE</envar> environment variable.
8589 </para>
8591 <para>
8592 Service names can be defined in either a per-user service file or a
8593 system-wide file. If the same service name exists in both the user
8594 and the system file, the user file takes precedence.
8595 By default, the per-user service file is named
8596 <filename>~/.pg_service.conf</filename>.
8597 On Microsoft Windows, it is named
8598 <filename>%APPDATA%\postgresql\.pg_service.conf</filename> (where
8599 <filename>%APPDATA%</filename> refers to the Application Data subdirectory
8600 in the user's profile). A different file name can be specified by
8601 setting the environment variable <envar>PGSERVICEFILE</envar>.
8602 The system-wide file is named <filename>pg_service.conf</filename>.
8603 By default it is sought in the <filename>etc</filename> directory
8604 of the <productname>PostgreSQL</productname> installation
8605 (use <literal>pg_config --sysconfdir</literal> to identify this
8606 directory precisely). Another directory, but not a different file
8607 name, can be specified by setting the environment variable
8608 <envar>PGSYSCONFDIR</envar>.
8609 </para>
8611 <para>
8612 Either service file uses an <quote>INI file</quote> format where the section
8613 name is the service name and the parameters are connection
8614 parameters; see <xref linkend="libpq-paramkeywords"/> for a list. For
8615 example:
8616 <programlisting>
8617 # comment
8618 [mydb]
8619 host=somehost
8620 port=5433
8621 user=admin
8622 </programlisting>
8623 An example file is provided in
8624 the <productname>PostgreSQL</productname> installation at
8625 <filename>share/pg_service.conf.sample</filename>.
8626 </para>
8628 <para>
8629 Connection parameters obtained from a service file are combined with
8630 parameters obtained from other sources. A service file setting
8631 overrides the corresponding environment variable, and in turn can be
8632 overridden by a value given directly in the connection string.
8633 For example, using the above service file, a connection string
8634 <literal>service=mydb port=5434</literal> will use
8635 host <literal>somehost</literal>, port <literal>5434</literal>,
8636 user <literal>admin</literal>, and other parameters as set by
8637 environment variables or built-in defaults.
8638 </para>
8639 </sect1>
8642 <sect1 id="libpq-ldap">
8643 <title>LDAP Lookup of Connection Parameters</title>
8645 <indexterm zone="libpq-ldap">
8646 <primary>LDAP connection parameter lookup</primary>
8647 </indexterm>
8649 <para>
8650 If <application>libpq</application> has been compiled with LDAP support (option
8651 <literal><option>--with-ldap</option></literal> for <command>configure</command>)
8652 it is possible to retrieve connection options like <literal>host</literal>
8653 or <literal>dbname</literal> via LDAP from a central server.
8654 The advantage is that if the connection parameters for a database change,
8655 the connection information doesn't have to be updated on all client machines.
8656 </para>
8658 <para>
8659 LDAP connection parameter lookup uses the connection service file
8660 <filename>pg_service.conf</filename> (see <xref
8661 linkend="libpq-pgservice"/>). A line in a
8662 <filename>pg_service.conf</filename> stanza that starts with
8663 <literal>ldap://</literal> will be recognized as an LDAP URL and an
8664 LDAP query will be performed. The result must be a list of
8665 <literal>keyword = value</literal> pairs which will be used to set
8666 connection options. The URL must conform to
8667 <ulink url="https://tools.ietf.org/html/rfc1959">RFC 1959</ulink>
8668 and be of the form
8669 <synopsis>
8670 ldap://[<replaceable>hostname</replaceable>[:<replaceable>port</replaceable>]]/<replaceable>search_base</replaceable>?<replaceable>attribute</replaceable>?<replaceable>search_scope</replaceable>?<replaceable>filter</replaceable>
8671 </synopsis>
8672 where <replaceable>hostname</replaceable> defaults to
8673 <literal>localhost</literal> and <replaceable>port</replaceable>
8674 defaults to 389.
8675 </para>
8677 <para>
8678 Processing of <filename>pg_service.conf</filename> is terminated after
8679 a successful LDAP lookup, but is continued if the LDAP server cannot
8680 be contacted. This is to provide a fallback with further LDAP URL
8681 lines that point to different LDAP servers, classical <literal>keyword
8682 = value</literal> pairs, or default connection options. If you would
8683 rather get an error message in this case, add a syntactically incorrect
8684 line after the LDAP URL.
8685 </para>
8687 <para>
8688 A sample LDAP entry that has been created with the LDIF file
8689 <programlisting>
8690 version:1
8691 dn:cn=mydatabase,dc=mycompany,dc=com
8692 changetype:add
8693 objectclass:top
8694 objectclass:device
8695 cn:mydatabase
8696 description:host=dbserver.mycompany.com
8697 description:port=5439
8698 description:dbname=mydb
8699 description:user=mydb_user
8700 description:sslmode=require
8701 </programlisting>
8702 might be queried with the following LDAP URL:
8703 <programlisting>
8704 ldap://ldap.mycompany.com/dc=mycompany,dc=com?description?one?(cn=mydatabase)
8705 </programlisting>
8706 </para>
8708 <para>
8709 You can also mix regular service file entries with LDAP lookups.
8710 A complete example for a stanza in <filename>pg_service.conf</filename>
8711 would be:
8712 <programlisting>
8713 # only host and port are stored in LDAP, specify dbname and user explicitly
8714 [customerdb]
8715 dbname=customer
8716 user=appuser
8717 ldap://ldap.acme.com/cn=dbserver,cn=hosts?pgconnectinfo?base?(objectclass=*)
8718 </programlisting>
8719 </para>
8721 </sect1>
8724 <sect1 id="libpq-ssl">
8725 <title>SSL Support</title>
8727 <indexterm zone="libpq-ssl">
8728 <primary>SSL</primary>
8729 <secondary>TLS</secondary>
8730 </indexterm>
8732 <para>
8733 <productname>PostgreSQL</productname> has native support for using <acronym>SSL</acronym>
8734 connections to encrypt client/server communications using
8735 <acronym>TLS</acronym> protocols for increased security.
8736 See <xref linkend="ssl-tcp"/> for details about the server-side
8737 <acronym>SSL</acronym> functionality.
8738 </para>
8740 <para>
8741 <application>libpq</application> reads the system-wide
8742 <productname>OpenSSL</productname> configuration file. By default, this
8743 file is named <filename>openssl.cnf</filename> and is located in the
8744 directory reported by <literal>openssl version -d</literal>. This default
8745 can be overridden by setting environment variable
8746 <envar>OPENSSL_CONF</envar> to the name of the desired configuration
8747 file.
8748 </para>
8750 <sect2 id="libq-ssl-certificates">
8751 <title>Client Verification of Server Certificates</title>
8753 <para>
8754 By default, <productname>PostgreSQL</productname> will not perform any verification of
8755 the server certificate. This means that it is possible to spoof the server
8756 identity (for example by modifying a DNS record or by taking over the server
8757 IP address) without the client knowing. In order to prevent spoofing,
8758 the client must be able to verify the server's identity via a chain of
8759 trust. A chain of trust is established by placing a root (self-signed)
8760 certificate authority (<acronym>CA</acronym>) certificate on one
8761 computer and a leaf certificate <emphasis>signed</emphasis> by the
8762 root certificate on another computer. It is also possible to use an
8763 <quote>intermediate</quote> certificate which is signed by the root
8764 certificate and signs leaf certificates.
8765 </para>
8767 <para>
8768 To allow the client to verify the identity of the server, place a root
8769 certificate on the client and a leaf certificate signed by the root
8770 certificate on the server. To allow the server to verify the identity
8771 of the client, place a root certificate on the server and a leaf
8772 certificate signed by the root certificate on the client. One or more
8773 intermediate certificates (usually stored with the leaf certificate)
8774 can also be used to link the leaf certificate to the root certificate.
8775 </para>
8777 <para>
8778 Once a chain of trust has been established, there are two ways for
8779 the client to validate the leaf certificate sent by the server.
8780 If the parameter <literal>sslmode</literal> is set to <literal>verify-ca</literal>,
8781 libpq will verify that the server is trustworthy by checking the
8782 certificate chain up to the root certificate stored on the client.
8783 If <literal>sslmode</literal> is set to <literal>verify-full</literal>,
8784 libpq will <emphasis>also</emphasis> verify that the server host
8785 name matches the name stored in the server certificate. The
8786 SSL connection will fail if the server certificate cannot be
8787 verified. <literal>verify-full</literal> is recommended in most
8788 security-sensitive environments.
8789 </para>
8791 <para>
8792 In <literal>verify-full</literal> mode, the host name is matched against the
8793 certificate's Subject Alternative Name attribute(s) (SAN), or against the
8794 Common Name attribute if no SAN of type <literal>dNSName</literal> is
8795 present. If the certificate's name attribute starts with an asterisk
8796 (<literal>*</literal>), the asterisk will be treated as
8797 a wildcard, which will match all characters <emphasis>except</emphasis> a dot
8798 (<literal>.</literal>). This means the certificate will not match subdomains.
8799 If the connection is made using an IP address instead of a host name, the
8800 IP address will be matched (without doing any DNS lookups) against SANs of
8801 type <literal>iPAddress</literal> or <literal>dNSName</literal>. If no
8802 <literal>iPAddress</literal> SAN is present and no
8803 matching <literal>dNSName</literal> SAN is present, the host IP address is
8804 matched against the Common Name attribute.
8805 </para>
8807 <note>
8808 <para>
8809 For backward compatibility with earlier versions of PostgreSQL, the host
8810 IP address is verified in a manner different
8811 from <ulink url="https://tools.ietf.org/html/rfc6125">RFC 6125</ulink>.
8812 The host IP address is always matched against <literal>dNSName</literal>
8813 SANs as well as <literal>iPAddress</literal> SANs, and can be matched
8814 against the Common Name attribute if no relevant SANs exist.
8815 </para>
8816 </note>
8818 <para>
8819 To allow server certificate verification, one or more root certificates
8820 must be placed in the file <filename>~/.postgresql/root.crt</filename>
8821 in the user's home directory. (On Microsoft Windows the file is named
8822 <filename>%APPDATA%\postgresql\root.crt</filename>.) Intermediate
8823 certificates should also be added to the file if they are needed to link
8824 the certificate chain sent by the server to the root certificates
8825 stored on the client.
8826 </para>
8828 <para>
8829 Certificate Revocation List (CRL) entries are also checked
8830 if the file <filename>~/.postgresql/root.crl</filename> exists
8831 (<filename>%APPDATA%\postgresql\root.crl</filename> on Microsoft
8832 Windows).
8833 </para>
8835 <para>
8836 The location of the root certificate file and the CRL can be changed by
8837 setting
8838 the connection parameters <literal>sslrootcert</literal> and <literal>sslcrl</literal>
8839 or the environment variables <envar>PGSSLROOTCERT</envar> and <envar>PGSSLCRL</envar>.
8840 <literal>sslcrldir</literal> or the environment variable <envar>PGSSLCRLDIR</envar>
8841 can also be used to specify a directory containing CRL files.
8842 </para>
8844 <note>
8845 <para>
8846 For backwards compatibility with earlier versions of PostgreSQL, if a
8847 root CA file exists, the behavior of
8848 <literal>sslmode</literal>=<literal>require</literal> will be the same
8849 as that of <literal>verify-ca</literal>, meaning the server certificate
8850 is validated against the CA. Relying on this behavior is discouraged,
8851 and applications that need certificate validation should always use
8852 <literal>verify-ca</literal> or <literal>verify-full</literal>.
8853 </para>
8854 </note>
8855 </sect2>
8857 <sect2 id="libpq-ssl-clientcert">
8858 <title>Client Certificates</title>
8860 <para>
8861 If the server attempts to verify the identity of the
8862 client by requesting the client's leaf certificate,
8863 <application>libpq</application> will send the certificate(s) stored in
8864 file <filename>~/.postgresql/postgresql.crt</filename> in the user's home
8865 directory. The certificates must chain to the root certificate trusted
8866 by the server. A matching
8867 private key file <filename>~/.postgresql/postgresql.key</filename> must also
8868 be present.
8869 On Microsoft Windows these files are named
8870 <filename>%APPDATA%\postgresql\postgresql.crt</filename> and
8871 <filename>%APPDATA%\postgresql\postgresql.key</filename>.
8872 The location of the certificate and key files can be overridden by the
8873 connection parameters <literal>sslcert</literal>
8874 and <literal>sslkey</literal>, or by the
8875 environment variables <envar>PGSSLCERT</envar> and <envar>PGSSLKEY</envar>.
8876 </para>
8878 <para>
8879 On Unix systems, the permissions on the private key file must disallow
8880 any access to world or group; achieve this by a command such as
8881 <command>chmod 0600 ~/.postgresql/postgresql.key</command>.
8882 Alternatively, the file can be owned by root and have group read access
8883 (that is, <literal>0640</literal> permissions). That setup is intended
8884 for installations where certificate and key files are managed by the
8885 operating system. The user of <application>libpq</application> should
8886 then be made a member of the group that has access to those certificate
8887 and key files. (On Microsoft Windows, there is no file permissions
8888 check, since the <filename>%APPDATA%\postgresql</filename> directory is
8889 presumed secure.)
8890 </para>
8892 <para>
8893 The first certificate in <filename>postgresql.crt</filename> must be the
8894 client's certificate because it must match the client's private key.
8895 <quote>Intermediate</quote> certificates can be optionally appended
8896 to the file &mdash; doing so avoids requiring storage of intermediate
8897 certificates on the server (<xref linkend="guc-ssl-ca-file"/>).
8898 </para>
8900 <para>
8901 The certificate and key may be in PEM or ASN.1 DER format.
8902 </para>
8904 <para>
8905 The key may be
8906 stored in cleartext or encrypted with a passphrase using any algorithm
8907 supported by <productname>OpenSSL</productname>, like AES-128. If the key
8908 is stored encrypted, then the passphrase may be provided in the
8909 <xref linkend="libpq-connect-sslpassword"/> connection option. If an
8910 encrypted key is supplied and the <literal>sslpassword</literal> option
8911 is absent or blank, a password will be prompted for interactively by
8912 <productname>OpenSSL</productname> with a
8913 <literal>Enter PEM pass phrase:</literal> prompt if a TTY is available.
8914 Applications can override the client certificate prompt and the handling
8915 of the <literal>sslpassword</literal> parameter by supplying their own
8916 key password callback; see
8917 <xref linkend="libpq-pqsetsslkeypasshook-openssl"/>.
8918 </para>
8920 <para>
8921 For instructions on creating certificates, see <xref
8922 linkend="ssl-certificate-creation"/>.
8923 </para>
8924 </sect2>
8926 <sect2 id="libpq-ssl-protection">
8927 <title>Protection Provided in Different Modes</title>
8929 <para>
8930 The different values for the <literal>sslmode</literal> parameter provide different
8931 levels of protection. SSL can provide
8932 protection against three types of attacks:
8934 <variablelist>
8935 <varlistentry>
8936 <term>Eavesdropping</term>
8937 <listitem>
8938 <para>If a third party can examine the network traffic between the
8939 client and the server, it can read both connection information (including
8940 the user name and password) and the data that is passed. <acronym>SSL</acronym>
8941 uses encryption to prevent this.
8942 </para>
8943 </listitem>
8944 </varlistentry>
8946 <varlistentry>
8947 <term>Man-in-the-middle (<acronym>MITM</acronym>)</term>
8948 <listitem>
8949 <para>If a third party can modify the data while passing between the
8950 client and server, it can pretend to be the server and therefore see and
8951 modify data <emphasis>even if it is encrypted</emphasis>. The third party can then
8952 forward the connection information and data to the original server,
8953 making it impossible to detect this attack. Common vectors to do this
8954 include DNS poisoning and address hijacking, whereby the client is directed
8955 to a different server than intended. There are also several other
8956 attack methods that can accomplish this. <acronym>SSL</acronym> uses certificate
8957 verification to prevent this, by authenticating the server to the client.
8958 </para>
8959 </listitem>
8960 </varlistentry>
8962 <varlistentry>
8963 <term>Impersonation</term>
8964 <listitem>
8965 <para>If a third party can pretend to be an authorized client, it can
8966 simply access data it should not have access to. Typically this can
8967 happen through insecure password management. <acronym>SSL</acronym> uses
8968 client certificates to prevent this, by making sure that only holders
8969 of valid certificates can access the server.
8970 </para>
8971 </listitem>
8972 </varlistentry>
8973 </variablelist>
8974 </para>
8976 <para>
8977 For a connection to be known SSL-secured, SSL usage must be configured
8978 on <emphasis>both the client and the server</emphasis> before the connection
8979 is made. If it is only configured on the server, the client may end up
8980 sending sensitive information (e.g., passwords) before
8981 it knows that the server requires high security. In libpq, secure
8982 connections can be ensured
8983 by setting the <literal>sslmode</literal> parameter to <literal>verify-full</literal> or
8984 <literal>verify-ca</literal>, and providing the system with a root certificate to
8985 verify against. This is analogous to using an <literal>https</literal>
8986 <acronym>URL</acronym> for encrypted web browsing.
8987 </para>
8989 <para>
8990 Once the server has been authenticated, the client can pass sensitive data.
8991 This means that up until this point, the client does not need to know if
8992 certificates will be used for authentication, making it safe to specify that
8993 only in the server configuration.
8994 </para>
8996 <para>
8997 All <acronym>SSL</acronym> options carry overhead in the form of encryption and
8998 key-exchange, so there is a trade-off that has to be made between performance
8999 and security. <xref linkend="libpq-ssl-sslmode-statements"/>
9000 illustrates the risks the different <literal>sslmode</literal> values
9001 protect against, and what statement they make about security and overhead.
9002 </para>
9004 <table id="libpq-ssl-sslmode-statements">
9005 <title>SSL Mode Descriptions</title>
9006 <tgroup cols="4">
9007 <colspec colname="col1" colwidth="1*"/>
9008 <colspec colname="col2" colwidth="1*"/>
9009 <colspec colname="col3" colwidth="1*"/>
9010 <colspec colname="col4" colwidth="2*"/>
9011 <thead>
9012 <row>
9013 <entry><literal>sslmode</literal></entry>
9014 <entry>Eavesdropping protection</entry>
9015 <entry><acronym>MITM</acronym> protection</entry>
9016 <entry>Statement</entry>
9017 </row>
9018 </thead>
9020 <tbody>
9021 <row>
9022 <entry><literal>disable</literal></entry>
9023 <entry>No</entry>
9024 <entry>No</entry>
9025 <entry>I don't care about security, and I don't want to pay the overhead
9026 of encryption.
9027 </entry>
9028 </row>
9030 <row>
9031 <entry><literal>allow</literal></entry>
9032 <entry>Maybe</entry>
9033 <entry>No</entry>
9034 <entry>I don't care about security, but I will pay the overhead of
9035 encryption if the server insists on it.
9036 </entry>
9037 </row>
9039 <row>
9040 <entry><literal>prefer</literal></entry>
9041 <entry>Maybe</entry>
9042 <entry>No</entry>
9043 <entry>I don't care about encryption, but I wish to pay the overhead of
9044 encryption if the server supports it.
9045 </entry>
9046 </row>
9048 <row>
9049 <entry><literal>require</literal></entry>
9050 <entry>Yes</entry>
9051 <entry>No</entry>
9052 <entry>I want my data to be encrypted, and I accept the overhead. I trust
9053 that the network will make sure I always connect to the server I want.
9054 </entry>
9055 </row>
9057 <row>
9058 <entry><literal>verify-ca</literal></entry>
9059 <entry>Yes</entry>
9060 <entry>Depends on CA policy</entry>
9061 <entry>I want my data encrypted, and I accept the overhead. I want to be
9062 sure that I connect to a server that I trust.
9063 </entry>
9064 </row>
9066 <row>
9067 <entry><literal>verify-full</literal></entry>
9068 <entry>Yes</entry>
9069 <entry>Yes</entry>
9070 <entry>I want my data encrypted, and I accept the overhead. I want to be
9071 sure that I connect to a server I trust, and that it's the one I
9072 specify.
9073 </entry>
9074 </row>
9076 </tbody>
9077 </tgroup>
9078 </table>
9080 <para>
9081 The difference between <literal>verify-ca</literal> and <literal>verify-full</literal>
9082 depends on the policy of the root <acronym>CA</acronym>. If a public
9083 <acronym>CA</acronym> is used, <literal>verify-ca</literal> allows connections to a server
9084 that <emphasis>somebody else</emphasis> may have registered with the <acronym>CA</acronym>.
9085 In this case, <literal>verify-full</literal> should always be used. If
9086 a local <acronym>CA</acronym> is used, or even a self-signed certificate, using
9087 <literal>verify-ca</literal> often provides enough protection.
9088 </para>
9090 <para>
9091 The default value for <literal>sslmode</literal> is <literal>prefer</literal>. As is shown
9092 in the table, this makes no sense from a security point of view, and it only
9093 promises performance overhead if possible. It is only provided as the default
9094 for backward compatibility, and is not recommended in secure deployments.
9095 </para>
9097 </sect2>
9099 <sect2 id="libpq-ssl-fileusage">
9100 <title>SSL Client File Usage</title>
9102 <para>
9103 <xref linkend="libpq-ssl-file-usage"/> summarizes the files that are
9104 relevant to the SSL setup on the client.
9105 </para>
9107 <table id="libpq-ssl-file-usage">
9108 <title>Libpq/Client SSL File Usage</title>
9109 <tgroup cols="3">
9110 <thead>
9111 <row>
9112 <entry>File</entry>
9113 <entry>Contents</entry>
9114 <entry>Effect</entry>
9115 </row>
9116 </thead>
9118 <tbody>
9120 <row>
9121 <entry><filename>~/.postgresql/postgresql.crt</filename></entry>
9122 <entry>client certificate</entry>
9123 <entry>sent to server</entry>
9124 </row>
9126 <row>
9127 <entry><filename>~/.postgresql/postgresql.key</filename></entry>
9128 <entry>client private key</entry>
9129 <entry>proves client certificate sent by owner; does not indicate
9130 certificate owner is trustworthy</entry>
9131 </row>
9133 <row>
9134 <entry><filename>~/.postgresql/root.crt</filename></entry>
9135 <entry>trusted certificate authorities</entry>
9136 <entry>checks that server certificate is signed by a trusted certificate
9137 authority</entry>
9138 </row>
9140 <row>
9141 <entry><filename>~/.postgresql/root.crl</filename></entry>
9142 <entry>certificates revoked by certificate authorities</entry>
9143 <entry>server certificate must not be on this list</entry>
9144 </row>
9146 </tbody>
9147 </tgroup>
9148 </table>
9149 </sect2>
9151 <sect2 id="libpq-ssl-initialize">
9152 <title>SSL Library Initialization</title>
9154 <para>
9155 If your application initializes <literal>libssl</literal> and/or
9156 <literal>libcrypto</literal> libraries and <application>libpq</application>
9157 is built with <acronym>SSL</acronym> support, you should call
9158 <xref linkend="libpq-PQinitOpenSSL"/> to tell <application>libpq</application>
9159 that the <literal>libssl</literal> and/or <literal>libcrypto</literal> libraries
9160 have been initialized by your application, so that
9161 <application>libpq</application> will not also initialize those libraries.
9162 However, this is unnecessary when using <productname>OpenSSL</productname>
9163 version 1.1.0 or later, as duplicate initializations are no longer problematic.
9164 </para>
9166 <para>
9167 <variablelist>
9168 <varlistentry id="libpq-PQinitOpenSSL">
9169 <term><function>PQinitOpenSSL</function><indexterm><primary>PQinitOpenSSL</primary></indexterm></term>
9171 <listitem>
9172 <para>
9173 Allows applications to select which security libraries to initialize.
9174 <synopsis>
9175 void PQinitOpenSSL(int do_ssl, int do_crypto);
9176 </synopsis>
9177 </para>
9179 <para>
9180 When <parameter>do_ssl</parameter> is non-zero, <application>libpq</application>
9181 will initialize the <productname>OpenSSL</productname> library before first
9182 opening a database connection. When <parameter>do_crypto</parameter> is
9183 non-zero, the <literal>libcrypto</literal> library will be initialized. By
9184 default (if <xref linkend="libpq-PQinitOpenSSL"/> is not called), both libraries
9185 are initialized. When SSL support is not compiled in, this function is
9186 present but does nothing.
9187 </para>
9189 <para>
9190 If your application uses and initializes either <productname>OpenSSL</productname>
9191 or its underlying <literal>libcrypto</literal> library, you <emphasis>must</emphasis>
9192 call this function with zeroes for the appropriate parameter(s)
9193 before first opening a database connection. Also be sure that you
9194 have done that initialization before opening a database connection.
9195 </para>
9196 </listitem>
9197 </varlistentry>
9199 <varlistentry id="libpq-PQinitSSL">
9200 <term><function>PQinitSSL</function><indexterm><primary>PQinitSSL</primary></indexterm></term><listitem>
9201 <para>
9202 Allows applications to select which security libraries to initialize.
9203 <synopsis>
9204 void PQinitSSL(int do_ssl);
9205 </synopsis>
9206 </para>
9208 <para>
9209 This function is equivalent to
9210 <literal>PQinitOpenSSL(do_ssl, do_ssl)</literal>.
9211 It is sufficient for applications that initialize both or neither
9212 of <productname>OpenSSL</productname> and <literal>libcrypto</literal>.
9213 </para>
9215 <para>
9216 <xref linkend="libpq-PQinitSSL"/> has been present since
9217 <productname>PostgreSQL</productname> 8.0, while <xref linkend="libpq-PQinitOpenSSL"/>
9218 was added in <productname>PostgreSQL</productname> 8.4, so <xref linkend="libpq-PQinitSSL"/>
9219 might be preferable for applications that need to work with older
9220 versions of <application>libpq</application>.
9221 </para>
9222 </listitem>
9223 </varlistentry>
9224 </variablelist>
9225 </para>
9226 </sect2>
9228 </sect1>
9231 <sect1 id="libpq-threading">
9232 <title>Behavior in Threaded Programs</title>
9234 <indexterm zone="libpq-threading">
9235 <primary>threads</primary>
9236 <secondary>with libpq</secondary>
9237 </indexterm>
9239 <para>
9240 As of version 17, <application>libpq</application> is always reentrant and thread-safe.
9241 However, one restriction is that no two threads attempt to manipulate
9242 the same <structname>PGconn</structname> object at the same time. In particular,
9243 you cannot issue concurrent commands from different threads through
9244 the same connection object. (If you need to run concurrent commands,
9245 use multiple connections.)
9246 </para>
9248 <para>
9249 <structname>PGresult</structname> objects are normally read-only after creation,
9250 and so can be passed around freely between threads. However, if you use
9251 any of the <structname>PGresult</structname>-modifying functions described in
9252 <xref linkend="libpq-misc"/> or <xref linkend="libpq-events"/>, it's up
9253 to you to avoid concurrent operations on the same <structname>PGresult</structname>,
9254 too.
9255 </para>
9257 <para>
9258 In earlier versions, <application>libpq</application> could be compiled
9259 with or without thread support, depending on compiler options. This
9260 function allows the querying of <application>libpq</application>'s
9261 thread-safe status:
9262 </para>
9264 <variablelist>
9265 <varlistentry id="libpq-PQisthreadsafe">
9266 <term><function>PQisthreadsafe</function><indexterm><primary>PQisthreadsafe</primary></indexterm></term>
9268 <listitem>
9269 <para>
9270 Returns the thread safety status of the
9271 <application>libpq</application> library.
9272 <synopsis>
9273 int PQisthreadsafe();
9274 </synopsis>
9275 </para>
9277 <para>
9278 Returns 1 if the <application>libpq</application> is thread-safe
9279 and 0 if it is not. Always returns 1 on version 17 and above.
9280 </para>
9281 </listitem>
9282 </varlistentry>
9283 </variablelist>
9285 <para>
9286 The deprecated functions <xref linkend="libpq-PQrequestCancel"/> and
9287 <xref linkend="libpq-PQoidStatus"/> are not thread-safe and should not be
9288 used in multithread programs. <xref linkend="libpq-PQrequestCancel"/>
9289 can be replaced by <xref linkend="libpq-PQcancel"/>.
9290 <xref linkend="libpq-PQoidStatus"/> can be replaced by
9291 <xref linkend="libpq-PQoidValue"/>.
9292 </para>
9294 <para>
9295 If you are using Kerberos inside your application (in addition to inside
9296 <application>libpq</application>), you will need to do locking around
9297 Kerberos calls because Kerberos functions are not thread-safe. See
9298 function <function>PQregisterThreadLock</function> in the
9299 <application>libpq</application> source code for a way to do cooperative
9300 locking between <application>libpq</application> and your application.
9301 </para>
9302 </sect1>
9305 <sect1 id="libpq-build">
9306 <title>Building <application>libpq</application> Programs</title>
9308 <indexterm zone="libpq-build">
9309 <primary>compiling</primary>
9310 <secondary>libpq applications</secondary>
9311 </indexterm>
9313 <para>
9314 To build (i.e., compile and link) a program using
9315 <application>libpq</application> you need to do all of the following
9316 things:
9318 <itemizedlist>
9319 <listitem>
9320 <para>
9321 Include the <filename>libpq-fe.h</filename> header file:
9322 <programlisting>
9323 #include &lt;libpq-fe.h&gt;
9324 </programlisting>
9325 If you failed to do that then you will normally get error messages
9326 from your compiler similar to:
9327 <screen>
9328 foo.c: In function `main':
9329 foo.c:34: `PGconn' undeclared (first use in this function)
9330 foo.c:35: `PGresult' undeclared (first use in this function)
9331 foo.c:54: `CONNECTION_BAD' undeclared (first use in this function)
9332 foo.c:68: `PGRES_COMMAND_OK' undeclared (first use in this function)
9333 foo.c:95: `PGRES_TUPLES_OK' undeclared (first use in this function)
9334 </screen>
9335 </para>
9336 </listitem>
9338 <listitem>
9339 <para>
9340 Point your compiler to the directory where the <productname>PostgreSQL</productname> header
9341 files were installed, by supplying the
9342 <literal>-I<replaceable>directory</replaceable></literal> option
9343 to your compiler. (In some cases the compiler will look into
9344 the directory in question by default, so you can omit this
9345 option.) For instance, your compile command line could look
9346 like:
9347 <programlisting>
9348 cc -c -I/usr/local/pgsql/include testprog.c
9349 </programlisting>
9350 If you are using makefiles then add the option to the
9351 <varname>CPPFLAGS</varname> variable:
9352 <programlisting>
9353 CPPFLAGS += -I/usr/local/pgsql/include
9354 </programlisting>
9355 </para>
9357 <para>
9358 If there is any chance that your program might be compiled by
9359 other users then you should not hardcode the directory location
9360 like that. Instead, you can run the utility
9361 <command>pg_config</command><indexterm><primary>pg_config</primary><secondary
9362 sortas="libpq">with libpq</secondary></indexterm> to find out where the header
9363 files are on the local system:
9364 <screen>
9365 <prompt>$</prompt> pg_config --includedir
9366 <computeroutput>/usr/local/include</computeroutput>
9367 </screen>
9368 </para>
9370 <para>
9371 If you
9372 have <command>pkg-config</command><indexterm><primary>pkg-config</primary><secondary sortas="libpq">with
9373 libpq</secondary></indexterm> installed, you can run instead:
9374 <screen>
9375 <prompt>$</prompt> pkg-config --cflags libpq
9376 <computeroutput>-I/usr/local/include</computeroutput>
9377 </screen>
9378 Note that this will already include the <option>-I</option> in front of
9379 the path.
9380 </para>
9382 <para>
9383 Failure to specify the correct option to the compiler will
9384 result in an error message such as:
9385 <screen>
9386 testlibpq.c:8:22: libpq-fe.h: No such file or directory
9387 </screen>
9388 </para>
9389 </listitem>
9391 <listitem>
9392 <para>
9393 When linking the final program, specify the option
9394 <literal>-lpq</literal> so that the <application>libpq</application>
9395 library gets pulled in, as well as the option
9396 <literal>-L<replaceable>directory</replaceable></literal> to point
9397 the compiler to the directory where the
9398 <application>libpq</application> library resides. (Again, the
9399 compiler will search some directories by default.) For maximum
9400 portability, put the <option>-L</option> option before the
9401 <option>-lpq</option> option. For example:
9402 <programlisting>
9403 cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq
9404 </programlisting>
9405 </para>
9407 <para>
9408 You can find out the library directory using
9409 <command>pg_config</command> as well:
9410 <screen>
9411 <prompt>$</prompt> pg_config --libdir
9412 <computeroutput>/usr/local/pgsql/lib</computeroutput>
9413 </screen>
9414 </para>
9416 <para>
9417 Or again use <command>pkg-config</command>:
9418 <screen>
9419 <prompt>$</prompt> pkg-config --libs libpq
9420 <computeroutput>-L/usr/local/pgsql/lib -lpq</computeroutput>
9421 </screen>
9422 Note again that this prints the full options, not only the path.
9423 </para>
9425 <para>
9426 Error messages that point to problems in this area could look like
9427 the following:
9428 <screen>
9429 testlibpq.o: In function `main':
9430 testlibpq.o(.text+0x60): undefined reference to `PQsetdbLogin'
9431 testlibpq.o(.text+0x71): undefined reference to `PQstatus'
9432 testlibpq.o(.text+0xa4): undefined reference to `PQerrorMessage'
9433 </screen>
9434 This means you forgot <option>-lpq</option>.
9435 <screen>
9436 /usr/bin/ld: cannot find -lpq
9437 </screen>
9438 This means you forgot the <option>-L</option> option or did not
9439 specify the right directory.
9440 </para>
9441 </listitem>
9442 </itemizedlist>
9443 </para>
9445 </sect1>
9448 <sect1 id="libpq-example">
9449 <title>Example Programs</title>
9451 <para>
9452 These examples and others can be found in the
9453 directory <filename>src/test/examples</filename> in the source code
9454 distribution.
9455 </para>
9457 <example id="libpq-example-1">
9458 <title><application>libpq</application> Example Program 1</title>
9460 <programlisting>
9461 <![CDATA[
9463 * src/test/examples/testlibpq.c
9466 * testlibpq.c
9468 * Test the C version of libpq, the PostgreSQL frontend library.
9470 #include <stdio.h>
9471 #include <stdlib.h>
9472 #include "libpq-fe.h"
9474 static void
9475 exit_nicely(PGconn *conn)
9477 PQfinish(conn);
9478 exit(1);
9482 main(int argc, char **argv)
9484 const char *conninfo;
9485 PGconn *conn;
9486 PGresult *res;
9487 int nFields;
9488 int i,
9492 * If the user supplies a parameter on the command line, use it as the
9493 * conninfo string; otherwise default to setting dbname=postgres and using
9494 * environment variables or defaults for all other connection parameters.
9496 if (argc > 1)
9497 conninfo = argv[1];
9498 else
9499 conninfo = "dbname = postgres";
9501 /* Make a connection to the database */
9502 conn = PQconnectdb(conninfo);
9504 /* Check to see that the backend connection was successfully made */
9505 if (PQstatus(conn) != CONNECTION_OK)
9507 fprintf(stderr, "%s", PQerrorMessage(conn));
9508 exit_nicely(conn);
9511 /* Set always-secure search path, so malicious users can't take control. */
9512 res = PQexec(conn,
9513 "SELECT pg_catalog.set_config('search_path', '', false)");
9514 if (PQresultStatus(res) != PGRES_TUPLES_OK)
9516 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
9517 PQclear(res);
9518 exit_nicely(conn);
9522 * Should PQclear PGresult whenever it is no longer needed to avoid memory
9523 * leaks
9525 PQclear(res);
9528 * Our test case here involves using a cursor, for which we must be inside
9529 * a transaction block. We could do the whole thing with a single
9530 * PQexec() of "select * from pg_database", but that's too trivial to make
9531 * a good example.
9534 /* Start a transaction block */
9535 res = PQexec(conn, "BEGIN");
9536 if (PQresultStatus(res) != PGRES_COMMAND_OK)
9538 fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn));
9539 PQclear(res);
9540 exit_nicely(conn);
9542 PQclear(res);
9545 * Fetch rows from pg_database, the system catalog of databases
9547 res = PQexec(conn, "DECLARE myportal CURSOR FOR select * from pg_database");
9548 if (PQresultStatus(res) != PGRES_COMMAND_OK)
9550 fprintf(stderr, "DECLARE CURSOR failed: %s", PQerrorMessage(conn));
9551 PQclear(res);
9552 exit_nicely(conn);
9554 PQclear(res);
9556 res = PQexec(conn, "FETCH ALL in myportal");
9557 if (PQresultStatus(res) != PGRES_TUPLES_OK)
9559 fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(conn));
9560 PQclear(res);
9561 exit_nicely(conn);
9564 /* first, print out the attribute names */
9565 nFields = PQnfields(res);
9566 for (i = 0; i < nFields; i++)
9567 printf("%-15s", PQfname(res, i));
9568 printf("\n\n");
9570 /* next, print out the rows */
9571 for (i = 0; i < PQntuples(res); i++)
9573 for (j = 0; j < nFields; j++)
9574 printf("%-15s", PQgetvalue(res, i, j));
9575 printf("\n");
9578 PQclear(res);
9580 /* close the portal ... we don't bother to check for errors ... */
9581 res = PQexec(conn, "CLOSE myportal");
9582 PQclear(res);
9584 /* end the transaction */
9585 res = PQexec(conn, "END");
9586 PQclear(res);
9588 /* close the connection to the database and cleanup */
9589 PQfinish(conn);
9591 return 0;
9594 </programlisting>
9595 </example>
9597 <example id="libpq-example-2">
9598 <title><application>libpq</application> Example Program 2</title>
9600 <programlisting>
9601 <![CDATA[
9603 * src/test/examples/testlibpq2.c
9606 * testlibpq2.c
9607 * Test of the asynchronous notification interface
9609 * Start this program, then from psql in another window do
9610 * NOTIFY TBL2;
9611 * Repeat four times to get this program to exit.
9613 * Or, if you want to get fancy, try this:
9614 * populate a database with the following commands
9615 * (provided in src/test/examples/testlibpq2.sql):
9617 * CREATE SCHEMA TESTLIBPQ2;
9618 * SET search_path = TESTLIBPQ2;
9619 * CREATE TABLE TBL1 (i int4);
9620 * CREATE TABLE TBL2 (i int4);
9621 * CREATE RULE r1 AS ON INSERT TO TBL1 DO
9622 * (INSERT INTO TBL2 VALUES (new.i); NOTIFY TBL2);
9624 * Start this program, then from psql do this four times:
9626 * INSERT INTO TESTLIBPQ2.TBL1 VALUES (10);
9629 #ifdef WIN32
9630 #include <windows.h>
9631 #endif
9632 #include <stdio.h>
9633 #include <stdlib.h>
9634 #include <string.h>
9635 #include <errno.h>
9636 #include <sys/select.h>
9637 #include <sys/time.h>
9638 #include <sys/types.h>
9640 #include "libpq-fe.h"
9642 static void
9643 exit_nicely(PGconn *conn)
9645 PQfinish(conn);
9646 exit(1);
9650 main(int argc, char **argv)
9652 const char *conninfo;
9653 PGconn *conn;
9654 PGresult *res;
9655 PGnotify *notify;
9656 int nnotifies;
9659 * If the user supplies a parameter on the command line, use it as the
9660 * conninfo string; otherwise default to setting dbname=postgres and using
9661 * environment variables or defaults for all other connection parameters.
9663 if (argc > 1)
9664 conninfo = argv[1];
9665 else
9666 conninfo = "dbname = postgres";
9668 /* Make a connection to the database */
9669 conn = PQconnectdb(conninfo);
9671 /* Check to see that the backend connection was successfully made */
9672 if (PQstatus(conn) != CONNECTION_OK)
9674 fprintf(stderr, "%s", PQerrorMessage(conn));
9675 exit_nicely(conn);
9678 /* Set always-secure search path, so malicious users can't take control. */
9679 res = PQexec(conn,
9680 "SELECT pg_catalog.set_config('search_path', '', false)");
9681 if (PQresultStatus(res) != PGRES_TUPLES_OK)
9683 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
9684 PQclear(res);
9685 exit_nicely(conn);
9689 * Should PQclear PGresult whenever it is no longer needed to avoid memory
9690 * leaks
9692 PQclear(res);
9695 * Issue LISTEN command to enable notifications from the rule's NOTIFY.
9697 res = PQexec(conn, "LISTEN TBL2");
9698 if (PQresultStatus(res) != PGRES_COMMAND_OK)
9700 fprintf(stderr, "LISTEN command failed: %s", PQerrorMessage(conn));
9701 PQclear(res);
9702 exit_nicely(conn);
9704 PQclear(res);
9706 /* Quit after four notifies are received. */
9707 nnotifies = 0;
9708 while (nnotifies < 4)
9711 * Sleep until something happens on the connection. We use select(2)
9712 * to wait for input, but you could also use poll() or similar
9713 * facilities.
9715 int sock;
9716 fd_set input_mask;
9718 sock = PQsocket(conn);
9720 if (sock < 0)
9721 break; /* shouldn't happen */
9723 FD_ZERO(&input_mask);
9724 FD_SET(sock, &input_mask);
9726 if (select(sock + 1, &input_mask, NULL, NULL, NULL) < 0)
9728 fprintf(stderr, "select() failed: %s\n", strerror(errno));
9729 exit_nicely(conn);
9732 /* Now check for input */
9733 PQconsumeInput(conn);
9734 while ((notify = PQnotifies(conn)) != NULL)
9736 fprintf(stderr,
9737 "ASYNC NOTIFY of '%s' received from backend PID %d\n",
9738 notify->relname, notify->be_pid);
9739 PQfreemem(notify);
9740 nnotifies++;
9741 PQconsumeInput(conn);
9745 fprintf(stderr, "Done.\n");
9747 /* close the connection to the database and cleanup */
9748 PQfinish(conn);
9750 return 0;
9753 </programlisting>
9754 </example>
9756 <example id="libpq-example-3">
9757 <title><application>libpq</application> Example Program 3</title>
9759 <programlisting>
9760 <![CDATA[
9762 * src/test/examples/testlibpq3.c
9765 * testlibpq3.c
9766 * Test out-of-line parameters and binary I/O.
9768 * Before running this, populate a database with the following commands
9769 * (provided in src/test/examples/testlibpq3.sql):
9771 * CREATE SCHEMA testlibpq3;
9772 * SET search_path = testlibpq3;
9773 * SET standard_conforming_strings = ON;
9774 * CREATE TABLE test1 (i int4, t text, b bytea);
9775 * INSERT INTO test1 values (1, 'joe''s place', '\000\001\002\003\004');
9776 * INSERT INTO test1 values (2, 'ho there', '\004\003\002\001\000');
9778 * The expected output is:
9780 * tuple 0: got
9781 * i = (4 bytes) 1
9782 * t = (11 bytes) 'joe's place'
9783 * b = (5 bytes) \000\001\002\003\004
9785 * tuple 0: got
9786 * i = (4 bytes) 2
9787 * t = (8 bytes) 'ho there'
9788 * b = (5 bytes) \004\003\002\001\000
9791 #ifdef WIN32
9792 #include <windows.h>
9793 #endif
9795 #include <stdio.h>
9796 #include <stdlib.h>
9797 #include <stdint.h>
9798 #include <string.h>
9799 #include <sys/types.h>
9800 #include "libpq-fe.h"
9802 /* for ntohl/htonl */
9803 #include <netinet/in.h>
9804 #include <arpa/inet.h>
9807 static void
9808 exit_nicely(PGconn *conn)
9810 PQfinish(conn);
9811 exit(1);
9815 * This function prints a query result that is a binary-format fetch from
9816 * a table defined as in the comment above. We split it out because the
9817 * main() function uses it twice.
9819 static void
9820 show_binary_results(PGresult *res)
9822 int i,
9824 int i_fnum,
9825 t_fnum,
9826 b_fnum;
9828 /* Use PQfnumber to avoid assumptions about field order in result */
9829 i_fnum = PQfnumber(res, "i");
9830 t_fnum = PQfnumber(res, "t");
9831 b_fnum = PQfnumber(res, "b");
9833 for (i = 0; i < PQntuples(res); i++)
9835 char *iptr;
9836 char *tptr;
9837 char *bptr;
9838 int blen;
9839 int ival;
9841 /* Get the field values (we ignore possibility they are null!) */
9842 iptr = PQgetvalue(res, i, i_fnum);
9843 tptr = PQgetvalue(res, i, t_fnum);
9844 bptr = PQgetvalue(res, i, b_fnum);
9847 * The binary representation of INT4 is in network byte order, which
9848 * we'd better coerce to the local byte order.
9850 ival = ntohl(*((uint32_t *) iptr));
9853 * The binary representation of TEXT is, well, text, and since libpq
9854 * was nice enough to append a zero byte to it, it'll work just fine
9855 * as a C string.
9857 * The binary representation of BYTEA is a bunch of bytes, which could
9858 * include embedded nulls so we have to pay attention to field length.
9860 blen = PQgetlength(res, i, b_fnum);
9862 printf("tuple %d: got\n", i);
9863 printf(" i = (%d bytes) %d\n",
9864 PQgetlength(res, i, i_fnum), ival);
9865 printf(" t = (%d bytes) '%s'\n",
9866 PQgetlength(res, i, t_fnum), tptr);
9867 printf(" b = (%d bytes) ", blen);
9868 for (j = 0; j < blen; j++)
9869 printf("\\%03o", bptr[j]);
9870 printf("\n\n");
9875 main(int argc, char **argv)
9877 const char *conninfo;
9878 PGconn *conn;
9879 PGresult *res;
9880 const char *paramValues[1];
9881 int paramLengths[1];
9882 int paramFormats[1];
9883 uint32_t binaryIntVal;
9886 * If the user supplies a parameter on the command line, use it as the
9887 * conninfo string; otherwise default to setting dbname=postgres and using
9888 * environment variables or defaults for all other connection parameters.
9890 if (argc > 1)
9891 conninfo = argv[1];
9892 else
9893 conninfo = "dbname = postgres";
9895 /* Make a connection to the database */
9896 conn = PQconnectdb(conninfo);
9898 /* Check to see that the backend connection was successfully made */
9899 if (PQstatus(conn) != CONNECTION_OK)
9901 fprintf(stderr, "%s", PQerrorMessage(conn));
9902 exit_nicely(conn);
9905 /* Set always-secure search path, so malicious users can't take control. */
9906 res = PQexec(conn, "SET search_path = testlibpq3");
9907 if (PQresultStatus(res) != PGRES_COMMAND_OK)
9909 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
9910 PQclear(res);
9911 exit_nicely(conn);
9913 PQclear(res);
9916 * The point of this program is to illustrate use of PQexecParams() with
9917 * out-of-line parameters, as well as binary transmission of data.
9919 * This first example transmits the parameters as text, but receives the
9920 * results in binary format. By using out-of-line parameters we can avoid
9921 * a lot of tedious mucking about with quoting and escaping, even though
9922 * the data is text. Notice how we don't have to do anything special with
9923 * the quote mark in the parameter value.
9926 /* Here is our out-of-line parameter value */
9927 paramValues[0] = "joe's place";
9929 res = PQexecParams(conn,
9930 "SELECT * FROM test1 WHERE t = $1",
9931 1, /* one param */
9932 NULL, /* let the backend deduce param type */
9933 paramValues,
9934 NULL, /* don't need param lengths since text */
9935 NULL, /* default to all text params */
9936 1); /* ask for binary results */
9938 if (PQresultStatus(res) != PGRES_TUPLES_OK)
9940 fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
9941 PQclear(res);
9942 exit_nicely(conn);
9945 show_binary_results(res);
9947 PQclear(res);
9950 * In this second example we transmit an integer parameter in binary form,
9951 * and again retrieve the results in binary form.
9953 * Although we tell PQexecParams we are letting the backend deduce
9954 * parameter type, we really force the decision by casting the parameter
9955 * symbol in the query text. This is a good safety measure when sending
9956 * binary parameters.
9959 /* Convert integer value "2" to network byte order */
9960 binaryIntVal = htonl((uint32_t) 2);
9962 /* Set up parameter arrays for PQexecParams */
9963 paramValues[0] = (char *) &binaryIntVal;
9964 paramLengths[0] = sizeof(binaryIntVal);
9965 paramFormats[0] = 1; /* binary */
9967 res = PQexecParams(conn,
9968 "SELECT * FROM test1 WHERE i = $1::int4",
9969 1, /* one param */
9970 NULL, /* let the backend deduce param type */
9971 paramValues,
9972 paramLengths,
9973 paramFormats,
9974 1); /* ask for binary results */
9976 if (PQresultStatus(res) != PGRES_TUPLES_OK)
9978 fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
9979 PQclear(res);
9980 exit_nicely(conn);
9983 show_binary_results(res);
9985 PQclear(res);
9987 /* close the connection to the database and cleanup */
9988 PQfinish(conn);
9990 return 0;
9993 </programlisting>
9994 </example>
9996 </sect1>
9997 </chapter>