Add a couple of recent commits to .git-blame-ignore-revs.
[pgsql.git] / doc / src / sgml / libpq.sgml
blob068ee60771cbf53852fd4468713d200d9261880d
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 id="libpq-PQconnectPoll"><function>PQconnectPoll</function><indexterm><primary>PQconnectPoll</primary></indexterm></term>
269 <listitem>
270 <para>
271 <indexterm><primary>nonblocking connection</primary></indexterm>
272 Make a connection to the database server in a nonblocking manner.
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). Note that <function>PQsocketPoll</function>
362 can help reduce boilerplate by abstracting the setup of
363 <function>select(2)</function> or <function>poll(2)</function> if it is
364 available on your system.
365 Then call <function>PQconnectPoll(conn)</function> again.
366 Conversely, if <function>PQconnectPoll(conn)</function> last returned
367 <symbol>PGRES_POLLING_WRITING</symbol>, wait until the socket is ready
368 to write, then call <function>PQconnectPoll(conn)</function> again.
369 On the first iteration, i.e., if you have yet to call
370 <function>PQconnectPoll</function>, behave as if it last returned
371 <symbol>PGRES_POLLING_WRITING</symbol>. Continue this loop until
372 <function>PQconnectPoll(conn)</function> returns
373 <symbol>PGRES_POLLING_FAILED</symbol>, indicating the connection procedure
374 has failed, or <symbol>PGRES_POLLING_OK</symbol>, indicating the connection
375 has been successfully made.
376 </para>
378 <para>
379 At any time during connection, the status of the connection can be
380 checked by calling <xref linkend="libpq-PQstatus"/>. If this call returns <symbol>CONNECTION_BAD</symbol>, then the
381 connection procedure has failed; if the call returns <function>CONNECTION_OK</function>, then the
382 connection is ready. Both of these states are equally detectable
383 from the return value of <function>PQconnectPoll</function>, described above. Other states might also occur
384 during (and only during) an asynchronous connection procedure. These
385 indicate the current stage of the connection procedure and might be useful
386 to provide feedback to the user for example. These statuses are:
388 <variablelist>
389 <varlistentry id="libpq-connection-started">
390 <term><symbol>CONNECTION_STARTED</symbol></term>
391 <listitem>
392 <para>
393 Waiting for connection to be made.
394 </para>
395 </listitem>
396 </varlistentry>
398 <varlistentry id="libpq-connection-made">
399 <term><symbol>CONNECTION_MADE</symbol></term>
400 <listitem>
401 <para>
402 Connection OK; waiting to send.
403 </para>
404 </listitem>
405 </varlistentry>
407 <varlistentry id="libpq-connection-awaiting-response">
408 <term><symbol>CONNECTION_AWAITING_RESPONSE</symbol></term>
409 <listitem>
410 <para>
411 Waiting for a response from the server.
412 </para>
413 </listitem>
414 </varlistentry>
416 <varlistentry id="libpq-connection-auth-ok">
417 <term><symbol>CONNECTION_AUTH_OK</symbol></term>
418 <listitem>
419 <para>
420 Received authentication; waiting for backend start-up to finish.
421 </para>
422 </listitem>
423 </varlistentry>
425 <varlistentry id="libpq-connection-ssl-startup">
426 <term><symbol>CONNECTION_SSL_STARTUP</symbol></term>
427 <listitem>
428 <para>
429 Negotiating SSL encryption.
430 </para>
431 </listitem>
432 </varlistentry>
434 <varlistentry id="libpq-connection-gss-startup">
435 <term><symbol>CONNECTION_GSS_STARTUP</symbol></term>
436 <listitem>
437 <para>
438 Negotiating GSS encryption.
439 </para>
440 </listitem>
441 </varlistentry>
443 <varlistentry id="libpq-connection-check-writable">
444 <term><symbol>CONNECTION_CHECK_WRITABLE</symbol></term>
445 <listitem>
446 <para>
447 Checking if connection is able to handle write transactions.
448 </para>
449 </listitem>
450 </varlistentry>
452 <varlistentry id="libpq-connection-check-standby">
453 <term><symbol>CONNECTION_CHECK_STANDBY</symbol></term>
454 <listitem>
455 <para>
456 Checking if connection is to a server in standby mode.
457 </para>
458 </listitem>
459 </varlistentry>
461 <varlistentry id="libpq-connection-consume">
462 <term><symbol>CONNECTION_CONSUME</symbol></term>
463 <listitem>
464 <para>
465 Consuming any remaining response messages on connection.
466 </para>
467 </listitem>
468 </varlistentry>
469 </variablelist>
471 Note that, although these constants will remain (in order to maintain
472 compatibility), an application should never rely upon these occurring in a
473 particular order, or at all, or on the status always being one of these
474 documented values. An application might do something like this:
475 <programlisting>
476 switch(PQstatus(conn))
478 case CONNECTION_STARTED:
479 feedback = "Connecting...";
480 break;
482 case CONNECTION_MADE:
483 feedback = "Connected to server...";
484 break;
488 default:
489 feedback = "Connecting...";
491 </programlisting>
492 </para>
494 <para>
495 The <literal>connect_timeout</literal> connection parameter is ignored
496 when using <function>PQconnectPoll</function>; it is the application's
497 responsibility to decide whether an excessive amount of time has elapsed.
498 Otherwise, <function>PQconnectStart</function> followed by a
499 <function>PQconnectPoll</function> loop is equivalent to
500 <xref linkend="libpq-PQconnectdb"/>.
501 </para>
503 <para>
504 Note that when <function>PQconnectStart</function>
505 or <xref linkend="libpq-PQconnectStartParams"/> returns a non-null
506 pointer, you must call <xref linkend="libpq-PQfinish"/> when you are
507 finished with it, in order to dispose of the structure and any
508 associated memory blocks. This must be done even if the connection
509 attempt fails or is abandoned.
510 </para>
511 </listitem>
512 </varlistentry>
514 <varlistentry id="libpq-PQsocketPoll">
515 <term><function>PQsocketPoll</function><indexterm><primary>PQsocketPoll</primary></indexterm></term>
516 <listitem>
517 <para>
518 <indexterm><primary>nonblocking connection</primary></indexterm>
519 Poll a connection's underlying socket descriptor retrieved with
520 <xref linkend="libpq-PQsocket"/>.
521 The primary use of this function is iterating through the connection
522 sequence described in the documentation of
523 <xref linkend="libpq-PQconnectStartParams"/>.
524 <synopsis>
525 typedef pg_int64 pg_usec_time_t;
527 int PQsocketPoll(int sock, int forRead, int forWrite,
528 pg_usec_time_t end_time);
529 </synopsis>
530 </para>
532 <para>
533 This function performs polling of a file descriptor, optionally with
534 a timeout.
535 If <parameter>forRead</parameter> is nonzero, the
536 function will terminate when the socket is ready for
537 reading. If <parameter>forWrite</parameter> is nonzero,
538 the function will terminate when the
539 socket is ready for writing.
540 </para>
542 <para>
543 The timeout is specified by <parameter>end_time</parameter>, which
544 is the time to stop waiting expressed as a number of microseconds since
545 the Unix epoch (that is, <type>time_t</type> times 1 million).
546 Timeout is infinite if <parameter>end_time</parameter>
547 is <literal>-1</literal>. Timeout is immediate (no blocking) if
548 end_time is <literal>0</literal> (or indeed, any time before now).
549 Timeout values can be calculated conveniently by adding the desired
550 number of microseconds to the result of
551 <xref linkend="libpq-PQgetCurrentTimeUSec"/>.
552 Note that the underlying system calls may have less than microsecond
553 precision, so that the actual delay may be imprecise.
554 </para>
556 <para>
557 The function returns a value greater than <literal>0</literal> if the
558 specified condition is met, <literal>0</literal> if a timeout occurred,
559 or <literal>-1</literal> if an error occurred. The error can be
560 retrieved by checking the <literal>errno(3)</literal> value. In the
561 event both <parameter>forRead</parameter>
562 and <parameter>forWrite</parameter> are zero, the function immediately
563 returns a timeout indication.
564 </para>
566 <para>
567 <function>PQsocketPoll</function> is implemented using either
568 <function>poll(2)</function> or <function>select(2)</function>,
569 depending on platform. See <literal>POLLIN</literal>
570 and <literal>POLLOUT</literal> from <function>poll(2)</function>,
571 or <parameter>readfds</parameter> and
572 <parameter>writefds</parameter> from <function>select(2)</function>,
573 for more information.
574 </para>
575 </listitem>
576 </varlistentry>
578 <varlistentry id="libpq-PQconndefaults">
579 <term><function>PQconndefaults</function><indexterm><primary>PQconndefaults</primary></indexterm></term>
580 <listitem>
581 <para>
582 Returns the default connection options.
583 <synopsis>
584 PQconninfoOption *PQconndefaults(void);
586 typedef struct
588 char *keyword; /* The keyword of the option */
589 char *envvar; /* Fallback environment variable name */
590 char *compiled; /* Fallback compiled in default value */
591 char *val; /* Option's current value, or NULL */
592 char *label; /* Label for field in connect dialog */
593 char *dispchar; /* Indicates how to display this field
594 in a connect dialog. Values are:
595 "" Display entered value as is
596 "*" Password field - hide value
597 "D" Debug option - don't show by default */
598 int dispsize; /* Field size in characters for dialog */
599 } PQconninfoOption;
600 </synopsis>
601 </para>
603 <para>
604 Returns a connection options array. This can be used to determine
605 all possible <xref linkend="libpq-PQconnectdb"/> options and their
606 current default values. The return value points to an array of
607 <structname>PQconninfoOption</structname> structures, which ends
608 with an entry having a null <structfield>keyword</structfield> pointer. The
609 null pointer is returned if memory could not be allocated. Note that
610 the current default values (<structfield>val</structfield> fields)
611 will depend on environment variables and other context. A
612 missing or invalid service file will be silently ignored. Callers
613 must treat the connection options data as read-only.
614 </para>
616 <para>
617 After processing the options array, free it by passing it to
618 <xref linkend="libpq-PQconninfoFree"/>. If this is not done, a small amount of memory
619 is leaked for each call to <xref linkend="libpq-PQconndefaults"/>.
620 </para>
622 </listitem>
623 </varlistentry>
625 <varlistentry id="libpq-PQconninfo">
626 <term><function>PQconninfo</function><indexterm><primary>PQconninfo</primary></indexterm></term>
627 <listitem>
628 <para>
629 Returns the connection options used by a live connection.
630 <synopsis>
631 PQconninfoOption *PQconninfo(PGconn *conn);
632 </synopsis>
633 </para>
635 <para>
636 Returns a connection options array. This can be used to determine
637 all possible <xref linkend="libpq-PQconnectdb"/> options and the
638 values that were used to connect to the server. The return
639 value points to an array of <structname>PQconninfoOption</structname>
640 structures, which ends with an entry having a null <structfield>keyword</structfield>
641 pointer. All notes above for <xref linkend="libpq-PQconndefaults"/> also
642 apply to the result of <xref linkend="libpq-PQconninfo"/>.
643 </para>
645 </listitem>
646 </varlistentry>
649 <varlistentry id="libpq-PQconninfoParse">
650 <term><function>PQconninfoParse</function><indexterm><primary>PQconninfoParse</primary></indexterm></term>
651 <listitem>
652 <para>
653 Returns parsed connection options from the provided connection string.
655 <synopsis>
656 PQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg);
657 </synopsis>
658 </para>
660 <para>
661 Parses a connection string and returns the resulting options as an
662 array; or returns <symbol>NULL</symbol> if there is a problem with the connection
663 string. This function can be used to extract
664 the <xref linkend="libpq-PQconnectdb"/> options in the provided
665 connection string. The return value points to an array of
666 <structname>PQconninfoOption</structname> structures, which ends
667 with an entry having a null <structfield>keyword</structfield> pointer.
668 </para>
670 <para>
671 All legal options will be present in the result array, but the
672 <literal>PQconninfoOption</literal> for any option not present
673 in the connection string will have <literal>val</literal> set to
674 <literal>NULL</literal>; default values are not inserted.
675 </para>
677 <para>
678 If <literal>errmsg</literal> is not <symbol>NULL</symbol>, then <literal>*errmsg</literal> is set
679 to <symbol>NULL</symbol> on success, else to a <function>malloc</function>'d error string explaining
680 the problem. (It is also possible for <literal>*errmsg</literal> to be
681 set to <symbol>NULL</symbol> and the function to return <symbol>NULL</symbol>;
682 this indicates an out-of-memory condition.)
683 </para>
685 <para>
686 After processing the options array, free it by passing it to
687 <xref linkend="libpq-PQconninfoFree"/>. If this is not done, some memory
688 is leaked for each call to <xref linkend="libpq-PQconninfoParse"/>.
689 Conversely, if an error occurs and <literal>errmsg</literal> is not <symbol>NULL</symbol>,
690 be sure to free the error string using <xref linkend="libpq-PQfreemem"/>.
691 </para>
693 </listitem>
694 </varlistentry>
696 <varlistentry id="libpq-PQfinish">
697 <term><function>PQfinish</function><indexterm><primary>PQfinish</primary></indexterm></term>
698 <listitem>
699 <para>
700 Closes the connection to the server. Also frees
701 memory used by the <structname>PGconn</structname> object.
702 <synopsis>
703 void PQfinish(PGconn *conn);
704 </synopsis>
705 </para>
707 <para>
708 Note that even if the server connection attempt fails (as
709 indicated by <xref linkend="libpq-PQstatus"/>), the application should call <xref linkend="libpq-PQfinish"/>
710 to free the memory used by the <structname>PGconn</structname> object.
711 The <structname>PGconn</structname> pointer must not be used again after
712 <xref linkend="libpq-PQfinish"/> has been called.
713 </para>
714 </listitem>
715 </varlistentry>
717 <varlistentry id="libpq-PQreset">
718 <term><function>PQreset</function><indexterm><primary>PQreset</primary></indexterm></term>
719 <listitem>
720 <para>
721 Resets the communication channel to the server.
722 <synopsis>
723 void PQreset(PGconn *conn);
724 </synopsis>
725 </para>
727 <para>
728 This function will close the connection
729 to the server and attempt to establish a new
730 connection, using all the same
731 parameters previously used. This might be useful for
732 error recovery if a working connection is lost.
733 </para>
734 </listitem>
735 </varlistentry>
737 <varlistentry id="libpq-PQresetStart">
738 <term><function>PQresetStart</function><indexterm><primary>PQresetStart</primary></indexterm></term>
739 <term><function>PQresetPoll</function><indexterm><primary>PQresetPoll</primary></indexterm></term>
740 <listitem>
741 <para>
742 Reset the communication channel to the server, in a nonblocking manner.
744 <synopsis>
745 int PQresetStart(PGconn *conn);
747 PostgresPollingStatusType PQresetPoll(PGconn *conn);
748 </synopsis>
749 </para>
751 <para>
752 These functions will close the connection to the server and attempt to
753 establish a new connection, using all the same
754 parameters previously used. This can be useful for error recovery if a
755 working connection is lost. They differ from <xref linkend="libpq-PQreset"/> (above) in that they
756 act in a nonblocking manner. These functions suffer from the same
757 restrictions as <xref linkend="libpq-PQconnectStartParams"/>, <function>PQconnectStart</function>
758 and <function>PQconnectPoll</function>.
759 </para>
761 <para>
762 To initiate a connection reset, call
763 <xref linkend="libpq-PQresetStart"/>. If it returns 0, the reset has
764 failed. If it returns 1, poll the reset using
765 <function>PQresetPoll</function> in exactly the same way as you
766 would create the connection using <function>PQconnectPoll</function>.
767 </para>
768 </listitem>
769 </varlistentry>
771 <varlistentry id="libpq-PQpingParams">
772 <term><function>PQpingParams</function><indexterm><primary>PQpingParams</primary></indexterm></term>
773 <listitem>
774 <para>
775 <xref linkend="libpq-PQpingParams"/> reports the status of the
776 server. It accepts connection parameters identical to those of
777 <xref linkend="libpq-PQconnectdbParams"/>, described above. It is not
778 necessary to supply correct user name, password, or database name
779 values to obtain the server status; however, if incorrect values
780 are provided, the server will log a failed connection attempt.
782 <synopsis>
783 PGPing PQpingParams(const char * const *keywords,
784 const char * const *values,
785 int expand_dbname);
786 </synopsis>
788 The function returns one of the following values:
790 <variablelist>
791 <varlistentry id="libpq-PQpingParams-PQPING_OK">
792 <term><literal>PQPING_OK</literal></term>
793 <listitem>
794 <para>
795 The server is running and appears to be accepting connections.
796 </para>
797 </listitem>
798 </varlistentry>
800 <varlistentry id="libpq-PQpingParams-PQPING_REJECT">
801 <term><literal>PQPING_REJECT</literal></term>
802 <listitem>
803 <para>
804 The server is running but is in a state that disallows connections
805 (startup, shutdown, or crash recovery).
806 </para>
807 </listitem>
808 </varlistentry>
810 <varlistentry id="libpq-PQpingParams-PQPING_NO_RESPONSE">
811 <term><literal>PQPING_NO_RESPONSE</literal></term>
812 <listitem>
813 <para>
814 The server could not be contacted. This might indicate that the
815 server is not running, or that there is something wrong with the
816 given connection parameters (for example, wrong port number), or
817 that there is a network connectivity problem (for example, a
818 firewall blocking the connection request).
819 </para>
820 </listitem>
821 </varlistentry>
823 <varlistentry id="libpq-PQpingParams-PQPING_NO_ATTEMPT">
824 <term><literal>PQPING_NO_ATTEMPT</literal></term>
825 <listitem>
826 <para>
827 No attempt was made to contact the server, because the supplied
828 parameters were obviously incorrect or there was some client-side
829 problem (for example, out of memory).
830 </para>
831 </listitem>
832 </varlistentry>
833 </variablelist>
835 </para>
837 </listitem>
838 </varlistentry>
840 <varlistentry id="libpq-PQping">
841 <term><function>PQping</function><indexterm><primary>PQping</primary></indexterm></term>
842 <listitem>
843 <para>
844 <xref linkend="libpq-PQping"/> reports the status of the
845 server. It accepts connection parameters identical to those of
846 <xref linkend="libpq-PQconnectdb"/>, described above. It is not
847 necessary to supply correct user name, password, or database name
848 values to obtain the server status; however, if incorrect values
849 are provided, the server will log a failed connection attempt.
851 <synopsis>
852 PGPing PQping(const char *conninfo);
853 </synopsis>
854 </para>
856 <para>
857 The return values are the same as for <xref linkend="libpq-PQpingParams"/>.
858 </para>
860 </listitem>
861 </varlistentry>
863 <varlistentry id="libpq-pqsetsslkeypasshook-openssl">
864 <term><function>PQsetSSLKeyPassHook_OpenSSL</function><indexterm><primary>PQsetSSLKeyPassHook_OpenSSL</primary></indexterm></term>
865 <listitem>
866 <para>
867 <function>PQsetSSLKeyPassHook_OpenSSL</function> lets an application override
868 <application>libpq</application>'s <link linkend="libpq-ssl-clientcert">default
869 handling of encrypted client certificate key files</link> using
870 <xref linkend="libpq-connect-sslpassword"/> or interactive prompting.
872 <synopsis>
873 void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook);
874 </synopsis>
876 The application passes a pointer to a callback function with signature:
877 <programlisting>
878 int callback_fn(char *buf, int size, PGconn *conn);
879 </programlisting>
880 which <application>libpq</application> will then call
881 <emphasis>instead of</emphasis> its default
882 <function>PQdefaultSSLKeyPassHook_OpenSSL</function> handler. The
883 callback should determine the password for the key and copy it to
884 result-buffer <parameter>buf</parameter> of size
885 <parameter>size</parameter>. The string in <parameter>buf</parameter>
886 must be null-terminated. The callback must return the length of the
887 password stored in <parameter>buf</parameter> excluding the null
888 terminator. On failure, the callback should set
889 <literal>buf[0] = '\0'</literal> and return 0. See
890 <function>PQdefaultSSLKeyPassHook_OpenSSL</function> in
891 <application>libpq</application>'s source code for an example.
892 </para>
894 <para>
895 If the user specified an explicit key location,
896 its path will be in <literal>conn->sslkey</literal> when the callback
897 is invoked. This will be empty if the default key path is being used.
898 For keys that are engine specifiers, it is up to engine implementations
899 whether they use the <productname>OpenSSL</productname> password
900 callback or define their own handling.
901 </para>
903 <para>
904 The app callback may choose to delegate unhandled cases to
905 <function>PQdefaultSSLKeyPassHook_OpenSSL</function>,
906 or call it first and try something else if it returns 0, or completely override it.
907 </para>
909 <para>
910 The callback <emphasis>must not</emphasis> escape normal flow control with exceptions,
911 <function>longjmp(...)</function>, etc. It must return normally.
912 </para>
914 </listitem>
915 </varlistentry>
917 <varlistentry id="libpq-pqgetsslkeypasshook-openssl">
918 <term><function>PQgetSSLKeyPassHook_OpenSSL</function><indexterm><primary>PQgetSSLKeyPassHook_OpenSSL</primary></indexterm></term>
919 <listitem>
920 <para>
921 <function>PQgetSSLKeyPassHook_OpenSSL</function> returns the current
922 client certificate key password hook, or <literal>NULL</literal>
923 if none has been set.
925 <synopsis>
926 PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void);
927 </synopsis>
928 </para>
930 </listitem>
931 </varlistentry>
933 </variablelist>
934 </para>
936 <sect2 id="libpq-connstring">
937 <title>Connection Strings</title>
939 <indexterm zone="libpq-connstring">
940 <primary><literal>conninfo</literal></primary>
941 </indexterm>
943 <indexterm zone="libpq-connstring">
944 <primary><literal>URI</literal></primary>
945 </indexterm>
947 <para>
948 Several <application>libpq</application> functions parse a user-specified string to obtain
949 connection parameters. There are two accepted formats for these strings:
950 plain keyword/value strings
951 and URIs. URIs generally follow
952 <ulink url="https://datatracker.ietf.org/doc/html/rfc3986">RFC
953 3986</ulink>, except that multi-host connection strings are allowed
954 as further described below.
955 </para>
957 <sect3 id="libpq-connstring-keyword-value">
958 <title>Keyword/Value Connection Strings</title>
960 <para>
961 In the keyword/value format, each parameter setting is in the form
962 <replaceable>keyword</replaceable> <literal>=</literal>
963 <replaceable>value</replaceable>, with space(s) between settings.
964 Spaces around a setting's equal sign are
965 optional. To write an empty value, or a value containing spaces, surround it
966 with single quotes, for example <literal>keyword = 'a value'</literal>.
967 Single quotes and backslashes within
968 a value must be escaped with a backslash, i.e., <literal>\'</literal> and
969 <literal>\\</literal>.
970 </para>
972 <para>
973 Example:
974 <programlisting>
975 host=localhost port=5432 dbname=mydb connect_timeout=10
976 </programlisting>
977 </para>
979 <para>
980 The recognized parameter key words are listed in <xref
981 linkend="libpq-paramkeywords"/>.
982 </para>
983 </sect3>
985 <sect3 id="libpq-connstring-uris">
986 <title>Connection URIs</title>
988 <para>
989 The general form for a connection <acronym>URI</acronym> is:
990 <synopsis>
991 postgresql://<optional><replaceable>userspec</replaceable>@</optional><optional><replaceable>hostspec</replaceable></optional><optional>/<replaceable>dbname</replaceable></optional><optional>?<replaceable>paramspec</replaceable></optional>
993 <phrase>where <replaceable>userspec</replaceable> is:</phrase>
995 <replaceable>user</replaceable><optional>:<replaceable>password</replaceable></optional>
997 <phrase>and <replaceable>hostspec</replaceable> is:</phrase>
999 <optional><replaceable>host</replaceable></optional><optional>:<replaceable>port</replaceable></optional><optional>,...</optional>
1001 <phrase>and <replaceable>paramspec</replaceable> is:</phrase>
1003 <replaceable>name</replaceable>=<replaceable>value</replaceable><optional>&amp;...</optional>
1004 </synopsis>
1005 </para>
1007 <para>
1008 The <acronym>URI</acronym> scheme designator can be either
1009 <literal>postgresql://</literal> or <literal>postgres://</literal>. Each
1010 of the remaining <acronym>URI</acronym> parts is optional. The
1011 following examples illustrate valid <acronym>URI</acronym> syntax:
1012 <programlisting>
1013 postgresql://
1014 postgresql://localhost
1015 postgresql://localhost:5433
1016 postgresql://localhost/mydb
1017 postgresql://user@localhost
1018 postgresql://user:secret@localhost
1019 postgresql://other@localhost/otherdb?connect_timeout=10&amp;application_name=myapp
1020 postgresql://host1:123,host2:456/somedb?target_session_attrs=any&amp;application_name=myapp
1021 </programlisting>
1022 Values that would normally appear in the hierarchical part of
1023 the <acronym>URI</acronym> can alternatively be given as named
1024 parameters. For example:
1025 <programlisting>
1026 postgresql:///mydb?host=localhost&amp;port=5433
1027 </programlisting>
1028 All named parameters must match key words listed in
1029 <xref linkend="libpq-paramkeywords"/>, except that for compatibility
1030 with JDBC connection <acronym>URI</acronym>s, instances
1031 of <literal>ssl=true</literal> are translated into
1032 <literal>sslmode=require</literal>.
1033 </para>
1035 <para>
1036 The connection <acronym>URI</acronym> needs to be encoded with <ulink
1037 url="https://datatracker.ietf.org/doc/html/rfc3986#section-2.1">percent-encoding</ulink>
1038 if it includes symbols with special meaning in any of its parts. Here is
1039 an example where the equal sign (<literal>=</literal>) is replaced with
1040 <literal>%3D</literal> and the space character with
1041 <literal>%20</literal>:
1042 <programlisting>
1043 postgresql://user@localhost:5433/mydb?options=-c%20synchronous_commit%3Doff
1044 </programlisting>
1045 </para>
1047 <para>
1048 The host part may be either a host name or an IP address. To specify an
1049 IPv6 address, enclose it in square brackets:
1050 <synopsis>
1051 postgresql://[2001:db8::1234]/database
1052 </synopsis>
1053 </para>
1055 <para>
1056 The host part is interpreted as described for the parameter <xref
1057 linkend="libpq-connect-host"/>. In particular, a Unix-domain socket
1058 connection is chosen if the host part is either empty or looks like an
1059 absolute path name,
1060 otherwise a TCP/IP connection is initiated. Note, however, that the
1061 slash is a reserved character in the hierarchical part of the URI. So, to
1062 specify a non-standard Unix-domain socket directory, either omit the host
1063 part of the URI and specify the host as a named parameter, or
1064 percent-encode the path in the host part of the URI:
1065 <programlisting>
1066 postgresql:///dbname?host=/var/lib/postgresql
1067 postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
1068 </programlisting>
1069 </para>
1071 <para>
1072 It is possible to specify multiple host components, each with an optional
1073 port component, in a single URI. A URI of the form
1074 <literal>postgresql://host1:port1,host2:port2,host3:port3/</literal>
1075 is equivalent to a connection string of the form
1076 <literal>host=host1,host2,host3 port=port1,port2,port3</literal>.
1077 As further described below, each
1078 host will be tried in turn until a connection is successfully established.
1079 </para>
1080 </sect3>
1082 <sect3 id="libpq-multiple-hosts">
1083 <title>Specifying Multiple Hosts</title>
1085 <para>
1086 It is possible to specify multiple hosts to connect to, so that they are
1087 tried in the given order. In the Keyword/Value format, the <literal>host</literal>,
1088 <literal>hostaddr</literal>, and <literal>port</literal> options accept comma-separated
1089 lists of values. The same number of elements must be given in each
1090 option that is specified, such
1091 that e.g., the first <literal>hostaddr</literal> corresponds to the first host name,
1092 the second <literal>hostaddr</literal> corresponds to the second host name, and so
1093 forth. As an exception, if only one <literal>port</literal> is specified, it
1094 applies to all the hosts.
1095 </para>
1097 <para>
1098 In the connection URI format, you can list multiple <literal>host:port</literal> pairs
1099 separated by commas in the <literal>host</literal> component of the URI.
1100 </para>
1102 <para>
1103 In either format, a single host name can translate to multiple network
1104 addresses. A common example of this is a host that has both an IPv4 and
1105 an IPv6 address.
1106 </para>
1108 <para>
1109 When multiple hosts are specified, or when a single host name is
1110 translated to multiple addresses, all the hosts and addresses will be
1111 tried in order, until one succeeds. If none of the hosts can be reached,
1112 the connection fails. If a connection is established successfully, but
1113 authentication fails, the remaining hosts in the list are not tried.
1114 </para>
1116 <para>
1117 If a password file is used, you can have different passwords for
1118 different hosts. All the other connection options are the same for every
1119 host in the list; it is not possible to e.g., specify different
1120 usernames for different hosts.
1121 </para>
1122 </sect3>
1123 </sect2>
1125 <sect2 id="libpq-paramkeywords">
1126 <title>Parameter Key Words</title>
1128 <para>
1129 The currently recognized parameter key words are:
1131 <variablelist>
1132 <varlistentry id="libpq-connect-host" xreflabel="host">
1133 <term><literal>host</literal></term>
1134 <listitem>
1135 <para>
1136 Name of host to connect to.<indexterm><primary>host
1137 name</primary></indexterm> If a host name looks like an absolute path
1138 name, it specifies Unix-domain communication rather than TCP/IP
1139 communication; the value is the name of the directory in which the
1140 socket file is stored. (On Unix, an absolute path name begins with a
1141 slash. On Windows, paths starting with drive letters are also
1142 recognized.) If the host name starts with <literal>@</literal>, it is
1143 taken as a Unix-domain socket in the abstract namespace (currently
1144 supported on Linux and Windows).
1145 The default behavior when <literal>host</literal> is not
1146 specified, or is empty, is to connect to a Unix-domain
1147 socket<indexterm><primary>Unix domain socket</primary></indexterm> in
1148 <filename>/tmp</filename> (or whatever socket directory was specified
1149 when <productname>PostgreSQL</productname> was built). On Windows,
1150 the default is to connect to <literal>localhost</literal>.
1151 </para>
1152 <para>
1153 A comma-separated list of host names is also accepted, in which case
1154 each host name in the list is tried in order; an empty item in the
1155 list selects the default behavior as explained above. See
1156 <xref linkend="libpq-multiple-hosts"/> for details.
1157 </para>
1158 </listitem>
1159 </varlistentry>
1161 <varlistentry id="libpq-connect-hostaddr" xreflabel="hostaddr">
1162 <term><literal>hostaddr</literal></term>
1163 <listitem>
1164 <para>
1165 Numeric IP address of host to connect to. This should be in the
1166 standard IPv4 address format, e.g., <literal>172.28.40.9</literal>. If
1167 your machine supports IPv6, you can also use those addresses.
1168 TCP/IP communication is
1169 always used when a nonempty string is specified for this parameter.
1170 If this parameter is not specified, the value of <literal>host</literal>
1171 will be looked up to find the corresponding IP address &mdash; or, if
1172 <literal>host</literal> specifies an IP address, that value will be
1173 used directly.
1174 </para>
1176 <para>
1177 Using <literal>hostaddr</literal> allows the
1178 application to avoid a host name look-up, which might be important
1179 in applications with time constraints. However, a host name is
1180 required for GSSAPI or SSPI authentication
1181 methods, as well as for <literal>verify-full</literal> SSL
1182 certificate verification. The following rules are used:
1183 <itemizedlist>
1184 <listitem>
1185 <para>
1186 If <literal>host</literal> is specified
1187 without <literal>hostaddr</literal>, a host name lookup occurs.
1188 (When using <function>PQconnectPoll</function>, the lookup occurs
1189 when <function>PQconnectPoll</function> first considers this host
1190 name, and it may cause <function>PQconnectPoll</function> to block
1191 for a significant amount of time.)
1192 </para>
1193 </listitem>
1194 <listitem>
1195 <para>
1196 If <literal>hostaddr</literal> is specified without <literal>host</literal>,
1197 the value for <literal>hostaddr</literal> gives the server network address.
1198 The connection attempt will fail if the authentication
1199 method requires a host name.
1200 </para>
1201 </listitem>
1202 <listitem>
1203 <para>
1204 If both <literal>host</literal> and <literal>hostaddr</literal> are specified,
1205 the value for <literal>hostaddr</literal> gives the server network address.
1206 The value for <literal>host</literal> is ignored unless the
1207 authentication method requires it, in which case it will be
1208 used as the host name.
1209 </para>
1210 </listitem>
1211 </itemizedlist>
1212 Note that authentication is likely to fail if <literal>host</literal>
1213 is not the name of the server at network address <literal>hostaddr</literal>.
1214 Also, when both <literal>host</literal> and <literal>hostaddr</literal>
1215 are specified, <literal>host</literal>
1216 is used to identify the connection in a password file (see
1217 <xref linkend="libpq-pgpass"/>).
1218 </para>
1220 <para>
1221 A comma-separated list of <literal>hostaddr</literal> values is also
1222 accepted, in which case each host in the list is tried in order.
1223 An empty item in the list causes the corresponding host name to be
1224 used, or the default host name if that is empty as well. See
1225 <xref linkend="libpq-multiple-hosts"/> for details.
1226 </para>
1227 <para>
1228 Without either a host name or host address,
1229 <application>libpq</application> will connect using a local
1230 Unix-domain socket; or on Windows, it will attempt to connect to
1231 <literal>localhost</literal>.
1232 </para>
1233 </listitem>
1234 </varlistentry>
1236 <varlistentry id="libpq-connect-port" xreflabel="port">
1237 <term><literal>port</literal></term>
1238 <listitem>
1239 <para>
1240 Port number to connect to at the server host, or socket file
1241 name extension for Unix-domain
1242 connections.<indexterm><primary>port</primary></indexterm>
1243 If multiple hosts were given in the <literal>host</literal> or
1244 <literal>hostaddr</literal> parameters, this parameter may specify a
1245 comma-separated list of ports of the same length as the host list, or
1246 it may specify a single port number to be used for all hosts.
1247 An empty string, or an empty item in a comma-separated list,
1248 specifies the default port number established
1249 when <productname>PostgreSQL</productname> was built.
1250 </para>
1251 </listitem>
1252 </varlistentry>
1254 <varlistentry id="libpq-connect-dbname" xreflabel="dbname">
1255 <term><literal>dbname</literal></term>
1256 <listitem>
1257 <para>
1258 The database name. Defaults to be the same as the user name.
1259 In certain contexts, the value is checked for extended
1260 formats; see <xref linkend="libpq-connstring"/> for more details on
1261 those.
1262 </para>
1263 </listitem>
1264 </varlistentry>
1266 <varlistentry id="libpq-connect-user" xreflabel="user">
1267 <term><literal>user</literal></term>
1268 <listitem>
1269 <para>
1270 <productname>PostgreSQL</productname> user name to connect as.
1271 Defaults to be the same as the operating system name of the user
1272 running the application.
1273 </para>
1274 </listitem>
1275 </varlistentry>
1277 <varlistentry id="libpq-connect-password" xreflabel="password">
1278 <term><literal>password</literal></term>
1279 <listitem>
1280 <para>
1281 Password to be used if the server demands password authentication.
1282 </para>
1283 </listitem>
1284 </varlistentry>
1286 <varlistentry id="libpq-connect-passfile" xreflabel="passfile">
1287 <term><literal>passfile</literal></term>
1288 <listitem>
1289 <para>
1290 Specifies the name of the file used to store passwords
1291 (see <xref linkend="libpq-pgpass"/>).
1292 Defaults to <filename>~/.pgpass</filename>, or
1293 <filename>%APPDATA%\postgresql\pgpass.conf</filename> on Microsoft Windows.
1294 (No error is reported if this file does not exist.)
1295 </para>
1296 </listitem>
1297 </varlistentry>
1299 <varlistentry id="libpq-connect-require-auth" xreflabel="require_auth">
1300 <term><literal>require_auth</literal></term>
1301 <listitem>
1302 <para>
1303 Specifies the authentication method that the client requires from the
1304 server. If the server does not use the required method to authenticate
1305 the client, or if the authentication handshake is not fully completed by
1306 the server, the connection will fail. A comma-separated list of methods
1307 may also be provided, of which the server must use exactly one in order
1308 for the connection to succeed. By default, any authentication method is
1309 accepted, and the server is free to skip authentication altogether.
1310 </para>
1311 <para>
1312 Methods may be negated with the addition of a <literal>!</literal>
1313 prefix, in which case the server must <emphasis>not</emphasis> attempt
1314 the listed method; any other method is accepted, and the server is free
1315 not to authenticate the client at all. If a comma-separated list is
1316 provided, the server may not attempt <emphasis>any</emphasis> of the
1317 listed negated methods. Negated and non-negated forms may not be
1318 combined in the same setting.
1319 </para>
1320 <para>
1321 As a final special case, the <literal>none</literal> method requires the
1322 server not to use an authentication challenge. (It may also be negated,
1323 to require some form of authentication.)
1324 </para>
1325 <para>
1326 The following methods may be specified:
1328 <variablelist>
1329 <varlistentry>
1330 <term><literal>password</literal></term>
1331 <listitem>
1332 <para>
1333 The server must request plaintext password authentication.
1334 </para>
1335 </listitem>
1336 </varlistentry>
1338 <varlistentry>
1339 <term><literal>md5</literal></term>
1340 <listitem>
1341 <para>
1342 The server must request MD5 hashed password authentication.
1343 </para>
1344 </listitem>
1345 </varlistentry>
1347 <varlistentry>
1348 <term><literal>gss</literal></term>
1349 <listitem>
1350 <para>
1351 The server must either request a Kerberos handshake via
1352 <acronym>GSSAPI</acronym> or establish a
1353 <acronym>GSS</acronym>-encrypted channel (see also
1354 <xref linkend="libpq-connect-gssencmode" />).
1355 </para>
1356 </listitem>
1357 </varlistentry>
1359 <varlistentry>
1360 <term><literal>sspi</literal></term>
1361 <listitem>
1362 <para>
1363 The server must request Windows <acronym>SSPI</acronym>
1364 authentication.
1365 </para>
1366 </listitem>
1367 </varlistentry>
1369 <varlistentry>
1370 <term><literal>scram-sha-256</literal></term>
1371 <listitem>
1372 <para>
1373 The server must successfully complete a SCRAM-SHA-256 authentication
1374 exchange with the client.
1375 </para>
1376 </listitem>
1377 </varlistentry>
1379 <varlistentry>
1380 <term><literal>none</literal></term>
1381 <listitem>
1382 <para>
1383 The server must not prompt the client for an authentication
1384 exchange. (This does not prohibit client certificate authentication
1385 via TLS, nor GSS authentication via its encrypted transport.)
1386 </para>
1387 </listitem>
1388 </varlistentry>
1389 </variablelist>
1390 </para>
1391 </listitem>
1392 </varlistentry>
1394 <varlistentry id="libpq-connect-channel-binding" xreflabel="channel_binding">
1395 <term><literal>channel_binding</literal></term>
1396 <listitem>
1397 <para>
1398 This option controls the client's use of channel binding. A setting
1399 of <literal>require</literal> means that the connection must employ
1400 channel binding, <literal>prefer</literal> means that the client will
1401 choose channel binding if available, and <literal>disable</literal>
1402 prevents the use of channel binding. The default
1403 is <literal>prefer</literal> if
1404 <productname>PostgreSQL</productname> is compiled with SSL support;
1405 otherwise the default is <literal>disable</literal>.
1406 </para>
1407 <para>
1408 Channel binding is a method for the server to authenticate itself to
1409 the client. It is only supported over SSL connections
1410 with <productname>PostgreSQL</productname> 11 or later servers using
1411 the <literal>SCRAM</literal> authentication method.
1412 </para>
1413 </listitem>
1414 </varlistentry>
1416 <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout">
1417 <term><literal>connect_timeout</literal></term>
1418 <listitem>
1419 <para>
1420 Maximum time to wait while connecting, in seconds (write as a decimal integer,
1421 e.g., <literal>10</literal>). Zero, negative, or not specified means
1422 wait indefinitely.
1423 This timeout applies separately to each host name or IP address.
1424 For example, if you specify two hosts and <literal>connect_timeout</literal>
1425 is 5, each host will time out if no connection is made within 5
1426 seconds, so the total time spent waiting for a connection might be
1427 up to 10 seconds.
1428 </para>
1429 </listitem>
1430 </varlistentry>
1432 <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding">
1433 <term><literal>client_encoding</literal></term>
1434 <listitem>
1435 <para>
1436 This sets the <varname>client_encoding</varname>
1437 configuration parameter for this connection. In addition to
1438 the values accepted by the corresponding server option, you
1439 can use <literal>auto</literal> to determine the right
1440 encoding from the current locale in the client
1441 (<envar>LC_CTYPE</envar> environment variable on Unix
1442 systems).
1443 </para>
1444 </listitem>
1445 </varlistentry>
1447 <varlistentry id="libpq-connect-options" xreflabel="options">
1448 <term><literal>options</literal></term>
1449 <listitem>
1450 <para>
1451 Specifies command-line options to send to the server at connection
1452 start. For example, setting this to <literal>-c geqo=off</literal>
1453 or <literal>--geqo=off</literal> sets the session's value of the
1454 <varname>geqo</varname> parameter to <literal>off</literal>.
1455 Spaces within this string are considered to
1456 separate command-line arguments, unless escaped with a backslash
1457 (<literal>\</literal>); write <literal>\\</literal> to represent a literal
1458 backslash. For a detailed discussion of the available
1459 options, consult <xref linkend="runtime-config"/>.
1460 </para>
1461 </listitem>
1462 </varlistentry>
1464 <varlistentry id="libpq-connect-application-name" xreflabel="application_name">
1465 <term><literal>application_name</literal></term>
1466 <listitem>
1467 <para>
1468 Specifies a value for the <xref linkend="guc-application-name"/>
1469 configuration parameter.
1470 </para>
1471 </listitem>
1472 </varlistentry>
1474 <varlistentry id="libpq-connect-fallback-application-name" xreflabel="fallback_application_name">
1475 <term><literal>fallback_application_name</literal></term>
1476 <listitem>
1477 <para>
1478 Specifies a fallback value for the <xref
1479 linkend="guc-application-name"/> configuration parameter.
1480 This value will be used if no value has been given for
1481 <literal>application_name</literal> via a connection parameter or the
1482 <envar>PGAPPNAME</envar> environment variable. Specifying
1483 a fallback name is useful in generic utility programs that
1484 wish to set a default application name but allow it to be
1485 overridden by the user.
1486 </para>
1487 </listitem>
1488 </varlistentry>
1490 <varlistentry id="libpq-keepalives" xreflabel="keepalives">
1491 <term><literal>keepalives</literal></term>
1492 <listitem>
1493 <para>
1494 Controls whether client-side TCP keepalives are used. The default
1495 value is 1, meaning on, but you can change this to 0, meaning off,
1496 if keepalives are not wanted. This parameter is ignored for
1497 connections made via a Unix-domain socket.
1498 </para>
1499 </listitem>
1500 </varlistentry>
1502 <varlistentry id="libpq-keepalives-idle" xreflabel="keepalives_idle">
1503 <term><literal>keepalives_idle</literal></term>
1504 <listitem>
1505 <para>
1506 Controls the number of seconds of inactivity after which TCP should
1507 send a keepalive message to the server. A value of zero uses the
1508 system default. This parameter is ignored for connections made via a
1509 Unix-domain socket, or if keepalives are disabled.
1510 It is only supported on systems where <symbol>TCP_KEEPIDLE</symbol> or
1511 an equivalent socket option is available, and on Windows; on other
1512 systems, it has no effect.
1513 </para>
1514 </listitem>
1515 </varlistentry>
1517 <varlistentry id="libpq-keepalives-interval" xreflabel="keepalives_interval">
1518 <term><literal>keepalives_interval</literal></term>
1519 <listitem>
1520 <para>
1521 Controls the number of seconds after which a TCP keepalive message
1522 that is not acknowledged by the server should be retransmitted. A
1523 value of zero uses the system default. This parameter is ignored for
1524 connections made via a Unix-domain socket, or if keepalives are disabled.
1525 It is only supported on systems where <symbol>TCP_KEEPINTVL</symbol> or
1526 an equivalent socket option is available, and on Windows; on other
1527 systems, it has no effect.
1528 </para>
1529 </listitem>
1530 </varlistentry>
1532 <varlistentry id="libpq-keepalives-count" xreflabel="keepalives_count">
1533 <term><literal>keepalives_count</literal></term>
1534 <listitem>
1535 <para>
1536 Controls the number of TCP keepalives that can be lost before the
1537 client's connection to the server is considered dead. A value of
1538 zero uses the system default. This parameter is ignored for
1539 connections made via a Unix-domain socket, or if keepalives are disabled.
1540 It is only supported on systems where <symbol>TCP_KEEPCNT</symbol> or
1541 an equivalent socket option is available; on other systems, it has no
1542 effect.
1543 </para>
1544 </listitem>
1545 </varlistentry>
1547 <varlistentry id="libpq-tcp-user-timeout" xreflabel="tcp_user_timeout">
1548 <term><literal>tcp_user_timeout</literal></term>
1549 <listitem>
1550 <para>
1551 Controls the number of milliseconds that transmitted data may
1552 remain unacknowledged before a connection is forcibly closed.
1553 A value of zero uses the system default. This parameter is
1554 ignored for connections made via a Unix-domain socket.
1555 It is only supported on systems where <symbol>TCP_USER_TIMEOUT</symbol>
1556 is available; on other systems, it has no effect.
1557 </para>
1558 </listitem>
1559 </varlistentry>
1561 <varlistentry id="libpq-connect-replication" xreflabel="replication">
1562 <term><literal>replication</literal></term>
1563 <listitem>
1564 <para>
1565 This option determines whether the connection should use the
1566 replication protocol instead of the normal protocol. This is what
1567 PostgreSQL replication connections as well as tools such as
1568 <application>pg_basebackup</application> use internally, but it can
1569 also be used by third-party applications. For a description of the
1570 replication protocol, consult <xref linkend="protocol-replication"/>.
1571 </para>
1573 <para>
1574 The following values, which are case-insensitive, are supported:
1575 <variablelist>
1576 <varlistentry>
1577 <term>
1578 <literal>true</literal>, <literal>on</literal>,
1579 <literal>yes</literal>, <literal>1</literal>
1580 </term>
1581 <listitem>
1582 <para>
1583 The connection goes into physical replication mode.
1584 </para>
1585 </listitem>
1586 </varlistentry>
1588 <varlistentry>
1589 <term><literal>database</literal></term>
1590 <listitem>
1591 <para>
1592 The connection goes into logical replication mode, connecting to
1593 the database specified in the <literal>dbname</literal> parameter.
1594 </para>
1595 </listitem>
1596 </varlistentry>
1598 <varlistentry>
1599 <term>
1600 <literal>false</literal>, <literal>off</literal>,
1601 <literal>no</literal>, <literal>0</literal>
1602 </term>
1603 <listitem>
1604 <para>
1605 The connection is a regular one, which is the default behavior.
1606 </para>
1607 </listitem>
1608 </varlistentry>
1609 </variablelist>
1610 </para>
1612 <para>
1613 In physical or logical replication mode, only the simple query protocol
1614 can be used.
1615 </para>
1616 </listitem>
1617 </varlistentry>
1619 <varlistentry id="libpq-connect-gssencmode" xreflabel="gssencmode">
1620 <term><literal>gssencmode</literal></term>
1621 <listitem>
1622 <para>
1623 This option determines whether or with what priority a secure
1624 <acronym>GSS</acronym> TCP/IP connection will be negotiated with the
1625 server. There are three modes:
1627 <variablelist>
1628 <varlistentry>
1629 <term><literal>disable</literal></term>
1630 <listitem>
1631 <para>
1632 only try a non-<acronym>GSSAPI</acronym>-encrypted connection
1633 </para>
1634 </listitem>
1635 </varlistentry>
1637 <varlistentry>
1638 <term><literal>prefer</literal> (default)</term>
1639 <listitem>
1640 <para>
1641 if there are <acronym>GSSAPI</acronym> credentials present (i.e.,
1642 in a credentials cache), first try
1643 a <acronym>GSSAPI</acronym>-encrypted connection; if that fails or
1644 there are no credentials, try a
1645 non-<acronym>GSSAPI</acronym>-encrypted connection. This is the
1646 default when <productname>PostgreSQL</productname> has been
1647 compiled with <acronym>GSSAPI</acronym> support.
1648 </para>
1649 </listitem>
1650 </varlistentry>
1652 <varlistentry>
1653 <term><literal>require</literal></term>
1654 <listitem>
1655 <para>
1656 only try a <acronym>GSSAPI</acronym>-encrypted connection
1657 </para>
1658 </listitem>
1659 </varlistentry>
1660 </variablelist>
1661 </para>
1663 <para>
1664 <literal>gssencmode</literal> is ignored for Unix domain socket
1665 communication. If <productname>PostgreSQL</productname> is compiled
1666 without GSSAPI support, using the <literal>require</literal> option
1667 will cause an error, while <literal>prefer</literal> will be accepted
1668 but <application>libpq</application> will not actually attempt
1669 a <acronym>GSSAPI</acronym>-encrypted
1670 connection.<indexterm><primary>GSSAPI</primary><secondary sortas="libpq">with
1671 libpq</secondary></indexterm>
1672 </para>
1673 </listitem>
1674 </varlistentry>
1676 <varlistentry id="libpq-connect-sslmode" xreflabel="sslmode">
1677 <term><literal>sslmode</literal></term>
1678 <listitem>
1679 <para>
1680 This option determines whether or with what priority a secure
1681 <acronym>SSL</acronym> TCP/IP connection will be negotiated with the
1682 server. There are six modes:
1684 <variablelist>
1685 <varlistentry>
1686 <term><literal>disable</literal></term>
1687 <listitem>
1688 <para>
1689 only try a non-<acronym>SSL</acronym> connection
1690 </para>
1691 </listitem>
1692 </varlistentry>
1694 <varlistentry>
1695 <term><literal>allow</literal></term>
1696 <listitem>
1697 <para>
1698 first try a non-<acronym>SSL</acronym> connection; if that
1699 fails, try an <acronym>SSL</acronym> connection
1700 </para>
1701 </listitem>
1702 </varlistentry>
1704 <varlistentry>
1705 <term><literal>prefer</literal> (default)</term>
1706 <listitem>
1707 <para>
1708 first try an <acronym>SSL</acronym> connection; if that fails,
1709 try a non-<acronym>SSL</acronym> connection
1710 </para>
1711 </listitem>
1712 </varlistentry>
1714 <varlistentry>
1715 <term><literal>require</literal></term>
1716 <listitem>
1717 <para>
1718 only try an <acronym>SSL</acronym> connection. If a root CA
1719 file is present, verify the certificate in the same way as
1720 if <literal>verify-ca</literal> was specified
1721 </para>
1722 </listitem>
1723 </varlistentry>
1725 <varlistentry>
1726 <term><literal>verify-ca</literal></term>
1727 <listitem>
1728 <para>
1729 only try an <acronym>SSL</acronym> connection, and verify that
1730 the server certificate is issued by a trusted
1731 certificate authority (<acronym>CA</acronym>)
1732 </para>
1733 </listitem>
1734 </varlistentry>
1736 <varlistentry>
1737 <term><literal>verify-full</literal></term>
1738 <listitem>
1739 <para>
1740 only try an <acronym>SSL</acronym> connection, verify that the
1741 server certificate is issued by a
1742 trusted <acronym>CA</acronym> and that the requested server host name
1743 matches that in the certificate
1744 </para>
1745 </listitem>
1746 </varlistentry>
1747 </variablelist>
1749 See <xref linkend="libpq-ssl"/> for a detailed description of how
1750 these options work.
1751 </para>
1753 <para>
1754 <literal>sslmode</literal> is ignored for Unix domain socket
1755 communication.
1756 If <productname>PostgreSQL</productname> is compiled without SSL support,
1757 using options <literal>require</literal>, <literal>verify-ca</literal>, or
1758 <literal>verify-full</literal> will cause an error, while
1759 options <literal>allow</literal> and <literal>prefer</literal> will be
1760 accepted but <application>libpq</application> will not actually attempt
1761 an <acronym>SSL</acronym>
1762 connection.<indexterm><primary>SSL</primary><secondary
1763 sortas="libpq">with libpq</secondary></indexterm>
1764 </para>
1766 <para>
1767 Note that if <acronym>GSSAPI</acronym> encryption is possible,
1768 that will be used in preference to <acronym>SSL</acronym>
1769 encryption, regardless of the value of <literal>sslmode</literal>.
1770 To force use of <acronym>SSL</acronym> encryption in an
1771 environment that has working <acronym>GSSAPI</acronym>
1772 infrastructure (such as a Kerberos server), also set
1773 <literal>gssencmode</literal> to <literal>disable</literal>.
1774 </para>
1775 </listitem>
1776 </varlistentry>
1778 <varlistentry id="libpq-connect-requiressl" xreflabel="requiressl">
1779 <term><literal>requiressl</literal></term>
1780 <listitem>
1781 <para>
1782 This option is deprecated in favor of the <literal>sslmode</literal>
1783 setting.
1784 </para>
1786 <para>
1787 If set to 1, an <acronym>SSL</acronym> connection to the server
1788 is required (this is equivalent to <literal>sslmode</literal>
1789 <literal>require</literal>). <application>libpq</application> will then refuse
1790 to connect if the server does not accept an
1791 <acronym>SSL</acronym> connection. If set to 0 (default),
1792 <application>libpq</application> will negotiate the connection type with
1793 the server (equivalent to <literal>sslmode</literal>
1794 <literal>prefer</literal>). This option is only available if
1795 <productname>PostgreSQL</productname> is compiled with SSL support.
1796 </para>
1797 </listitem>
1798 </varlistentry>
1800 <varlistentry id="libpq-connect-sslnegotiation" xreflabel="sslnegotiation">
1801 <term><literal>sslnegotiation</literal></term>
1802 <listitem>
1803 <para>
1804 This option controls how SSL encryption is negotiated with the server,
1805 if SSL is used. In the default <literal>postgres</literal> mode, the
1806 client first asks the server if SSL is supported. In
1807 <literal>direct</literal> mode, the client starts the standard SSL
1808 handshake directly after establishing the TCP/IP connection. Traditional
1809 <productname>PostgreSQL</productname> protocol negotiation is the most
1810 flexible with different server configurations. If the server is known
1811 to support direct <acronym>SSL</acronym> connections then the latter
1812 requires one fewer round trip reducing connection latency and also
1813 allows the use of protocol agnostic SSL network tools. The direct SSL
1814 option was introduced in <productname>PostgreSQL</productname> version
1816 </para>
1818 <variablelist>
1819 <varlistentry>
1820 <term><literal>postgres</literal></term>
1821 <listitem>
1822 <para>
1823 perform <productname>PostgreSQL</productname> protocol
1824 negotiation. This is the default if the option is not provided.
1825 </para>
1826 </listitem>
1827 </varlistentry>
1829 <varlistentry>
1830 <term><literal>direct</literal></term>
1831 <listitem>
1832 <para>
1833 start SSL handshake directly after establishing the TCP/IP
1834 connection. This is only allowed with sslmode=require or higher,
1835 because the weaker settings could lead to unintended fallback to
1836 plaintext authentication when the server does not support direct
1837 SSL handshake.
1838 </para>
1839 </listitem>
1840 </varlistentry>
1841 </variablelist>
1842 </listitem>
1843 </varlistentry>
1845 <varlistentry id="libpq-connect-sslcompression" xreflabel="sslcompression">
1846 <term><literal>sslcompression</literal></term>
1847 <listitem>
1848 <para>
1849 If set to 1, data sent over SSL connections will be compressed. If
1850 set to 0, compression will be disabled. The default is 0. This
1851 parameter is ignored if a connection without SSL is made.
1852 </para>
1854 <para>
1855 SSL compression is nowadays considered insecure and its use is no
1856 longer recommended. <productname>OpenSSL</productname> 1.1.0 disabled
1857 compression by default, and many operating system distributions
1858 disabled it in prior versions as well, so setting this parameter to on
1859 will not have any effect if the server does not accept compression.
1860 <productname>PostgreSQL</productname> 14 disabled compression
1861 completely in the backend.
1862 </para>
1864 <para>
1865 If security is not a primary concern, compression can improve
1866 throughput if the network is the bottleneck. Disabling compression
1867 can improve response time and throughput if CPU performance is the
1868 limiting factor.
1869 </para>
1870 </listitem>
1871 </varlistentry>
1873 <varlistentry id="libpq-connect-sslcert" xreflabel="sslcert">
1874 <term><literal>sslcert</literal></term>
1875 <listitem>
1876 <para>
1877 This parameter specifies the file name of the client SSL
1878 certificate, replacing the default
1879 <filename>~/.postgresql/postgresql.crt</filename>.
1880 This parameter is ignored if an SSL connection is not made.
1881 </para>
1882 </listitem>
1883 </varlistentry>
1885 <varlistentry id="libpq-connect-sslkey" xreflabel="sslkey">
1886 <term><literal>sslkey</literal></term>
1887 <listitem>
1888 <para>
1889 This parameter specifies the location for the secret key used for
1890 the client certificate. It can either specify a file name that will
1891 be used instead of the default
1892 <filename>~/.postgresql/postgresql.key</filename>, or it can specify a key
1893 obtained from an external <quote>engine</quote> (engines are
1894 <productname>OpenSSL</productname> loadable modules). An external engine
1895 specification should consist of a colon-separated engine name and
1896 an engine-specific key identifier. This parameter is ignored if an
1897 SSL connection is not made.
1898 </para>
1899 </listitem>
1900 </varlistentry>
1902 <varlistentry id="libpq-connect-sslpassword" xreflabel="sslpassword">
1903 <term><literal>sslpassword</literal></term>
1904 <listitem>
1905 <para>
1906 This parameter specifies the password for the secret key specified in
1907 <literal>sslkey</literal>, allowing client certificate private keys
1908 to be stored in encrypted form on disk even when interactive passphrase
1909 input is not practical.
1910 </para>
1911 <para>
1912 Specifying this parameter with any non-empty value suppresses the
1913 <literal>Enter PEM pass phrase:</literal>
1914 prompt that <productname>OpenSSL</productname> will emit by default
1915 when an encrypted client certificate key is provided to
1916 <literal>libpq</literal>.
1917 </para>
1918 <para>
1919 If the key is not encrypted this parameter is ignored. The parameter
1920 has no effect on keys specified by <productname>OpenSSL</productname>
1921 engines unless the engine uses the <productname>OpenSSL</productname>
1922 password callback mechanism for prompts.
1923 </para>
1924 <para>
1925 There is no environment variable equivalent to this option, and no
1926 facility for looking it up in <filename>.pgpass</filename>. It can be
1927 used in a service file connection definition. Users with
1928 more sophisticated uses should consider using <productname>OpenSSL</productname> engines and
1929 tools like PKCS#11 or USB crypto offload devices.
1930 </para>
1931 </listitem>
1932 </varlistentry>
1934 <varlistentry id="libpq-connect-sslcertmode" xreflabel="sslcertmode">
1935 <term><literal>sslcertmode</literal></term>
1936 <listitem>
1937 <para>
1938 This option determines whether a client certificate may be sent to the
1939 server, and whether the server is required to request one. There are
1940 three modes:
1942 <variablelist>
1943 <varlistentry>
1944 <term><literal>disable</literal></term>
1945 <listitem>
1946 <para>
1947 A client certificate is never sent, even if one is available
1948 (default location or provided via
1949 <xref linkend="libpq-connect-sslcert" />).
1950 </para>
1951 </listitem>
1952 </varlistentry>
1954 <varlistentry>
1955 <term><literal>allow</literal> (default)</term>
1956 <listitem>
1957 <para>
1958 A certificate may be sent, if the server requests one and the
1959 client has one to send.
1960 </para>
1961 </listitem>
1962 </varlistentry>
1964 <varlistentry>
1965 <term><literal>require</literal></term>
1966 <listitem>
1967 <para>
1968 The server <emphasis>must</emphasis> request a certificate. The
1969 connection will fail if the client does not send a certificate and
1970 the server successfully authenticates the client anyway.
1971 </para>
1972 </listitem>
1973 </varlistentry>
1974 </variablelist>
1975 </para>
1977 <note>
1978 <para>
1979 <literal>sslcertmode=require</literal> doesn't add any additional
1980 security, since there is no guarantee that the server is validating
1981 the certificate correctly; PostgreSQL servers generally request TLS
1982 certificates from clients whether they validate them or not. The
1983 option may be useful when troubleshooting more complicated TLS
1984 setups.
1985 </para>
1986 </note>
1987 </listitem>
1988 </varlistentry>
1990 <varlistentry id="libpq-connect-sslrootcert" xreflabel="sslrootcert">
1991 <term><literal>sslrootcert</literal></term>
1992 <listitem>
1993 <para>
1994 This parameter specifies the name of a file containing SSL
1995 certificate authority (<acronym>CA</acronym>) certificate(s).
1996 If the file exists, the server's certificate will be verified
1997 to be signed by one of these authorities. The default is
1998 <filename>~/.postgresql/root.crt</filename>.
1999 </para>
2000 <para>
2001 The special value <literal>system</literal> may be specified instead, in
2002 which case the system's trusted CA roots will be loaded. The exact
2003 locations of these root certificates differ by SSL implementation and
2004 platform. For <productname>OpenSSL</productname> in particular, the
2005 locations may be further modified by the <envar>SSL_CERT_DIR</envar>
2006 and <envar>SSL_CERT_FILE</envar> environment variables.
2007 </para>
2008 <note>
2009 <para>
2010 When using <literal>sslrootcert=system</literal>, the default
2011 <literal>sslmode</literal> is changed to <literal>verify-full</literal>,
2012 and any weaker setting will result in an error. In most cases it is
2013 trivial for anyone to obtain a certificate trusted by the system for a
2014 hostname they control, rendering <literal>verify-ca</literal> and all
2015 weaker modes useless.
2016 </para>
2017 <para>
2018 The magic <literal>system</literal> value will take precedence over a
2019 local certificate file with the same name. If for some reason you find
2020 yourself in this situation, use an alternative path like
2021 <literal>sslrootcert=./system</literal> instead.
2022 </para>
2023 </note>
2024 </listitem>
2025 </varlistentry>
2027 <varlistentry id="libpq-connect-sslcrl" xreflabel="sslcrl">
2028 <term><literal>sslcrl</literal></term>
2029 <listitem>
2030 <para>
2031 This parameter specifies the file name of the SSL server certificate
2032 revocation list (CRL). Certificates listed in this file, if it
2033 exists, will be rejected while attempting to authenticate the
2034 server's certificate. If neither
2035 <xref linkend="libpq-connect-sslcrl"/> nor
2036 <xref linkend="libpq-connect-sslcrldir"/> is set, this setting is
2037 taken as
2038 <filename>~/.postgresql/root.crl</filename>.
2039 </para>
2040 </listitem>
2041 </varlistentry>
2043 <varlistentry id="libpq-connect-sslcrldir" xreflabel="sslcrldir">
2044 <term><literal>sslcrldir</literal></term>
2045 <listitem>
2046 <para>
2047 This parameter specifies the directory name of the SSL server certificate
2048 revocation list (CRL). Certificates listed in the files in this
2049 directory, if it exists, will be rejected while attempting to
2050 authenticate the server's certificate.
2051 </para>
2053 <para>
2054 The directory needs to be prepared with the
2055 <productname>OpenSSL</productname> command
2056 <literal>openssl rehash</literal> or <literal>c_rehash</literal>. See
2057 its documentation for details.
2058 </para>
2060 <para>
2061 Both <literal>sslcrl</literal> and <literal>sslcrldir</literal> can be
2062 specified together.
2063 </para>
2064 </listitem>
2065 </varlistentry>
2067 <varlistentry id="libpq-connect-sslsni" xreflabel="sslsni">
2068 <term><literal>sslsni</literal><indexterm><primary>Server Name Indication</primary></indexterm></term>
2069 <listitem>
2070 <para>
2071 If set to 1 (default), libpq sets the TLS extension <quote>Server Name
2072 Indication</quote> (<acronym>SNI</acronym>) on SSL-enabled connections.
2073 By setting this parameter to 0, this is turned off.
2074 </para>
2076 <para>
2077 The Server Name Indication can be used by SSL-aware proxies to route
2078 connections without having to decrypt the SSL stream. (Note that
2079 unless the proxy is aware of the PostgreSQL protocol handshake this
2080 would require setting <literal>sslnegotiation</literal>
2081 to <literal>direct</literal>.)
2082 However, <acronym>SNI</acronym> makes the destination host name appear
2083 in cleartext in the network traffic, so it might be undesirable in
2084 some cases.
2085 </para>
2086 </listitem>
2087 </varlistentry>
2089 <varlistentry id="libpq-connect-requirepeer" xreflabel="requirepeer">
2090 <term><literal>requirepeer</literal></term>
2091 <listitem>
2092 <para>
2093 This parameter specifies the operating-system user name of the
2094 server, for example <literal>requirepeer=postgres</literal>.
2095 When making a Unix-domain socket connection, if this
2096 parameter is set, the client checks at the beginning of the
2097 connection that the server process is running under the specified
2098 user name; if it is not, the connection is aborted with an error.
2099 This parameter can be used to provide server authentication similar
2100 to that available with SSL certificates on TCP/IP connections.
2101 (Note that if the Unix-domain socket is in
2102 <filename>/tmp</filename> or another publicly writable location,
2103 any user could start a server listening there. Use this parameter
2104 to ensure that you are connected to a server run by a trusted user.)
2105 This option is only supported on platforms for which the
2106 <literal>peer</literal> authentication method is implemented; see
2107 <xref linkend="auth-peer"/>.
2108 </para>
2109 </listitem>
2110 </varlistentry>
2112 <varlistentry id="libpq-connect-ssl-min-protocol-version" xreflabel="ssl_min_protocol_version">
2113 <term><literal>ssl_min_protocol_version</literal></term>
2114 <listitem>
2115 <para>
2116 This parameter specifies the minimum SSL/TLS protocol version to allow
2117 for the connection. Valid values are <literal>TLSv1</literal>,
2118 <literal>TLSv1.1</literal>, <literal>TLSv1.2</literal> and
2119 <literal>TLSv1.3</literal>. The supported protocols depend on the
2120 version of <productname>OpenSSL</productname> used, older versions
2121 not supporting the most modern protocol versions. If not specified,
2122 the default is <literal>TLSv1.2</literal>, which satisfies industry
2123 best practices as of this writing.
2124 </para>
2125 </listitem>
2126 </varlistentry>
2128 <varlistentry id="libpq-connect-ssl-max-protocol-version" xreflabel="ssl_max_protocol_version">
2129 <term><literal>ssl_max_protocol_version</literal></term>
2130 <listitem>
2131 <para>
2132 This parameter specifies the maximum SSL/TLS protocol version to allow
2133 for the connection. Valid values are <literal>TLSv1</literal>,
2134 <literal>TLSv1.1</literal>, <literal>TLSv1.2</literal> and
2135 <literal>TLSv1.3</literal>. The supported protocols depend on the
2136 version of <productname>OpenSSL</productname> used, older versions
2137 not supporting the most modern protocol versions. If not set, this
2138 parameter is ignored and the connection will use the maximum bound
2139 defined by the backend, if set. Setting the maximum protocol version
2140 is mainly useful for testing or if some component has issues working
2141 with a newer protocol.
2142 </para>
2143 </listitem>
2144 </varlistentry>
2146 <varlistentry id="libpq-connect-krbsrvname" xreflabel="krbsrvname">
2147 <term><literal>krbsrvname</literal></term>
2148 <listitem>
2149 <para>
2150 Kerberos service name to use when authenticating with GSSAPI.
2151 This must match the service name specified in the server
2152 configuration for Kerberos authentication to succeed. (See also
2153 <xref linkend="gssapi-auth"/>.)
2154 The default value is normally <literal>postgres</literal>,
2155 but that can be changed when
2156 building <productname>PostgreSQL</productname> via
2157 the <option>--with-krb-srvnam</option> option
2158 of <application>configure</application>.
2159 In most environments, this parameter never needs to be changed.
2160 Some Kerberos implementations might require a different service name,
2161 such as Microsoft Active Directory which requires the service name
2162 to be in upper case (<literal>POSTGRES</literal>).
2163 </para>
2164 </listitem>
2165 </varlistentry>
2167 <varlistentry id="libpq-connect-gsslib" xreflabel="gsslib">
2168 <term><literal>gsslib</literal></term>
2169 <listitem>
2170 <para>
2171 GSS library to use for GSSAPI authentication.
2172 Currently this is disregarded except on Windows builds that include
2173 both GSSAPI and SSPI support. In that case, set
2174 this to <literal>gssapi</literal> to cause libpq to use the GSSAPI
2175 library for authentication instead of the default SSPI.
2176 </para>
2177 </listitem>
2178 </varlistentry>
2180 <varlistentry id="libpq-connect-gssdelegation" xreflabel="gssdelegation">
2181 <term><literal>gssdelegation</literal></term>
2182 <listitem>
2183 <para>
2184 Forward (delegate) GSS credentials to the server. The default is
2185 <literal>0</literal> which means credentials will not be forwarded
2186 to the server. Set this to <literal>1</literal> to have credentials
2187 forwarded when possible.
2188 </para>
2189 </listitem>
2190 </varlistentry>
2192 <varlistentry id="libpq-connect-service" xreflabel="service">
2193 <term><literal>service</literal></term>
2194 <listitem>
2195 <para>
2196 Service name to use for additional parameters. It specifies a service
2197 name in <filename>pg_service.conf</filename> that holds additional connection parameters.
2198 This allows applications to specify only a service name so connection parameters
2199 can be centrally maintained. See <xref linkend="libpq-pgservice"/>.
2200 </para>
2201 </listitem>
2202 </varlistentry>
2204 <varlistentry id="libpq-connect-target-session-attrs" xreflabel="target_session_attrs">
2205 <term><literal>target_session_attrs</literal></term>
2206 <listitem>
2207 <para>
2208 This option determines whether the session must have certain
2209 properties to be acceptable. It's typically used in combination
2210 with multiple host names to select the first acceptable alternative
2211 among several hosts. There are six modes:
2213 <variablelist>
2214 <varlistentry>
2215 <term><literal>any</literal> (default)</term>
2216 <listitem>
2217 <para>
2218 any successful connection is acceptable
2219 </para>
2220 </listitem>
2221 </varlistentry>
2223 <varlistentry>
2224 <term><literal>read-write</literal></term>
2225 <listitem>
2226 <para>
2227 session must accept read-write transactions by default (that
2228 is, the server must not be in hot standby mode and
2229 the <varname>default_transaction_read_only</varname> parameter
2230 must be <literal>off</literal>)
2231 </para>
2232 </listitem>
2233 </varlistentry>
2235 <varlistentry>
2236 <term><literal>read-only</literal></term>
2237 <listitem>
2238 <para>
2239 session must not accept read-write transactions by default (the
2240 converse)
2241 </para>
2242 </listitem>
2243 </varlistentry>
2245 <varlistentry>
2246 <term><literal>primary</literal></term>
2247 <listitem>
2248 <para>
2249 server must not be in hot standby mode
2250 </para>
2251 </listitem>
2252 </varlistentry>
2254 <varlistentry>
2255 <term><literal>standby</literal></term>
2256 <listitem>
2257 <para>
2258 server must be in hot standby mode
2259 </para>
2260 </listitem>
2261 </varlistentry>
2263 <varlistentry>
2264 <term><literal>prefer-standby</literal></term>
2265 <listitem>
2266 <para>
2267 first try to find a standby server, but if none of the listed
2268 hosts is a standby server, try again in <literal>any</literal>
2269 mode
2270 </para>
2271 </listitem>
2272 </varlistentry>
2273 </variablelist>
2274 </para>
2275 </listitem>
2276 </varlistentry>
2278 <varlistentry id="libpq-connect-load-balance-hosts" xreflabel="load_balance_hosts">
2279 <term><literal>load_balance_hosts</literal></term>
2280 <listitem>
2281 <para>
2282 Controls the order in which the client tries to connect to the available
2283 hosts and addresses. Once a connection attempt is successful no other
2284 hosts and addresses will be tried. This parameter is typically used in
2285 combination with multiple host names or a DNS record that returns
2286 multiple IPs. This parameter can be used in combination with
2287 <xref linkend="libpq-connect-target-session-attrs"/>
2288 to, for example, load balance over standby servers only. Once successfully
2289 connected, subsequent queries on the returned connection will all be
2290 sent to the same server. There are currently two modes:
2291 <variablelist>
2292 <varlistentry>
2293 <term><literal>disable</literal> (default)</term>
2294 <listitem>
2295 <para>
2296 No load balancing across hosts is performed. Hosts are tried in
2297 the order in which they are provided and addresses are tried in
2298 the order they are received from DNS or a hosts file.
2299 </para>
2300 </listitem>
2301 </varlistentry>
2303 <varlistentry>
2304 <term><literal>random</literal></term>
2305 <listitem>
2306 <para>
2307 Hosts and addresses are tried in random order. This value is mostly
2308 useful when opening multiple connections at the same time, possibly
2309 from different machines. This way connections can be load balanced
2310 across multiple <productname>PostgreSQL</productname> servers.
2311 </para>
2312 <para>
2313 While random load balancing, due to its random nature, will almost
2314 never result in a completely uniform distribution, it statistically
2315 gets quite close. One important aspect here is that this algorithm
2316 uses two levels of random choices: First the hosts
2317 will be resolved in random order. Then secondly, before resolving
2318 the next host, all resolved addresses for the current host will be
2319 tried in random order. This behaviour can skew the amount of
2320 connections each node gets greatly in certain cases, for instance
2321 when some hosts resolve to more addresses than others. But such a
2322 skew can also be used on purpose, e.g. to increase the number of
2323 connections a larger server gets by providing its hostname multiple
2324 times in the host string.
2325 </para>
2326 <para>
2327 When using this value it's recommended to also configure a reasonable
2328 value for <xref linkend="libpq-connect-connect-timeout"/>. Because then,
2329 if one of the nodes that are used for load balancing is not responding,
2330 a new node will be tried.
2331 </para>
2332 </listitem>
2333 </varlistentry>
2334 </variablelist>
2335 </para>
2336 </listitem>
2337 </varlistentry>
2338 </variablelist>
2339 </para>
2340 </sect2>
2341 </sect1>
2343 <sect1 id="libpq-status">
2344 <title>Connection Status Functions</title>
2346 <para>
2347 These functions can be used to interrogate the status
2348 of an existing database connection object.
2349 </para>
2351 <tip>
2352 <para>
2353 <indexterm><primary>libpq-fe.h</primary></indexterm>
2354 <indexterm><primary>libpq-int.h</primary></indexterm>
2355 <application>libpq</application> application programmers should be careful to
2356 maintain the <structname>PGconn</structname> abstraction. Use the accessor
2357 functions described below to get at the contents of <structname>PGconn</structname>.
2358 Reference to internal <structname>PGconn</structname> fields using
2359 <filename>libpq-int.h</filename> is not recommended because they are subject to change
2360 in the future.
2361 </para>
2362 </tip>
2364 <para>
2365 The following functions return parameter values established at connection.
2366 These values are fixed for the life of the connection. If a multi-host
2367 connection string is used, the values of <xref linkend="libpq-PQhost"/>,
2368 <xref linkend="libpq-PQport"/>, and <xref linkend="libpq-PQpass"/> can change if a new connection
2369 is established using the same <structname>PGconn</structname> object. Other values
2370 are fixed for the lifetime of the <structname>PGconn</structname> object.
2372 <variablelist>
2373 <varlistentry id="libpq-PQdb">
2374 <term><function>PQdb</function><indexterm><primary>PQdb</primary></indexterm></term>
2376 <listitem>
2377 <para>
2378 Returns the database name of the connection.
2379 <synopsis>
2380 char *PQdb(const PGconn *conn);
2381 </synopsis>
2382 </para>
2383 </listitem>
2384 </varlistentry>
2386 <varlistentry id="libpq-PQuser">
2387 <term><function>PQuser</function><indexterm><primary>PQuser</primary></indexterm></term>
2389 <listitem>
2390 <para>
2391 Returns the user name of the connection.
2392 <synopsis>
2393 char *PQuser(const PGconn *conn);
2394 </synopsis>
2395 </para>
2396 </listitem>
2397 </varlistentry>
2399 <varlistentry id="libpq-PQpass">
2400 <term><function>PQpass</function><indexterm><primary>PQpass</primary></indexterm></term>
2402 <listitem>
2403 <para>
2404 Returns the password of the connection.
2405 <synopsis>
2406 char *PQpass(const PGconn *conn);
2407 </synopsis>
2408 </para>
2410 <para>
2411 <xref linkend="libpq-PQpass"/> will return either the password specified
2412 in the connection parameters, or if there was none and the password
2413 was obtained from the <link linkend="libpq-pgpass">password
2414 file</link>, it will return that. In the latter case,
2415 if multiple hosts were specified in the connection parameters, it is
2416 not possible to rely on the result of <xref linkend="libpq-PQpass"/> until
2417 the connection is established. The status of the connection can be
2418 checked using the function <xref linkend="libpq-PQstatus"/>.
2419 </para>
2420 </listitem>
2421 </varlistentry>
2423 <varlistentry id="libpq-PQhost">
2424 <term><function>PQhost</function><indexterm><primary>PQhost</primary></indexterm></term>
2426 <listitem>
2427 <para>
2428 Returns the server host name of the active connection.
2429 This can be a host name, an IP address, or a directory path if the
2430 connection is via Unix socket. (The path case can be distinguished
2431 because it will always be an absolute path, beginning
2432 with <literal>/</literal>.)
2433 <synopsis>
2434 char *PQhost(const PGconn *conn);
2435 </synopsis>
2436 </para>
2438 <para>
2439 If the connection parameters specified both <literal>host</literal> and
2440 <literal>hostaddr</literal>, then <xref linkend="libpq-PQhost"/> will
2441 return the <literal>host</literal> information. If only
2442 <literal>hostaddr</literal> was specified, then that is returned.
2443 If multiple hosts were specified in the connection parameters,
2444 <xref linkend="libpq-PQhost"/> returns the host actually connected to.
2445 </para>
2447 <para>
2448 <xref linkend="libpq-PQhost"/> returns <symbol>NULL</symbol> if the
2449 <parameter>conn</parameter> argument is <symbol>NULL</symbol>.
2450 Otherwise, if there is an error producing the host information (perhaps
2451 if the connection has not been fully established or there was an
2452 error), it returns an empty string.
2453 </para>
2455 <para>
2456 If multiple hosts were specified in the connection parameters, it is
2457 not possible to rely on the result of <xref linkend="libpq-PQhost"/> until
2458 the connection is established. The status of the connection can be
2459 checked using the function <xref linkend="libpq-PQstatus"/>.
2460 </para>
2461 </listitem>
2462 </varlistentry>
2465 <varlistentry id="libpq-PQhostaddr">
2466 <term><function>PQhostaddr</function><indexterm><primary>PQhostaddr</primary></indexterm></term>
2468 <listitem>
2469 <para>
2470 Returns the server IP address of the active connection.
2471 This can be the address that a host name resolved to,
2472 or an IP address provided through the <literal>hostaddr</literal>
2473 parameter.
2474 <synopsis>
2475 char *PQhostaddr(const PGconn *conn);
2476 </synopsis>
2477 </para>
2479 <para>
2480 <xref linkend="libpq-PQhostaddr"/> returns <symbol>NULL</symbol> if the
2481 <parameter>conn</parameter> argument is <symbol>NULL</symbol>.
2482 Otherwise, if there is an error producing the host information
2483 (perhaps if the connection has not been fully established or
2484 there was an error), it returns an empty string.
2485 </para>
2486 </listitem>
2487 </varlistentry>
2489 <varlistentry id="libpq-PQport">
2490 <term><function>PQport</function><indexterm><primary>PQport</primary></indexterm></term>
2492 <listitem>
2493 <para>
2494 Returns the port of the active connection.
2496 <synopsis>
2497 char *PQport(const PGconn *conn);
2498 </synopsis>
2499 </para>
2501 <para>
2502 If multiple ports were specified in the connection parameters,
2503 <xref linkend="libpq-PQport"/> returns the port actually connected to.
2504 </para>
2506 <para>
2507 <xref linkend="libpq-PQport"/> returns <symbol>NULL</symbol> if the
2508 <parameter>conn</parameter> argument is <symbol>NULL</symbol>.
2509 Otherwise, if there is an error producing the port information (perhaps
2510 if the connection has not been fully established or there was an
2511 error), it returns an empty string.
2512 </para>
2514 <para>
2515 If multiple ports were specified in the connection parameters, it is
2516 not possible to rely on the result of <xref linkend="libpq-PQport"/> until
2517 the connection is established. The status of the connection can be
2518 checked using the function <xref linkend="libpq-PQstatus"/>.
2519 </para>
2520 </listitem>
2521 </varlistentry>
2523 <varlistentry id="libpq-PQtty">
2524 <term><function>PQtty</function><indexterm><primary>PQtty</primary></indexterm></term>
2526 <listitem>
2527 <para>
2528 This function no longer does anything, but it remains for backwards
2529 compatibility. The function always return an empty string, or
2530 <symbol>NULL</symbol> if the <parameter>conn</parameter> argument is
2531 <symbol>NULL</symbol>.
2533 <synopsis>
2534 char *PQtty(const PGconn *conn);
2535 </synopsis>
2536 </para>
2537 </listitem>
2538 </varlistentry>
2540 <varlistentry id="libpq-PQoptions">
2541 <term><function>PQoptions</function><indexterm><primary>PQoptions</primary></indexterm></term>
2543 <listitem>
2544 <para>
2545 Returns the command-line options passed in the connection request.
2546 <synopsis>
2547 char *PQoptions(const PGconn *conn);
2548 </synopsis>
2549 </para>
2550 </listitem>
2551 </varlistentry>
2552 </variablelist>
2553 </para>
2555 <para>
2556 The following functions return status data that can change as operations
2557 are executed on the <structname>PGconn</structname> object.
2559 <variablelist>
2560 <varlistentry id="libpq-PQstatus">
2561 <term><function>PQstatus</function><indexterm><primary>PQstatus</primary></indexterm></term>
2563 <listitem>
2564 <para>
2565 Returns the status of the connection.
2566 <synopsis>
2567 ConnStatusType PQstatus(const PGconn *conn);
2568 </synopsis>
2569 </para>
2571 <para>
2572 The status can be one of a number of values. However, only two of
2573 these are seen outside of an asynchronous connection procedure:
2574 <literal>CONNECTION_OK</literal> and
2575 <literal>CONNECTION_BAD</literal>. A good connection to the database
2576 has the status <literal>CONNECTION_OK</literal>. A failed
2577 connection attempt is signaled by status
2578 <literal>CONNECTION_BAD</literal>. Ordinarily, an OK status will
2579 remain so until <xref linkend="libpq-PQfinish"/>, but a communications
2580 failure might result in the status changing to
2581 <literal>CONNECTION_BAD</literal> prematurely. In that case the
2582 application could try to recover by calling
2583 <xref linkend="libpq-PQreset"/>.
2584 </para>
2586 <para>
2587 See the entry for <xref linkend="libpq-PQconnectStartParams"/>, <function>PQconnectStart</function>
2588 and <function>PQconnectPoll</function> with regards to other status codes that
2589 might be returned.
2590 </para>
2591 </listitem>
2592 </varlistentry>
2594 <varlistentry id="libpq-PQtransactionStatus">
2595 <term><function>PQtransactionStatus</function><indexterm><primary>PQtransactionStatus</primary></indexterm></term>
2597 <listitem>
2598 <para>
2599 Returns the current in-transaction status of the server.
2601 <synopsis>
2602 PGTransactionStatusType PQtransactionStatus(const PGconn *conn);
2603 </synopsis>
2605 The status can be <literal>PQTRANS_IDLE</literal> (currently idle),
2606 <literal>PQTRANS_ACTIVE</literal> (a command is in progress),
2607 <literal>PQTRANS_INTRANS</literal> (idle, in a valid transaction block),
2608 or <literal>PQTRANS_INERROR</literal> (idle, in a failed transaction block).
2609 <literal>PQTRANS_UNKNOWN</literal> is reported if the connection is bad.
2610 <literal>PQTRANS_ACTIVE</literal> is reported only when a query
2611 has been sent to the server and not yet completed.
2612 </para>
2613 </listitem>
2614 </varlistentry>
2616 <varlistentry id="libpq-PQparameterStatus">
2617 <term><function>PQparameterStatus</function><indexterm><primary>PQparameterStatus</primary></indexterm></term>
2619 <listitem>
2620 <para>
2621 Looks up a current parameter setting of the server.
2623 <synopsis>
2624 const char *PQparameterStatus(const PGconn *conn, const char *paramName);
2625 </synopsis>
2627 Certain parameter values are reported by the server automatically at
2628 connection startup or whenever their values change.
2629 <xref linkend="libpq-PQparameterStatus"/> can be used to interrogate these settings.
2630 It returns the current value of a parameter if known, or <symbol>NULL</symbol>
2631 if the parameter is not known.
2632 </para>
2634 <para>
2635 Parameters reported as of the current release include:
2636 <simplelist type="vert" columns="2">
2637 <member><varname>application_name</varname></member>
2638 <member><varname>client_encoding</varname></member>
2639 <member><varname>DateStyle</varname></member>
2640 <member><varname>default_transaction_read_only</varname></member>
2641 <member><varname>in_hot_standby</varname></member>
2642 <member><varname>integer_datetimes</varname></member>
2643 <member><varname>IntervalStyle</varname></member>
2644 <member><varname>is_superuser</varname></member>
2645 <member><varname>scram_iterations</varname></member>
2646 <member><varname>server_encoding</varname></member>
2647 <member><varname>server_version</varname></member>
2648 <member><varname>session_authorization</varname></member>
2649 <member><varname>standard_conforming_strings</varname></member>
2650 <member><varname>TimeZone</varname></member>
2651 </simplelist>
2652 (<varname>default_transaction_read_only</varname> and
2653 <varname>in_hot_standby</varname> were not reported by releases before
2654 14; <varname>scram_iterations</varname> was not reported by releases
2655 before 16.)
2656 Note that
2657 <varname>server_version</varname>,
2658 <varname>server_encoding</varname> and
2659 <varname>integer_datetimes</varname>
2660 cannot change after startup.
2661 </para>
2663 <para>
2664 If no value for <varname>standard_conforming_strings</varname> is reported,
2665 applications can assume it is <literal>off</literal>, that is, backslashes
2666 are treated as escapes in string literals. Also, the presence of
2667 this parameter can be taken as an indication that the escape string
2668 syntax (<literal>E'...'</literal>) is accepted.
2669 </para>
2671 <para>
2672 Although the returned pointer is declared <literal>const</literal>, it in fact
2673 points to mutable storage associated with the <literal>PGconn</literal> structure.
2674 It is unwise to assume the pointer will remain valid across queries.
2675 </para>
2676 </listitem>
2677 </varlistentry>
2679 <varlistentry id="libpq-PQprotocolVersion">
2680 <term><function>PQprotocolVersion</function><indexterm><primary>PQprotocolVersion</primary></indexterm></term>
2682 <listitem>
2683 <para>
2684 Interrogates the frontend/backend protocol being used.
2685 <synopsis>
2686 int PQprotocolVersion(const PGconn *conn);
2687 </synopsis>
2688 Applications might wish to use this function to determine whether certain
2689 features are supported. Currently, the possible values are 3
2690 (3.0 protocol), or zero (connection bad). The protocol version will
2691 not change after connection startup is complete, but it could
2692 theoretically change during a connection reset. The 3.0 protocol is
2693 supported by <productname>PostgreSQL</productname> server versions 7.4
2694 and above.
2695 </para>
2696 </listitem>
2697 </varlistentry>
2699 <varlistentry id="libpq-PQserverVersion">
2700 <term><function>PQserverVersion</function><indexterm><primary>PQserverVersion</primary></indexterm></term>
2702 <listitem>
2703 <para>
2704 Returns an integer representing the server version.
2705 <synopsis>
2706 int PQserverVersion(const PGconn *conn);
2707 </synopsis>
2708 </para>
2710 <para>
2711 Applications might use this function to determine the version of the
2712 database server they are connected to. The result is formed by
2713 multiplying the server's major version number by 10000 and adding
2714 the minor version number. For example, version 10.1 will be
2715 returned as 100001, and version 11.0 will be returned as 110000.
2716 Zero is returned if the connection is bad.
2717 </para>
2719 <para>
2720 Prior to major version 10, <productname>PostgreSQL</productname> used
2721 three-part version numbers in which the first two parts together
2722 represented the major version. For those
2723 versions, <xref linkend="libpq-PQserverVersion"/> uses two digits for each
2724 part; for example version 9.1.5 will be returned as 90105, and
2725 version 9.2.0 will be returned as 90200.
2726 </para>
2728 <para>
2729 Therefore, for purposes of determining feature compatibility,
2730 applications should divide the result of <xref linkend="libpq-PQserverVersion"/>
2731 by 100 not 10000 to determine a logical major version number.
2732 In all release series, only the last two digits differ between
2733 minor releases (bug-fix releases).
2734 </para>
2735 </listitem>
2736 </varlistentry>
2738 <varlistentry id="libpq-PQerrorMessage">
2739 <term>
2740 <function>PQerrorMessage</function><indexterm><primary>PQerrorMessage</primary></indexterm>
2741 <indexterm><primary>error message</primary><secondary>in <structname>PGconn</structname></secondary></indexterm>
2742 </term>
2744 <listitem>
2745 <para>
2746 Returns the error message most recently generated by
2747 an operation on the connection.
2749 <synopsis>
2750 char *PQerrorMessage(const PGconn *conn);
2751 </synopsis>
2752 </para>
2754 <para>
2755 Nearly all <application>libpq</application> functions will set a message for
2756 <xref linkend="libpq-PQerrorMessage"/> if they fail. Note that by
2757 <application>libpq</application> convention, a nonempty
2758 <xref linkend="libpq-PQerrorMessage"/> result can consist of multiple lines,
2759 and will include a trailing newline. The caller should not free
2760 the result directly. It will be freed when the associated
2761 <structname>PGconn</structname> handle is passed to
2762 <xref linkend="libpq-PQfinish"/>. The result string should not be
2763 expected to remain the same across operations on the
2764 <literal>PGconn</literal> structure.
2765 </para>
2766 </listitem>
2767 </varlistentry>
2769 <varlistentry id="libpq-PQsocket">
2770 <term><function>PQsocket</function><indexterm><primary>PQsocket</primary></indexterm></term>
2771 <listitem>
2772 <para>
2773 Obtains the file descriptor number of the connection socket to
2774 the server. A valid descriptor will be greater than or equal
2775 to 0; a result of -1 indicates that no server connection is
2776 currently open. (This will not change during normal operation,
2777 but could change during connection setup or reset.)
2779 <synopsis>
2780 int PQsocket(const PGconn *conn);
2781 </synopsis>
2783 </para>
2784 </listitem>
2785 </varlistentry>
2787 <varlistentry id="libpq-PQbackendPID">
2788 <term><function>PQbackendPID</function><indexterm><primary>PQbackendPID</primary></indexterm></term>
2789 <listitem>
2790 <para>
2791 Returns the process <acronym>ID</acronym> (PID)<indexterm>
2792 <primary>PID</primary>
2793 <secondary>determining PID of server process</secondary>
2794 <tertiary>in libpq</tertiary>
2795 </indexterm>
2796 of the backend process handling this connection.
2798 <synopsis>
2799 int PQbackendPID(const PGconn *conn);
2800 </synopsis>
2801 </para>
2803 <para>
2804 The backend <acronym>PID</acronym> is useful for debugging
2805 purposes and for comparison to <command>NOTIFY</command>
2806 messages (which include the <acronym>PID</acronym> of the
2807 notifying backend process). Note that the
2808 <acronym>PID</acronym> belongs to a process executing on the
2809 database server host, not the local host!
2810 </para>
2811 </listitem>
2812 </varlistentry>
2814 <varlistentry id="libpq-PQconnectionNeedsPassword">
2815 <term><function>PQconnectionNeedsPassword</function><indexterm><primary>PQconnectionNeedsPassword</primary></indexterm></term>
2816 <listitem>
2817 <para>
2818 Returns true (1) if the connection authentication method
2819 required a password, but none was available.
2820 Returns false (0) if not.
2822 <synopsis>
2823 int PQconnectionNeedsPassword(const PGconn *conn);
2824 </synopsis>
2825 </para>
2827 <para>
2828 This function can be applied after a failed connection attempt
2829 to decide whether to prompt the user for a password.
2830 </para>
2831 </listitem>
2832 </varlistentry>
2834 <varlistentry id="libpq-PQconnectionUsedPassword">
2835 <term><function>PQconnectionUsedPassword</function><indexterm><primary>PQconnectionUsedPassword</primary></indexterm></term>
2836 <listitem>
2837 <para>
2838 Returns true (1) if the connection authentication method
2839 used a password. Returns false (0) if not.
2841 <synopsis>
2842 int PQconnectionUsedPassword(const PGconn *conn);
2843 </synopsis>
2844 </para>
2846 <para>
2847 This function can be applied after either a failed or successful
2848 connection attempt to detect whether the server demanded a password.
2849 </para>
2850 </listitem>
2851 </varlistentry>
2853 <varlistentry id="libpq-PQconnectionUsedGSSAPI">
2854 <term><function>PQconnectionUsedGSSAPI</function><indexterm><primary>PQconnectionUsedGSSAPI</primary></indexterm></term>
2855 <listitem>
2856 <para>
2857 Returns true (1) if the connection authentication method
2858 used GSSAPI. Returns false (0) if not.
2860 <synopsis>
2861 int PQconnectionUsedGSSAPI(const PGconn *conn);
2862 </synopsis>
2863 </para>
2865 <para>
2866 This function can be applied to detect whether the connection was
2867 authenticated with GSSAPI.
2868 </para>
2869 </listitem>
2870 </varlistentry>
2871 </variablelist>
2872 </para>
2874 <para>
2875 The following functions return information related to SSL. This information
2876 usually doesn't change after a connection is established.
2878 <variablelist>
2879 <varlistentry id="libpq-PQsslInUse">
2880 <term><function>PQsslInUse</function><indexterm><primary>PQsslInUse</primary></indexterm></term>
2881 <listitem>
2882 <para>
2883 Returns true (1) if the connection uses SSL, false (0) if not.
2885 <synopsis>
2886 int PQsslInUse(const PGconn *conn);
2887 </synopsis>
2888 </para>
2890 </listitem>
2891 </varlistentry>
2893 <varlistentry id="libpq-PQsslAttribute">
2894 <term><function>PQsslAttribute</function><indexterm><primary>PQsslAttribute</primary></indexterm></term>
2895 <listitem>
2896 <para>
2897 Returns SSL-related information about the connection.
2899 <synopsis>
2900 const char *PQsslAttribute(const PGconn *conn, const char *attribute_name);
2901 </synopsis>
2902 </para>
2904 <para>
2905 The list of available attributes varies depending on the SSL library
2906 being used and the type of connection. Returns NULL if the connection
2907 does not use SSL or the specified attribute name is not defined for the
2908 library in use.
2909 </para>
2911 <para>
2912 The following attributes are commonly available:
2913 <variablelist>
2914 <varlistentry>
2915 <term><literal>library</literal></term>
2916 <listitem>
2917 <para>
2918 Name of the SSL implementation in use. (Currently, only
2919 <literal>"OpenSSL"</literal> is implemented)
2920 </para>
2921 </listitem>
2922 </varlistentry>
2923 <varlistentry>
2924 <term><literal>protocol</literal></term>
2925 <listitem>
2926 <para>
2927 SSL/TLS version in use. Common values
2928 are <literal>"TLSv1"</literal>, <literal>"TLSv1.1"</literal>
2929 and <literal>"TLSv1.2"</literal>, but an implementation may
2930 return other strings if some other protocol is used.
2931 </para>
2932 </listitem>
2933 </varlistentry>
2934 <varlistentry>
2935 <term><literal>key_bits</literal></term>
2936 <listitem>
2937 <para>
2938 Number of key bits used by the encryption algorithm.
2939 </para>
2940 </listitem>
2941 </varlistentry>
2942 <varlistentry>
2943 <term><literal>cipher</literal></term>
2944 <listitem>
2945 <para>
2946 A short name of the ciphersuite used, e.g.,
2947 <literal>"DHE-RSA-DES-CBC3-SHA"</literal>. The names are specific
2948 to each SSL implementation.
2949 </para>
2950 </listitem>
2951 </varlistentry>
2952 <varlistentry>
2953 <term><literal>compression</literal></term>
2954 <listitem>
2955 <para>
2956 Returns "on" if SSL compression is in use, else it returns "off".
2957 </para>
2958 </listitem>
2959 </varlistentry>
2960 <varlistentry>
2961 <term><literal>alpn</literal></term>
2962 <listitem>
2963 <para>
2964 Application protocol selected by the TLS Application-Layer
2965 Protocol Negotiation (ALPN) extension. The only protocol
2966 supported by libpq is <literal>postgresql</literal>, so this is
2967 mainly useful for checking whether the server supported ALPN or
2968 not. Empty string if ALPN was not used.
2969 </para>
2970 </listitem>
2971 </varlistentry>
2972 </variablelist>
2973 </para>
2975 <para>
2976 As a special case, the <literal>library</literal> attribute may be
2977 queried without a connection by passing NULL as
2978 the <literal>conn</literal> argument. The result will be the default
2979 SSL library name, or NULL if <application>libpq</application> was
2980 compiled without any SSL support. (Prior
2981 to <productname>PostgreSQL</productname> version 15, passing NULL as
2982 the <literal>conn</literal> argument always resulted in NULL.
2983 Client programs needing to differentiate between the newer and older
2984 implementations of this case may check the
2985 <literal>LIBPQ_HAS_SSL_LIBRARY_DETECTION</literal> feature macro.)
2986 </para>
2987 </listitem>
2988 </varlistentry>
2990 <varlistentry id="libpq-PQsslAttributeNames">
2991 <term><function>PQsslAttributeNames</function><indexterm><primary>PQsslAttributeNames</primary></indexterm></term>
2992 <listitem>
2993 <para>
2994 Returns an array of SSL attribute names that can be used
2995 in <function>PQsslAttribute()</function>.
2996 The array is terminated by a NULL pointer.
2997 <synopsis>
2998 const char * const * PQsslAttributeNames(const PGconn *conn);
2999 </synopsis>
3000 </para>
3002 <para>
3003 If <literal>conn</literal> is NULL, the attributes available for the
3004 default SSL library are returned, or an empty list
3005 if <application>libpq</application> was compiled without any SSL
3006 support. If <literal>conn</literal> is not NULL, the attributes
3007 available for the SSL library in use for the connection are returned,
3008 or an empty list if the connection is not encrypted.
3009 </para>
3010 </listitem>
3011 </varlistentry>
3013 <varlistentry id="libpq-PQsslStruct">
3014 <term><function>PQsslStruct</function><indexterm><primary>PQsslStruct</primary></indexterm></term>
3015 <listitem>
3016 <para>
3017 Returns a pointer to an SSL-implementation-specific object describing
3018 the connection. Returns NULL if the connection is not encrypted
3019 or the requested type of object is not available from the connection's
3020 SSL implementation.
3021 <synopsis>
3022 void *PQsslStruct(const PGconn *conn, const char *struct_name);
3023 </synopsis>
3024 </para>
3025 <para>
3026 The struct(s) available depend on the SSL implementation in use.
3027 For <productname>OpenSSL</productname>, there is one struct,
3028 available under the name <literal>OpenSSL</literal>,
3029 and it returns a pointer to
3030 <productname>OpenSSL</productname>'s <literal>SSL</literal> struct.
3031 To use this function, code along the following lines could be used:
3032 <programlisting><![CDATA[
3033 #include <libpq-fe.h>
3034 #include <openssl/ssl.h>
3038 SSL *ssl;
3040 dbconn = PQconnectdb(...);
3043 ssl = PQsslStruct(dbconn, "OpenSSL");
3044 if (ssl)
3046 /* use OpenSSL functions to access ssl */
3048 ]]></programlisting>
3049 </para>
3050 <para>
3051 This structure can be used to verify encryption levels, check server
3052 certificates, and more. Refer to the <productname>OpenSSL</productname>
3053 documentation for information about this structure.
3054 </para>
3055 </listitem>
3056 </varlistentry>
3058 <varlistentry id="libpq-PQgetssl">
3059 <term><function>PQgetssl</function><indexterm><primary>PQgetssl</primary></indexterm></term>
3060 <listitem>
3061 <para>
3062 <indexterm><primary>SSL</primary><secondary sortas="libpq">in libpq</secondary></indexterm>
3063 Returns the SSL structure used in the connection, or NULL
3064 if SSL is not in use.
3066 <synopsis>
3067 void *PQgetssl(const PGconn *conn);
3068 </synopsis>
3069 </para>
3071 <para>
3072 This function is equivalent to <literal>PQsslStruct(conn, "OpenSSL")</literal>. It should
3073 not be used in new applications, because the returned struct is
3074 specific to <productname>OpenSSL</productname> and will not be
3075 available if another <acronym>SSL</acronym> implementation is used.
3076 To check if a connection uses SSL, call
3077 <xref linkend="libpq-PQsslInUse"/> instead, and for more details about the
3078 connection, use <xref linkend="libpq-PQsslAttribute"/>.
3079 </para>
3080 </listitem>
3081 </varlistentry>
3083 </variablelist>
3084 </para>
3086 </sect1>
3088 <sect1 id="libpq-exec">
3089 <title>Command Execution Functions</title>
3091 <para>
3092 Once a connection to a database server has been successfully
3093 established, the functions described here are used to perform
3094 SQL queries and commands.
3095 </para>
3097 <sect2 id="libpq-exec-main">
3098 <title>Main Functions</title>
3100 <para>
3101 <variablelist>
3102 <varlistentry id="libpq-PQexec">
3103 <term><function>PQexec</function><indexterm><primary>PQexec</primary></indexterm></term>
3105 <listitem>
3106 <para>
3107 Submits a command to the server and waits for the result.
3109 <synopsis>
3110 PGresult *PQexec(PGconn *conn, const char *command);
3111 </synopsis>
3112 </para>
3114 <para>
3115 Returns a <structname>PGresult</structname> pointer or possibly a null
3116 pointer. A non-null pointer will generally be returned except in
3117 out-of-memory conditions or serious errors such as inability to send
3118 the command to the server. The <xref linkend="libpq-PQresultStatus"/> function
3119 should be called to check the return value for any errors (including
3120 the value of a null pointer, in which case it will return
3121 <symbol>PGRES_FATAL_ERROR</symbol>). Use
3122 <xref linkend="libpq-PQerrorMessage"/> to get more information about such
3123 errors.
3124 </para>
3125 </listitem>
3126 </varlistentry>
3127 </variablelist>
3129 The command string can include multiple SQL commands
3130 (separated by semicolons). Multiple queries sent in a single
3131 <xref linkend="libpq-PQexec"/> call are processed in a single transaction, unless
3132 there are explicit <command>BEGIN</command>/<command>COMMIT</command>
3133 commands included in the query string to divide it into multiple
3134 transactions. (See <xref linkend="protocol-flow-multi-statement"/>
3135 for more details about how the server handles multi-query strings.)
3136 Note however that the returned
3137 <structname>PGresult</structname> structure describes only the result
3138 of the last command executed from the string. Should one of the
3139 commands fail, processing of the string stops with it and the returned
3140 <structname>PGresult</structname> describes the error condition.
3141 </para>
3143 <para>
3144 <variablelist>
3145 <varlistentry id="libpq-PQexecParams">
3146 <term><function>PQexecParams</function><indexterm><primary>PQexecParams</primary></indexterm></term>
3148 <listitem>
3149 <para>
3150 Submits a command to the server and waits for the result,
3151 with the ability to pass parameters separately from the SQL
3152 command text.
3154 <synopsis>
3155 PGresult *PQexecParams(PGconn *conn,
3156 const char *command,
3157 int nParams,
3158 const Oid *paramTypes,
3159 const char * const *paramValues,
3160 const int *paramLengths,
3161 const int *paramFormats,
3162 int resultFormat);
3163 </synopsis>
3164 </para>
3166 <para>
3167 <xref linkend="libpq-PQexecParams"/> is like <xref linkend="libpq-PQexec"/>, but offers additional
3168 functionality: parameter values can be specified separately from the command
3169 string proper, and query results can be requested in either text or binary
3170 format.
3171 </para>
3173 <para>
3174 The function arguments are:
3176 <variablelist>
3177 <varlistentry>
3178 <term><parameter>conn</parameter></term>
3180 <listitem>
3181 <para>
3182 The connection object to send the command through.
3183 </para>
3184 </listitem>
3185 </varlistentry>
3187 <varlistentry>
3188 <term><parameter>command</parameter></term>
3189 <listitem>
3190 <para>
3191 The SQL command string to be executed. If parameters are used,
3192 they are referred to in the command string as <literal>$1</literal>,
3193 <literal>$2</literal>, etc.
3194 </para>
3195 </listitem>
3196 </varlistentry>
3198 <varlistentry>
3199 <term><parameter>nParams</parameter></term>
3200 <listitem>
3201 <para>
3202 The number of parameters supplied; it is the length of the arrays
3203 <parameter>paramTypes[]</parameter>, <parameter>paramValues[]</parameter>,
3204 <parameter>paramLengths[]</parameter>, and <parameter>paramFormats[]</parameter>. (The
3205 array pointers can be <symbol>NULL</symbol> when <parameter>nParams</parameter>
3206 is zero.)
3207 </para>
3208 </listitem>
3209 </varlistentry>
3211 <varlistentry>
3212 <term><parameter>paramTypes[]</parameter></term>
3213 <listitem>
3214 <para>
3215 Specifies, by OID, the data types to be assigned to the
3216 parameter symbols. If <parameter>paramTypes</parameter> is
3217 <symbol>NULL</symbol>, or any particular element in the array
3218 is zero, the server infers a data type for the parameter symbol
3219 in the same way it would do for an untyped literal string.
3220 </para>
3221 </listitem>
3222 </varlistentry>
3224 <varlistentry>
3225 <term><parameter>paramValues[]</parameter></term>
3226 <listitem>
3227 <para>
3228 Specifies the actual values of the parameters. A null pointer
3229 in this array means the corresponding parameter is null;
3230 otherwise the pointer points to a zero-terminated text string
3231 (for text format) or binary data in the format expected by the
3232 server (for binary format).
3233 </para>
3234 </listitem>
3235 </varlistentry>
3237 <varlistentry>
3238 <term><parameter>paramLengths[]</parameter></term>
3239 <listitem>
3240 <para>
3241 Specifies the actual data lengths of binary-format parameters.
3242 It is ignored for null parameters and text-format parameters.
3243 The array pointer can be null when there are no binary parameters.
3244 </para>
3245 </listitem>
3246 </varlistentry>
3248 <varlistentry>
3249 <term><parameter>paramFormats[]</parameter></term>
3250 <listitem>
3251 <para>
3252 Specifies whether parameters are text (put a zero in the
3253 array entry for the corresponding parameter) or binary (put
3254 a one in the array entry for the corresponding parameter).
3255 If the array pointer is null then all parameters are presumed
3256 to be text strings.
3257 </para>
3258 <para>
3259 Values passed in binary format require knowledge of
3260 the internal representation expected by the backend.
3261 For example, integers must be passed in network byte
3262 order. Passing <type>numeric</type> values requires
3263 knowledge of the server storage format, as implemented
3265 <filename>src/backend/utils/adt/numeric.c::numeric_send()</filename> and
3266 <filename>src/backend/utils/adt/numeric.c::numeric_recv()</filename>.
3267 </para>
3268 </listitem>
3269 </varlistentry>
3271 <varlistentry>
3272 <term><parameter>resultFormat</parameter></term>
3273 <listitem>
3274 <para>
3275 Specify zero to obtain results in text format, or one to obtain
3276 results in binary format. (There is not currently a provision
3277 to obtain different result columns in different formats,
3278 although that is possible in the underlying protocol.)
3279 </para>
3280 </listitem>
3281 </varlistentry>
3282 </variablelist>
3283 </para>
3284 </listitem>
3285 </varlistentry>
3286 </variablelist>
3287 </para>
3289 <para>
3290 The primary advantage of <xref linkend="libpq-PQexecParams"/> over
3291 <xref linkend="libpq-PQexec"/> is that parameter values can be separated from the
3292 command string, thus avoiding the need for tedious and error-prone
3293 quoting and escaping.
3294 </para>
3296 <para>
3297 Unlike <xref linkend="libpq-PQexec"/>, <xref linkend="libpq-PQexecParams"/> allows at most
3298 one SQL command in the given string. (There can be semicolons in it,
3299 but not more than one nonempty command.) This is a limitation of the
3300 underlying protocol, but has some usefulness as an extra defense against
3301 SQL-injection attacks.
3302 </para>
3304 <tip>
3305 <para>
3306 Specifying parameter types via OIDs is tedious, particularly if you prefer
3307 not to hard-wire particular OID values into your program. However, you can
3308 avoid doing so even in cases where the server by itself cannot determine the
3309 type of the parameter, or chooses a different type than you want. In the
3310 SQL command text, attach an explicit cast to the parameter symbol to show what
3311 data type you will send. For example:
3312 <programlisting>
3313 SELECT * FROM mytable WHERE x = $1::bigint;
3314 </programlisting>
3315 This forces parameter <literal>$1</literal> to be treated as <type>bigint</type>, whereas
3316 by default it would be assigned the same type as <literal>x</literal>. Forcing the
3317 parameter type decision, either this way or by specifying a numeric type OID,
3318 is strongly recommended when sending parameter values in binary format, because
3319 binary format has less redundancy than text format and so there is less chance
3320 that the server will detect a type mismatch mistake for you.
3321 </para>
3322 </tip>
3324 <para>
3325 <variablelist>
3326 <varlistentry id="libpq-PQprepare">
3327 <term><function>PQprepare</function><indexterm><primary>PQprepare</primary></indexterm></term>
3329 <listitem>
3330 <para>
3331 Submits a request to create a prepared statement with the
3332 given parameters, and waits for completion.
3333 <synopsis>
3334 PGresult *PQprepare(PGconn *conn,
3335 const char *stmtName,
3336 const char *query,
3337 int nParams,
3338 const Oid *paramTypes);
3339 </synopsis>
3340 </para>
3342 <para>
3343 <xref linkend="libpq-PQprepare"/> creates a prepared statement for later
3344 execution with <xref linkend="libpq-PQexecPrepared"/>. This feature allows
3345 commands to be executed repeatedly without being parsed and
3346 planned each time; see <xref linkend="sql-prepare"/> for details.
3347 </para>
3349 <para>
3350 The function creates a prepared statement named
3351 <parameter>stmtName</parameter> from the <parameter>query</parameter> string, which
3352 must contain a single SQL command. <parameter>stmtName</parameter> can be
3353 <literal>""</literal> to create an unnamed statement, in which case any
3354 pre-existing unnamed statement is automatically replaced; otherwise
3355 it is an error if the statement name is already defined in the
3356 current session. If any parameters are used, they are referred
3357 to in the query as <literal>$1</literal>, <literal>$2</literal>, etc.
3358 <parameter>nParams</parameter> is the number of parameters for which types
3359 are pre-specified in the array <parameter>paramTypes[]</parameter>. (The
3360 array pointer can be <symbol>NULL</symbol> when
3361 <parameter>nParams</parameter> is zero.) <parameter>paramTypes[]</parameter>
3362 specifies, by OID, the data types to be assigned to the parameter
3363 symbols. If <parameter>paramTypes</parameter> is <symbol>NULL</symbol>,
3364 or any particular element in the array is zero, the server assigns
3365 a data type to the parameter symbol in the same way it would do
3366 for an untyped literal string. Also, the query can use parameter
3367 symbols with numbers higher than <parameter>nParams</parameter>; data types
3368 will be inferred for these symbols as well. (See
3369 <xref linkend="libpq-PQdescribePrepared"/> for a means to find out
3370 what data types were inferred.)
3371 </para>
3373 <para>
3374 As with <xref linkend="libpq-PQexec"/>, the result is normally a
3375 <structname>PGresult</structname> object whose contents indicate
3376 server-side success or failure. A null result indicates
3377 out-of-memory or inability to send the command at all. Use
3378 <xref linkend="libpq-PQerrorMessage"/> to get more information about
3379 such errors.
3380 </para>
3381 </listitem>
3382 </varlistentry>
3383 </variablelist>
3385 Prepared statements for use with <xref linkend="libpq-PQexecPrepared"/> can also
3386 be created by executing SQL <xref linkend="sql-prepare"/>
3387 statements.
3388 </para>
3390 <para>
3391 <variablelist>
3392 <varlistentry id="libpq-PQexecPrepared">
3393 <term><function>PQexecPrepared</function><indexterm><primary>PQexecPrepared</primary></indexterm></term>
3395 <listitem>
3396 <para>
3397 Sends a request to execute a prepared statement with given
3398 parameters, and waits for the result.
3399 <synopsis>
3400 PGresult *PQexecPrepared(PGconn *conn,
3401 const char *stmtName,
3402 int nParams,
3403 const char * const *paramValues,
3404 const int *paramLengths,
3405 const int *paramFormats,
3406 int resultFormat);
3407 </synopsis>
3408 </para>
3410 <para>
3411 <xref linkend="libpq-PQexecPrepared"/> is like <xref linkend="libpq-PQexecParams"/>,
3412 but the command to be executed is specified by naming a
3413 previously-prepared statement, instead of giving a query string.
3414 This feature allows commands that will be used repeatedly to be
3415 parsed and planned just once, rather than each time they are
3416 executed. The statement must have been prepared previously in
3417 the current session.
3418 </para>
3420 <para>
3421 The parameters are identical to <xref linkend="libpq-PQexecParams"/>, except that the
3422 name of a prepared statement is given instead of a query string, and the
3423 <parameter>paramTypes[]</parameter> parameter is not present (it is not needed since
3424 the prepared statement's parameter types were determined when it was created).
3425 </para>
3426 </listitem>
3427 </varlistentry>
3429 <varlistentry id="libpq-PQdescribePrepared">
3430 <term><function>PQdescribePrepared</function><indexterm><primary>PQdescribePrepared</primary></indexterm></term>
3432 <listitem>
3433 <para>
3434 Submits a request to obtain information about the specified
3435 prepared statement, and waits for completion.
3436 <synopsis>
3437 PGresult *PQdescribePrepared(PGconn *conn, const char *stmtName);
3438 </synopsis>
3439 </para>
3441 <para>
3442 <xref linkend="libpq-PQdescribePrepared"/> allows an application to obtain
3443 information about a previously prepared statement.
3444 </para>
3446 <para>
3447 <parameter>stmtName</parameter> can be <literal>""</literal> or <symbol>NULL</symbol> to reference
3448 the unnamed statement, otherwise it must be the name of an existing
3449 prepared statement. On success, a <structname>PGresult</structname> with
3450 status <literal>PGRES_COMMAND_OK</literal> is returned. The
3451 functions <xref linkend="libpq-PQnparams"/> and
3452 <xref linkend="libpq-PQparamtype"/> can be applied to this
3453 <structname>PGresult</structname> to obtain information about the parameters
3454 of the prepared statement, and the functions
3455 <xref linkend="libpq-PQnfields"/>, <xref linkend="libpq-PQfname"/>,
3456 <xref linkend="libpq-PQftype"/>, etc. provide information about the
3457 result columns (if any) of the statement.
3458 </para>
3459 </listitem>
3460 </varlistentry>
3462 <varlistentry id="libpq-PQdescribePortal">
3463 <term><function>PQdescribePortal</function><indexterm><primary>PQdescribePortal</primary></indexterm></term>
3465 <listitem>
3466 <para>
3467 Submits a request to obtain information about the specified
3468 portal, and waits for completion.
3469 <synopsis>
3470 PGresult *PQdescribePortal(PGconn *conn, const char *portalName);
3471 </synopsis>
3472 </para>
3474 <para>
3475 <xref linkend="libpq-PQdescribePortal"/> allows an application to obtain
3476 information about a previously created portal.
3477 (<application>libpq</application> does not provide any direct access to
3478 portals, but you can use this function to inspect the properties
3479 of a cursor created with a <command>DECLARE CURSOR</command> SQL command.)
3480 </para>
3482 <para>
3483 <parameter>portalName</parameter> can be <literal>""</literal> or <symbol>NULL</symbol> to reference
3484 the unnamed portal, otherwise it must be the name of an existing
3485 portal. On success, a <structname>PGresult</structname> with status
3486 <literal>PGRES_COMMAND_OK</literal> is returned. The functions
3487 <xref linkend="libpq-PQnfields"/>, <xref linkend="libpq-PQfname"/>,
3488 <xref linkend="libpq-PQftype"/>, etc. can be applied to the
3489 <structname>PGresult</structname> to obtain information about the result
3490 columns (if any) of the portal.
3491 </para>
3492 </listitem>
3493 </varlistentry>
3495 <varlistentry id="libpq-PQclosePrepared">
3496 <term><function>PQclosePrepared</function><indexterm><primary>PQclosePrepared</primary></indexterm></term>
3498 <listitem>
3499 <para>
3500 Submits a request to close the specified prepared statement, and waits
3501 for completion.
3502 <synopsis>
3503 PGresult *PQclosePrepared(PGconn *conn, const char *stmtName);
3504 </synopsis>
3505 </para>
3507 <para>
3508 <xref linkend="libpq-PQclosePrepared"/> allows an application to close
3509 a previously prepared statement. Closing a statement releases all
3510 of its associated resources on the server and allows its name to be
3511 reused.
3512 </para>
3514 <para>
3515 <parameter>stmtName</parameter> can be <literal>""</literal> or
3516 <symbol>NULL</symbol> to reference the unnamed statement. It is fine
3517 if no statement exists with this name, in that case the operation is a
3518 no-op. On success, a <structname>PGresult</structname> with
3519 status <literal>PGRES_COMMAND_OK</literal> is returned.
3520 </para>
3521 </listitem>
3522 </varlistentry>
3524 <varlistentry id="libpq-PQclosePortal">
3525 <term><function>PQclosePortal</function><indexterm><primary>PQclosePortal</primary></indexterm></term>
3527 <listitem>
3528 <para>
3529 Submits a request to close the specified portal, and waits for
3530 completion.
3531 <synopsis>
3532 PGresult *PQclosePortal(PGconn *conn, const char *portalName);
3533 </synopsis>
3534 </para>
3536 <para>
3537 <xref linkend="libpq-PQclosePortal"/> allows an application to trigger
3538 a close of a previously created portal. Closing a portal releases all
3539 of its associated resources on the server and allows its name to be
3540 reused. (<application>libpq</application> does not provide any
3541 direct access to portals, but you can use this function to close a
3542 cursor created with a <command>DECLARE CURSOR</command> SQL command.)
3543 </para>
3545 <para>
3546 <parameter>portalName</parameter> can be <literal>""</literal> or
3547 <symbol>NULL</symbol> to reference the unnamed portal. It is fine
3548 if no portal exists with this name, in that case the operation is a
3549 no-op. On success, a <structname>PGresult</structname> with status
3550 <literal>PGRES_COMMAND_OK</literal> is returned.
3551 </para>
3552 </listitem>
3553 </varlistentry>
3554 </variablelist>
3555 </para>
3557 <para>
3558 The <structname>PGresult</structname><indexterm><primary>PGresult</primary></indexterm>
3559 structure encapsulates the result returned by the server.
3560 <application>libpq</application> application programmers should be
3561 careful to maintain the <structname>PGresult</structname> abstraction.
3562 Use the accessor functions below to get at the contents of
3563 <structname>PGresult</structname>. Avoid directly referencing the
3564 fields of the <structname>PGresult</structname> structure because they
3565 are subject to change in the future.
3567 <variablelist>
3568 <varlistentry id="libpq-PQresultStatus">
3569 <term><function>PQresultStatus</function><indexterm><primary>PQresultStatus</primary></indexterm></term>
3571 <listitem>
3572 <para>
3573 Returns the result status of the command.
3574 <synopsis>
3575 ExecStatusType PQresultStatus(const PGresult *res);
3576 </synopsis>
3577 </para>
3579 <para>
3580 <xref linkend="libpq-PQresultStatus"/> can return one of the following values:
3582 <variablelist>
3583 <varlistentry id="libpq-pgres-empty-query">
3584 <term><literal>PGRES_EMPTY_QUERY</literal></term>
3585 <listitem>
3586 <para>
3587 The string sent to the server was empty.
3588 </para>
3589 </listitem>
3590 </varlistentry>
3592 <varlistentry id="libpq-pgres-command-ok">
3593 <term><literal>PGRES_COMMAND_OK</literal></term>
3594 <listitem>
3595 <para>
3596 Successful completion of a command returning no data.
3597 </para>
3598 </listitem>
3599 </varlistentry>
3601 <varlistentry id="libpq-pgres-tuples-ok">
3602 <term><literal>PGRES_TUPLES_OK</literal></term>
3603 <listitem>
3604 <para>
3605 Successful completion of a command returning data (such as
3606 a <command>SELECT</command> or <command>SHOW</command>).
3607 </para>
3608 </listitem>
3609 </varlistentry>
3611 <varlistentry id="libpq-pgres-copy-out">
3612 <term><literal>PGRES_COPY_OUT</literal></term>
3613 <listitem>
3614 <para>
3615 Copy Out (from server) data transfer started.
3616 </para>
3617 </listitem>
3618 </varlistentry>
3620 <varlistentry id="libpq-pgres-copy-in">
3621 <term><literal>PGRES_COPY_IN</literal></term>
3622 <listitem>
3623 <para>
3624 Copy In (to server) data transfer started.
3625 </para>
3626 </listitem>
3627 </varlistentry>
3629 <varlistentry id="libpq-pgres-bad-response">
3630 <term><literal>PGRES_BAD_RESPONSE</literal></term>
3631 <listitem>
3632 <para>
3633 The server's response was not understood.
3634 </para>
3635 </listitem>
3636 </varlistentry>
3638 <varlistentry id="libpq-pgres-nonfatal-error">
3639 <term><literal>PGRES_NONFATAL_ERROR</literal></term>
3640 <listitem>
3641 <para>
3642 A nonfatal error (a notice or warning) occurred.
3643 </para>
3644 </listitem>
3645 </varlistentry>
3647 <varlistentry id="libpq-pgres-fatal-error">
3648 <term><literal>PGRES_FATAL_ERROR</literal></term>
3649 <listitem>
3650 <para>
3651 A fatal error occurred.
3652 </para>
3653 </listitem>
3654 </varlistentry>
3656 <varlistentry id="libpq-pgres-copy-both">
3657 <term><literal>PGRES_COPY_BOTH</literal></term>
3658 <listitem>
3659 <para>
3660 Copy In/Out (to and from server) data transfer started. This
3661 feature is currently used only for streaming replication,
3662 so this status should not occur in ordinary applications.
3663 </para>
3664 </listitem>
3665 </varlistentry>
3667 <varlistentry id="libpq-pgres-single-tuple">
3668 <term><literal>PGRES_SINGLE_TUPLE</literal></term>
3669 <listitem>
3670 <para>
3671 The <structname>PGresult</structname> contains a single result tuple
3672 from the current command. This status occurs only when
3673 single-row mode has been selected for the query
3674 (see <xref linkend="libpq-single-row-mode"/>).
3675 </para>
3676 </listitem>
3677 </varlistentry>
3679 <varlistentry id="libpq-pgres-tuples-chunk">
3680 <term><literal>PGRES_TUPLES_CHUNK</literal></term>
3681 <listitem>
3682 <para>
3683 The <structname>PGresult</structname> contains several result tuples
3684 from the current command. This status occurs only when
3685 chunked mode has been selected for the query
3686 (see <xref linkend="libpq-single-row-mode"/>).
3687 The number of tuples will not exceed the limit passed to
3688 <xref linkend="libpq-PQsetChunkedRowsMode"/>.
3689 </para>
3690 </listitem>
3691 </varlistentry>
3693 <varlistentry id="libpq-pgres-pipeline-sync">
3694 <term><literal>PGRES_PIPELINE_SYNC</literal></term>
3695 <listitem>
3696 <para>
3697 The <structname>PGresult</structname> represents a
3698 synchronization point in pipeline mode, requested by either
3699 <xref linkend="libpq-PQpipelineSync"/> or
3700 <xref linkend="libpq-PQsendPipelineSync"/>.
3701 This status occurs only when pipeline mode has been selected.
3702 </para>
3703 </listitem>
3704 </varlistentry>
3706 <varlistentry id="libpq-pgres-pipeline-aborted">
3707 <term><literal>PGRES_PIPELINE_ABORTED</literal></term>
3708 <listitem>
3709 <para>
3710 The <structname>PGresult</structname> represents a pipeline that has
3711 received an error from the server. <function>PQgetResult</function>
3712 must be called repeatedly, and each time it will return this status code
3713 until the end of the current pipeline, at which point it will return
3714 <literal>PGRES_PIPELINE_SYNC</literal> and normal processing can
3715 resume.
3716 </para>
3717 </listitem>
3718 </varlistentry>
3720 </variablelist>
3722 If the result status is <literal>PGRES_TUPLES_OK</literal>,
3723 <literal>PGRES_SINGLE_TUPLE</literal>, or
3724 <literal>PGRES_TUPLES_CHUNK</literal>, then
3725 the functions described below can be used to retrieve the rows
3726 returned by the query. Note that a <command>SELECT</command>
3727 command that happens to retrieve zero rows still shows
3728 <literal>PGRES_TUPLES_OK</literal>.
3729 <literal>PGRES_COMMAND_OK</literal> is for commands that can never
3730 return rows (<command>INSERT</command> or <command>UPDATE</command>
3731 without a <literal>RETURNING</literal> clause,
3732 etc.). A response of <literal>PGRES_EMPTY_QUERY</literal> might
3733 indicate a bug in the client software.
3734 </para>
3736 <para>
3737 A result of status <symbol>PGRES_NONFATAL_ERROR</symbol> will
3738 never be returned directly by <xref linkend="libpq-PQexec"/> or other
3739 query execution functions; results of this kind are instead passed
3740 to the notice processor (see <xref
3741 linkend="libpq-notice-processing"/>).
3742 </para>
3743 </listitem>
3744 </varlistentry>
3746 <varlistentry id="libpq-PQresStatus">
3747 <term><function>PQresStatus</function><indexterm><primary>PQresStatus</primary></indexterm></term>
3749 <listitem>
3750 <para>
3751 Converts the enumerated type returned by
3752 <xref linkend="libpq-PQresultStatus"/> into a string constant describing the
3753 status code. The caller should not free the result.
3755 <synopsis>
3756 char *PQresStatus(ExecStatusType status);
3757 </synopsis>
3758 </para>
3759 </listitem>
3760 </varlistentry>
3762 <varlistentry id="libpq-PQresultErrorMessage">
3763 <term><function>PQresultErrorMessage</function><indexterm><primary>PQresultErrorMessage</primary></indexterm></term>
3765 <listitem>
3766 <para>
3767 Returns the error message associated with the command, or an empty string
3768 if there was no error.
3769 <synopsis>
3770 char *PQresultErrorMessage(const PGresult *res);
3771 </synopsis>
3772 If there was an error, the returned string will include a trailing
3773 newline. The caller should not free the result directly. It will
3774 be freed when the associated <structname>PGresult</structname> handle is
3775 passed to <xref linkend="libpq-PQclear"/>.
3776 </para>
3778 <para>
3779 Immediately following a <xref linkend="libpq-PQexec"/> or
3780 <xref linkend="libpq-PQgetResult"/> call,
3781 <xref linkend="libpq-PQerrorMessage"/> (on the connection) will return
3782 the same string as <xref linkend="libpq-PQresultErrorMessage"/> (on
3783 the result). However, a <structname>PGresult</structname> will
3784 retain its error message until destroyed, whereas the connection's
3785 error message will change when subsequent operations are done.
3786 Use <xref linkend="libpq-PQresultErrorMessage"/> when you want to
3787 know the status associated with a particular
3788 <structname>PGresult</structname>; use
3789 <xref linkend="libpq-PQerrorMessage"/> when you want to know the
3790 status from the latest operation on the connection.
3791 </para>
3792 </listitem>
3793 </varlistentry>
3795 <varlistentry id="libpq-PQresultVerboseErrorMessage">
3796 <term><function>PQresultVerboseErrorMessage</function><indexterm><primary>PQresultVerboseErrorMessage</primary></indexterm></term>
3798 <listitem>
3799 <para>
3800 Returns a reformatted version of the error message associated with
3801 a <structname>PGresult</structname> object.
3802 <synopsis>
3803 char *PQresultVerboseErrorMessage(const PGresult *res,
3804 PGVerbosity verbosity,
3805 PGContextVisibility show_context);
3806 </synopsis>
3807 In some situations a client might wish to obtain a more detailed
3808 version of a previously-reported error.
3809 <xref linkend="libpq-PQresultVerboseErrorMessage"/> addresses this need
3810 by computing the message that would have been produced
3811 by <xref linkend="libpq-PQresultErrorMessage"/> if the specified
3812 verbosity settings had been in effect for the connection when the
3813 given <structname>PGresult</structname> was generated. If
3814 the <structname>PGresult</structname> is not an error result,
3815 <quote>PGresult is not an error result</quote> is reported instead.
3816 The returned string includes a trailing newline.
3817 </para>
3819 <para>
3820 Unlike most other functions for extracting data from
3821 a <structname>PGresult</structname>, the result of this function is a freshly
3822 allocated string. The caller must free it
3823 using <function>PQfreemem()</function> when the string is no longer needed.
3824 </para>
3826 <para>
3827 A NULL return is possible if there is insufficient memory.
3828 </para>
3829 </listitem>
3830 </varlistentry>
3832 <varlistentry id="libpq-PQresultErrorField">
3833 <term><function>PQresultErrorField</function><indexterm><primary>PQresultErrorField</primary></indexterm></term>
3834 <listitem>
3835 <para>
3836 Returns an individual field of an error report.
3837 <synopsis>
3838 char *PQresultErrorField(const PGresult *res, int fieldcode);
3839 </synopsis>
3840 <parameter>fieldcode</parameter> is an error field identifier; see the symbols
3841 listed below. <symbol>NULL</symbol> is returned if the
3842 <structname>PGresult</structname> is not an error or warning result,
3843 or does not include the specified field. Field values will normally
3844 not include a trailing newline. The caller should not free the
3845 result directly. It will be freed when the
3846 associated <structname>PGresult</structname> handle is passed to
3847 <xref linkend="libpq-PQclear"/>.
3848 </para>
3850 <para>
3851 The following field codes are available:
3852 <variablelist>
3853 <varlistentry id="libpq-pg-diag-severity">
3854 <term><symbol>PG_DIAG_SEVERITY</symbol></term>
3855 <listitem>
3856 <para>
3857 The severity; the field contents are <literal>ERROR</literal>,
3858 <literal>FATAL</literal>, or <literal>PANIC</literal> (in an error message),
3859 or <literal>WARNING</literal>, <literal>NOTICE</literal>, <literal>DEBUG</literal>,
3860 <literal>INFO</literal>, or <literal>LOG</literal> (in a notice message), or
3861 a localized translation of one of these. Always present.
3862 </para>
3863 </listitem>
3864 </varlistentry>
3866 <varlistentry id="libpq-PG-diag-severity-nonlocalized">
3867 <term><symbol>PG_DIAG_SEVERITY_NONLOCALIZED</symbol></term>
3868 <listitem>
3869 <para>
3870 The severity; the field contents are <literal>ERROR</literal>,
3871 <literal>FATAL</literal>, or <literal>PANIC</literal> (in an error message),
3872 or <literal>WARNING</literal>, <literal>NOTICE</literal>, <literal>DEBUG</literal>,
3873 <literal>INFO</literal>, or <literal>LOG</literal> (in a notice message).
3874 This is identical to the <symbol>PG_DIAG_SEVERITY</symbol> field except
3875 that the contents are never localized. This is present only in
3876 reports generated by <productname>PostgreSQL</productname> versions 9.6
3877 and later.
3878 </para>
3879 </listitem>
3880 </varlistentry>
3882 <varlistentry id="libpq-pg-diag-sqlstate">
3883 <term><symbol>PG_DIAG_SQLSTATE</symbol><indexterm
3884 ><primary>error codes</primary><secondary>libpq</secondary></indexterm></term>
3885 <listitem>
3886 <para>
3887 The SQLSTATE code for the error. The SQLSTATE code identifies
3888 the type of error that has occurred; it can be used by
3889 front-end applications to perform specific operations (such
3890 as error handling) in response to a particular database error.
3891 For a list of the possible SQLSTATE codes, see <xref
3892 linkend="errcodes-appendix"/>. This field is not localizable,
3893 and is always present.
3894 </para>
3895 </listitem>
3896 </varlistentry>
3898 <varlistentry id="libpq-pg-diag-message-primary">
3899 <term><symbol>PG_DIAG_MESSAGE_PRIMARY</symbol></term>
3900 <listitem>
3901 <para>
3902 The primary human-readable error message (typically one line).
3903 Always present.
3904 </para>
3905 </listitem>
3906 </varlistentry>
3908 <varlistentry id="libpq-pg-diag-message-detail">
3909 <term><symbol>PG_DIAG_MESSAGE_DETAIL</symbol></term>
3910 <listitem>
3911 <para>
3912 Detail: an optional secondary error message carrying more
3913 detail about the problem. Might run to multiple lines.
3914 </para>
3915 </listitem>
3916 </varlistentry>
3918 <varlistentry id="libpq-pg-diag-message-hint">
3919 <term><symbol>PG_DIAG_MESSAGE_HINT</symbol></term>
3920 <listitem>
3921 <para>
3922 Hint: an optional suggestion what to do about the problem.
3923 This is intended to differ from detail in that it offers advice
3924 (potentially inappropriate) rather than hard facts. Might
3925 run to multiple lines.
3926 </para>
3927 </listitem>
3928 </varlistentry>
3930 <varlistentry id="libpq-pg-diag-statement-position">
3931 <term><symbol>PG_DIAG_STATEMENT_POSITION</symbol></term>
3932 <listitem>
3933 <para>
3934 A string containing a decimal integer indicating an error cursor
3935 position as an index into the original statement string. The
3936 first character has index 1, and positions are measured in
3937 characters not bytes.
3938 </para>
3939 </listitem>
3940 </varlistentry>
3942 <varlistentry id="libpq-pg-diag-internal-position">
3943 <term><symbol>PG_DIAG_INTERNAL_POSITION</symbol></term>
3944 <listitem>
3945 <para>
3946 This is defined the same as the
3947 <symbol>PG_DIAG_STATEMENT_POSITION</symbol> field, but it is used
3948 when the cursor position refers to an internally generated
3949 command rather than the one submitted by the client. The
3950 <symbol>PG_DIAG_INTERNAL_QUERY</symbol> field will always appear when
3951 this field appears.
3952 </para>
3953 </listitem>
3954 </varlistentry>
3956 <varlistentry id="libpq-pg-diag-internal-query">
3957 <term><symbol>PG_DIAG_INTERNAL_QUERY</symbol></term>
3958 <listitem>
3959 <para>
3960 The text of a failed internally-generated command. This could
3961 be, for example, an SQL query issued by a PL/pgSQL function.
3962 </para>
3963 </listitem>
3964 </varlistentry>
3966 <varlistentry id="libpq-pg-diag-context">
3967 <term><symbol>PG_DIAG_CONTEXT</symbol></term>
3968 <listitem>
3969 <para>
3970 An indication of the context in which the error occurred.
3971 Presently this includes a call stack traceback of active
3972 procedural language functions and internally-generated queries.
3973 The trace is one entry per line, most recent first.
3974 </para>
3975 </listitem>
3976 </varlistentry>
3978 <varlistentry id="libpq-pg-diag-schema-name">
3979 <term><symbol>PG_DIAG_SCHEMA_NAME</symbol></term>
3980 <listitem>
3981 <para>
3982 If the error was associated with a specific database object,
3983 the name of the schema containing that object, if any.
3984 </para>
3985 </listitem>
3986 </varlistentry>
3988 <varlistentry id="libpq-pg-diag-table-name">
3989 <term><symbol>PG_DIAG_TABLE_NAME</symbol></term>
3990 <listitem>
3991 <para>
3992 If the error was associated with a specific table, the name of the
3993 table. (Refer to the schema name field for the name of the
3994 table's schema.)
3995 </para>
3996 </listitem>
3997 </varlistentry>
3999 <varlistentry id="libpq-pg-diag-column-name">
4000 <term><symbol>PG_DIAG_COLUMN_NAME</symbol></term>
4001 <listitem>
4002 <para>
4003 If the error was associated with a specific table column, the name
4004 of the column. (Refer to the schema and table name fields to
4005 identify the table.)
4006 </para>
4007 </listitem>
4008 </varlistentry>
4010 <varlistentry id="libpq-pg-diag-datatype-name">
4011 <term><symbol>PG_DIAG_DATATYPE_NAME</symbol></term>
4012 <listitem>
4013 <para>
4014 If the error was associated with a specific data type, the name of
4015 the data type. (Refer to the schema name field for the name of
4016 the data type's schema.)
4017 </para>
4018 </listitem>
4019 </varlistentry>
4021 <varlistentry id="libpq-pg-diag-constraint-name">
4022 <term><symbol>PG_DIAG_CONSTRAINT_NAME</symbol></term>
4023 <listitem>
4024 <para>
4025 If the error was associated with a specific constraint, the name
4026 of the constraint. Refer to fields listed above for the
4027 associated table or domain. (For this purpose, indexes are
4028 treated as constraints, even if they weren't created with
4029 constraint syntax.)
4030 </para>
4031 </listitem>
4032 </varlistentry>
4034 <varlistentry id="libpq-pg-diag-source-file">
4035 <term><symbol>PG_DIAG_SOURCE_FILE</symbol></term>
4036 <listitem>
4037 <para>
4038 The file name of the source-code location where the error was
4039 reported.
4040 </para>
4041 </listitem>
4042 </varlistentry>
4044 <varlistentry id="libpq-pg-diag-source-line">
4045 <term><symbol>PG_DIAG_SOURCE_LINE</symbol></term>
4046 <listitem>
4047 <para>
4048 The line number of the source-code location where the error
4049 was reported.
4050 </para>
4051 </listitem>
4052 </varlistentry>
4054 <varlistentry id="libpq-pg-diag-source-function">
4055 <term><symbol>PG_DIAG_SOURCE_FUNCTION</symbol></term>
4056 <listitem>
4057 <para>
4058 The name of the source-code function reporting the error.
4059 </para>
4060 </listitem>
4061 </varlistentry>
4062 </variablelist>
4063 </para>
4065 <note>
4066 <para>
4067 The fields for schema name, table name, column name, data type name,
4068 and constraint name are supplied only for a limited number of error
4069 types; see <xref linkend="errcodes-appendix"/>. Do not assume that
4070 the presence of any of these fields guarantees the presence of
4071 another field. Core error sources observe the interrelationships
4072 noted above, but user-defined functions may use these fields in other
4073 ways. In the same vein, do not assume that these fields denote
4074 contemporary objects in the current database.
4075 </para>
4076 </note>
4078 <para>
4079 The client is responsible for formatting displayed information to meet
4080 its needs; in particular it should break long lines as needed.
4081 Newline characters appearing in the error message fields should be
4082 treated as paragraph breaks, not line breaks.
4083 </para>
4085 <para>
4086 Errors generated internally by <application>libpq</application> will
4087 have severity and primary message, but typically no other fields.
4088 </para>
4090 <para>
4091 Note that error fields are only available from
4092 <structname>PGresult</structname> objects, not
4093 <structname>PGconn</structname> objects; there is no
4094 <function>PQerrorField</function> function.
4095 </para>
4096 </listitem>
4097 </varlistentry>
4099 <varlistentry id="libpq-PQclear">
4100 <term><function>PQclear</function><indexterm><primary>PQclear</primary></indexterm></term>
4101 <listitem>
4102 <para>
4103 Frees the storage associated with a
4104 <structname>PGresult</structname>. Every command result should be
4105 freed via <xref linkend="libpq-PQclear"/> when it is no longer
4106 needed.
4108 <synopsis>
4109 void PQclear(PGresult *res);
4110 </synopsis>
4112 If the argument is a <symbol>NULL</symbol> pointer, no operation is
4113 performed.
4114 </para>
4116 <para>
4117 You can keep a <structname>PGresult</structname> object around for
4118 as long as you need it; it does not go away when you issue a new
4119 command, nor even if you close the connection. To get rid of it,
4120 you must call <xref linkend="libpq-PQclear"/>. Failure to do this
4121 will result in memory leaks in your application.
4122 </para>
4123 </listitem>
4124 </varlistentry>
4125 </variablelist>
4126 </para>
4127 </sect2>
4129 <sect2 id="libpq-exec-select-info">
4130 <title>Retrieving Query Result Information</title>
4132 <para>
4133 These functions are used to extract information from a
4134 <structname>PGresult</structname> object that represents a successful
4135 query result (that is, one that has status
4136 <literal>PGRES_TUPLES_OK</literal>,
4137 <literal>PGRES_SINGLE_TUPLE</literal>, or
4138 <literal>PGRES_TUPLES_CHUNK</literal>).
4139 They can also be used to extract
4140 information from a successful Describe operation: a Describe's result
4141 has all the same column information that actual execution of the query
4142 would provide, but it has zero rows. For objects with other status values,
4143 these functions will act as though the result has zero rows and zero columns.
4144 </para>
4146 <variablelist>
4147 <varlistentry id="libpq-PQntuples">
4148 <term><function>PQntuples</function><indexterm><primary>PQntuples</primary></indexterm></term>
4150 <listitem>
4151 <para>
4152 Returns the number of rows (tuples) in the query result.
4153 (Note that <structname>PGresult</structname> objects are limited to no more
4154 than <literal>INT_MAX</literal> rows, so an <type>int</type> result is
4155 sufficient.)
4157 <synopsis>
4158 int PQntuples(const PGresult *res);
4159 </synopsis>
4161 </para>
4162 </listitem>
4163 </varlistentry>
4165 <varlistentry id="libpq-PQnfields">
4166 <term><function>PQnfields</function><indexterm><primary>PQnfields</primary></indexterm></term>
4168 <listitem>
4169 <para>
4170 Returns the number of columns (fields) in each row of the query
4171 result.
4173 <synopsis>
4174 int PQnfields(const PGresult *res);
4175 </synopsis>
4176 </para>
4177 </listitem>
4178 </varlistentry>
4180 <varlistentry id="libpq-PQfname">
4181 <term><function>PQfname</function><indexterm><primary>PQfname</primary></indexterm></term>
4183 <listitem>
4184 <para>
4185 Returns the column name associated with the given column number.
4186 Column numbers start at 0. The caller should not free the result
4187 directly. It will be freed when the associated
4188 <structname>PGresult</structname> handle is passed to
4189 <xref linkend="libpq-PQclear"/>.
4190 <synopsis>
4191 char *PQfname(const PGresult *res,
4192 int column_number);
4193 </synopsis>
4194 </para>
4196 <para>
4197 <symbol>NULL</symbol> is returned if the column number is out of range.
4198 </para>
4199 </listitem>
4200 </varlistentry>
4202 <varlistentry id="libpq-PQfnumber">
4203 <term><function>PQfnumber</function><indexterm><primary>PQfnumber</primary></indexterm></term>
4205 <listitem>
4206 <para>
4207 Returns the column number associated with the given column name.
4208 <synopsis>
4209 int PQfnumber(const PGresult *res,
4210 const char *column_name);
4211 </synopsis>
4212 </para>
4214 <para>
4215 -1 is returned if the given name does not match any column.
4216 </para>
4218 <para>
4219 The given name is treated like an identifier in an SQL command,
4220 that is, it is downcased unless double-quoted. For example, given
4221 a query result generated from the SQL command:
4222 <programlisting>
4223 SELECT 1 AS FOO, 2 AS "BAR";
4224 </programlisting>
4225 we would have the results:
4226 <programlisting>
4227 PQfname(res, 0) <lineannotation>foo</lineannotation>
4228 PQfname(res, 1) <lineannotation>BAR</lineannotation>
4229 PQfnumber(res, "FOO") <lineannotation>0</lineannotation>
4230 PQfnumber(res, "foo") <lineannotation>0</lineannotation>
4231 PQfnumber(res, "BAR") <lineannotation>-1</lineannotation>
4232 PQfnumber(res, "\"BAR\"") <lineannotation>1</lineannotation>
4233 </programlisting>
4234 </para>
4235 </listitem>
4236 </varlistentry>
4238 <varlistentry id="libpq-PQftable">
4239 <term><function>PQftable</function><indexterm><primary>PQftable</primary></indexterm></term>
4241 <listitem>
4242 <para>
4243 Returns the OID of the table from which the given column was
4244 fetched. Column numbers start at 0.
4245 <synopsis>
4246 Oid PQftable(const PGresult *res,
4247 int column_number);
4248 </synopsis>
4249 </para>
4251 <para>
4252 <literal>InvalidOid</literal> is returned if the column number is out of range,
4253 or if the specified column is not a simple reference to a table column.
4254 You can query the system table <literal>pg_class</literal> to determine
4255 exactly which table is referenced.
4256 </para>
4258 <para>
4259 The type <type>Oid</type> and the constant
4260 <literal>InvalidOid</literal> will be defined when you include
4261 the <application>libpq</application> header file. They will both
4262 be some integer type.
4263 </para>
4264 </listitem>
4265 </varlistentry>
4267 <varlistentry id="libpq-PQftablecol">
4268 <term><function>PQftablecol</function><indexterm><primary>PQftablecol</primary></indexterm></term>
4270 <listitem>
4271 <para>
4272 Returns the column number (within its table) of the column making
4273 up the specified query result column. Query-result column numbers
4274 start at 0, but table columns have nonzero numbers.
4275 <synopsis>
4276 int PQftablecol(const PGresult *res,
4277 int column_number);
4278 </synopsis>
4279 </para>
4281 <para>
4282 Zero is returned if the column number is out of range, or if the
4283 specified column is not a simple reference to a table column.
4284 </para>
4285 </listitem>
4286 </varlistentry>
4288 <varlistentry id="libpq-PQfformat">
4289 <term><function>PQfformat</function><indexterm><primary>PQfformat</primary></indexterm></term>
4291 <listitem>
4292 <para>
4293 Returns the format code indicating the format of the given
4294 column. Column numbers start at 0.
4295 <synopsis>
4296 int PQfformat(const PGresult *res,
4297 int column_number);
4298 </synopsis>
4299 </para>
4301 <para>
4302 Format code zero indicates textual data representation, while format
4303 code one indicates binary representation. (Other codes are reserved
4304 for future definition.)
4305 </para>
4306 </listitem>
4307 </varlistentry>
4309 <varlistentry id="libpq-PQftype">
4310 <term><function>PQftype</function><indexterm><primary>PQftype</primary></indexterm></term>
4312 <listitem>
4313 <para>
4314 Returns the data type associated with the given column number.
4315 The integer returned is the internal OID number of the type.
4316 Column numbers start at 0.
4317 <synopsis>
4318 Oid PQftype(const PGresult *res,
4319 int column_number);
4320 </synopsis>
4321 </para>
4323 <para>
4324 You can query the system table <literal>pg_type</literal> to
4325 obtain the names and properties of the various data types. The
4326 <acronym>OID</acronym>s of the built-in data types are defined
4327 in the file <filename>catalog/pg_type_d.h</filename>
4328 in the <productname>PostgreSQL</productname>
4329 installation's <filename>include</filename> directory.
4330 </para>
4331 </listitem>
4332 </varlistentry>
4334 <varlistentry id="libpq-PQfmod">
4335 <term><function>PQfmod</function><indexterm><primary>PQfmod</primary></indexterm></term>
4337 <listitem>
4338 <para>
4339 Returns the type modifier of the column associated with the
4340 given column number. Column numbers start at 0.
4341 <synopsis>
4342 int PQfmod(const PGresult *res,
4343 int column_number);
4344 </synopsis>
4345 </para>
4347 <para>
4348 The interpretation of modifier values is type-specific; they
4349 typically indicate precision or size limits. The value -1 is
4350 used to indicate <quote>no information available</quote>. Most data
4351 types do not use modifiers, in which case the value is always
4353 </para>
4354 </listitem>
4355 </varlistentry>
4357 <varlistentry id="libpq-PQfsize">
4358 <term><function>PQfsize</function><indexterm><primary>PQfsize</primary></indexterm></term>
4360 <listitem>
4361 <para>
4362 Returns the size in bytes of the column associated with the
4363 given column number. Column numbers start at 0.
4364 <synopsis>
4365 int PQfsize(const PGresult *res,
4366 int column_number);
4367 </synopsis>
4368 </para>
4370 <para>
4371 <xref linkend="libpq-PQfsize"/> returns the space allocated for this column
4372 in a database row, in other words the size of the server's
4373 internal representation of the data type. (Accordingly, it is
4374 not really very useful to clients.) A negative value indicates
4375 the data type is variable-length.
4376 </para>
4377 </listitem>
4378 </varlistentry>
4380 <varlistentry id="libpq-PQbinaryTuples">
4381 <term><function>PQbinaryTuples</function><indexterm><primary>PQbinaryTuples</primary></indexterm></term>
4383 <listitem>
4384 <para>
4385 Returns 1 if the <structname>PGresult</structname> contains binary data
4386 and 0 if it contains text data.
4387 <synopsis>
4388 int PQbinaryTuples(const PGresult *res);
4389 </synopsis>
4390 </para>
4392 <para>
4393 This function is deprecated (except for its use in connection with
4394 <command>COPY</command>), because it is possible for a single
4395 <structname>PGresult</structname> to contain text data in some columns and
4396 binary data in others. <xref linkend="libpq-PQfformat"/> is preferred.
4397 <xref linkend="libpq-PQbinaryTuples"/> returns 1 only if all columns of the
4398 result are binary (format 1).
4399 </para>
4400 </listitem>
4401 </varlistentry>
4403 <varlistentry id="libpq-PQgetvalue">
4404 <term><function>PQgetvalue</function><indexterm><primary>PQgetvalue</primary></indexterm></term>
4406 <listitem>
4407 <para>
4408 Returns a single field value of one row of a
4409 <structname>PGresult</structname>. Row and column numbers start
4410 at 0. The caller should not free the result directly. It will
4411 be freed when the associated <structname>PGresult</structname> handle is
4412 passed to <xref linkend="libpq-PQclear"/>.
4413 <synopsis>
4414 char *PQgetvalue(const PGresult *res,
4415 int row_number,
4416 int column_number);
4417 </synopsis>
4418 </para>
4420 <para>
4421 For data in text format, the value returned by
4422 <xref linkend="libpq-PQgetvalue"/> is a null-terminated character
4423 string representation of the field value. For data in binary
4424 format, the value is in the binary representation determined by
4425 the data type's <function>typsend</function> and <function>typreceive</function>
4426 functions. (The value is actually followed by a zero byte in
4427 this case too, but that is not ordinarily useful, since the
4428 value is likely to contain embedded nulls.)
4429 </para>
4431 <para>
4432 An empty string is returned if the field value is null. See
4433 <xref linkend="libpq-PQgetisnull"/> to distinguish null values from
4434 empty-string values.
4435 </para>
4437 <para>
4438 The pointer returned by <xref linkend="libpq-PQgetvalue"/> points
4439 to storage that is part of the <structname>PGresult</structname>
4440 structure. One should not modify the data it points to, and one
4441 must explicitly copy the data into other storage if it is to be
4442 used past the lifetime of the <structname>PGresult</structname>
4443 structure itself.
4444 </para>
4445 </listitem>
4446 </varlistentry>
4448 <varlistentry id="libpq-PQgetisnull">
4449 <term><function>PQgetisnull</function><indexterm
4450 ><primary>PQgetisnull</primary></indexterm><indexterm
4451 ><primary>null value</primary><secondary sortas="libpq">in libpq</secondary></indexterm></term>
4453 <listitem>
4454 <para>
4455 Tests a field for a null value. Row and column numbers start
4456 at 0.
4457 <synopsis>
4458 int PQgetisnull(const PGresult *res,
4459 int row_number,
4460 int column_number);
4461 </synopsis>
4462 </para>
4464 <para>
4465 This function returns 1 if the field is null and 0 if it
4466 contains a non-null value. (Note that
4467 <xref linkend="libpq-PQgetvalue"/> will return an empty string,
4468 not a null pointer, for a null field.)
4469 </para>
4470 </listitem>
4471 </varlistentry>
4473 <varlistentry id="libpq-PQgetlength">
4474 <term><function>PQgetlength</function><indexterm><primary>PQgetlength</primary></indexterm></term>
4476 <listitem>
4477 <para>
4478 Returns the actual length of a field value in bytes. Row and
4479 column numbers start at 0.
4480 <synopsis>
4481 int PQgetlength(const PGresult *res,
4482 int row_number,
4483 int column_number);
4484 </synopsis>
4485 </para>
4487 <para>
4488 This is the actual data length for the particular data value,
4489 that is, the size of the object pointed to by
4490 <xref linkend="libpq-PQgetvalue"/>. For text data format this is
4491 the same as <function>strlen()</function>. For binary format this is
4492 essential information. Note that one should <emphasis>not</emphasis>
4493 rely on <xref linkend="libpq-PQfsize"/> to obtain the actual data
4494 length.
4495 </para>
4496 </listitem>
4497 </varlistentry>
4499 <varlistentry id="libpq-PQnparams">
4500 <term><function>PQnparams</function><indexterm><primary>PQnparams</primary></indexterm></term>
4502 <listitem>
4503 <para>
4504 Returns the number of parameters of a prepared statement.
4505 <synopsis>
4506 int PQnparams(const PGresult *res);
4507 </synopsis>
4508 </para>
4510 <para>
4511 This function is only useful when inspecting the result of
4512 <xref linkend="libpq-PQdescribePrepared"/>. For other types of results it
4513 will return zero.
4514 </para>
4515 </listitem>
4516 </varlistentry>
4518 <varlistentry id="libpq-PQparamtype">
4519 <term><function>PQparamtype</function><indexterm><primary>PQparamtype</primary></indexterm></term>
4521 <listitem>
4522 <para>
4523 Returns the data type of the indicated statement parameter.
4524 Parameter numbers start at 0.
4525 <synopsis>
4526 Oid PQparamtype(const PGresult *res, int param_number);
4527 </synopsis>
4528 </para>
4530 <para>
4531 This function is only useful when inspecting the result of
4532 <xref linkend="libpq-PQdescribePrepared"/>. For other types of results it
4533 will return zero.
4534 </para>
4535 </listitem>
4536 </varlistentry>
4538 <varlistentry id="libpq-PQprint">
4539 <term><function>PQprint</function><indexterm><primary>PQprint</primary></indexterm></term>
4541 <listitem>
4542 <para>
4543 Prints out all the rows and, optionally, the column names to
4544 the specified output stream.
4545 <synopsis>
4546 void PQprint(FILE *fout, /* output stream */
4547 const PGresult *res,
4548 const PQprintOpt *po);
4549 typedef struct
4551 pqbool header; /* print output field headings and row count */
4552 pqbool align; /* fill align the fields */
4553 pqbool standard; /* old brain dead format */
4554 pqbool html3; /* output HTML tables */
4555 pqbool expanded; /* expand tables */
4556 pqbool pager; /* use pager for output if needed */
4557 char *fieldSep; /* field separator */
4558 char *tableOpt; /* attributes for HTML table element */
4559 char *caption; /* HTML table caption */
4560 char **fieldName; /* null-terminated array of replacement field names */
4561 } PQprintOpt;
4562 </synopsis>
4563 </para>
4565 <para>
4566 This function was formerly used by <application>psql</application>
4567 to print query results, but this is no longer the case. Note
4568 that it assumes all the data is in text format.
4569 </para>
4570 </listitem>
4571 </varlistentry>
4572 </variablelist>
4573 </sect2>
4575 <sect2 id="libpq-exec-nonselect">
4576 <title>Retrieving Other Result Information</title>
4578 <para>
4579 These functions are used to extract other information from
4580 <structname>PGresult</structname> objects.
4581 </para>
4583 <variablelist>
4584 <varlistentry id="libpq-PQcmdStatus">
4585 <term><function>PQcmdStatus</function><indexterm><primary>PQcmdStatus</primary></indexterm></term>
4587 <listitem>
4588 <para>
4589 Returns the command status tag from the SQL command that generated
4590 the <structname>PGresult</structname>.
4591 <synopsis>
4592 char *PQcmdStatus(PGresult *res);
4593 </synopsis>
4594 </para>
4596 <para>
4597 Commonly this is just the name of the command, but it might include
4598 additional data such as the number of rows processed. The caller
4599 should not free the result directly. It will be freed when the
4600 associated <structname>PGresult</structname> handle is passed to
4601 <xref linkend="libpq-PQclear"/>.
4602 </para>
4603 </listitem>
4604 </varlistentry>
4606 <varlistentry id="libpq-PQcmdTuples">
4607 <term><function>PQcmdTuples</function><indexterm><primary>PQcmdTuples</primary></indexterm></term>
4609 <listitem>
4610 <para>
4611 Returns the number of rows affected by the SQL command.
4612 <synopsis>
4613 char *PQcmdTuples(PGresult *res);
4614 </synopsis>
4615 </para>
4617 <para>
4618 This function returns a string containing the number of rows
4619 affected by the <acronym>SQL</acronym> statement that generated the
4620 <structname>PGresult</structname>. This function can only be used following
4621 the execution of a <command>SELECT</command>, <command>CREATE TABLE AS</command>,
4622 <command>INSERT</command>, <command>UPDATE</command>, <command>DELETE</command>,
4623 <command>MERGE</command>, <command>MOVE</command>, <command>FETCH</command>,
4624 or <command>COPY</command> statement, or an <command>EXECUTE</command> of a
4625 prepared query that contains an <command>INSERT</command>,
4626 <command>UPDATE</command>, <command>DELETE</command>,
4627 or <command>MERGE</command> statement.
4628 If the command that generated the <structname>PGresult</structname> was anything
4629 else, <xref linkend="libpq-PQcmdTuples"/> returns an empty string. The caller
4630 should not free the return value directly. It will be freed when
4631 the associated <structname>PGresult</structname> handle is passed to
4632 <xref linkend="libpq-PQclear"/>.
4633 </para>
4634 </listitem>
4635 </varlistentry>
4637 <varlistentry id="libpq-PQoidValue">
4638 <term><function>PQoidValue</function><indexterm><primary>PQoidValue</primary></indexterm></term>
4640 <listitem>
4641 <para>
4642 Returns the OID<indexterm><primary>OID</primary><secondary>in libpq</secondary></indexterm>
4643 of the inserted row, if the <acronym>SQL</acronym> command was an
4644 <command>INSERT</command> that inserted exactly one row into a table that
4645 has OIDs, or a <command>EXECUTE</command> of a prepared query containing
4646 a suitable <command>INSERT</command> statement. Otherwise, this function
4647 returns <literal>InvalidOid</literal>. This function will also
4648 return <literal>InvalidOid</literal> if the table affected by the
4649 <command>INSERT</command> statement does not contain OIDs.
4650 <synopsis>
4651 Oid PQoidValue(const PGresult *res);
4652 </synopsis>
4653 </para>
4654 </listitem>
4655 </varlistentry>
4657 <varlistentry id="libpq-PQoidStatus">
4658 <term><function>PQoidStatus</function><indexterm><primary>PQoidStatus</primary></indexterm></term>
4660 <listitem>
4661 <para>
4662 This function is deprecated in favor of
4663 <xref linkend="libpq-PQoidValue"/> and is not thread-safe.
4664 It returns a string with the OID of the inserted row, while
4665 <xref linkend="libpq-PQoidValue"/> returns the OID value.
4666 <synopsis>
4667 char *PQoidStatus(const PGresult *res);
4668 </synopsis>
4669 </para>
4671 </listitem>
4672 </varlistentry>
4673 </variablelist>
4675 </sect2>
4677 <sect2 id="libpq-exec-escape-string">
4678 <title>Escaping Strings for Inclusion in SQL Commands</title>
4680 <indexterm zone="libpq-exec-escape-string">
4681 <primary>escaping strings</primary>
4682 <secondary>in libpq</secondary>
4683 </indexterm>
4685 <variablelist>
4686 <varlistentry id="libpq-PQescapeLiteral">
4687 <term><function>PQescapeLiteral</function><indexterm><primary>PQescapeLiteral</primary></indexterm></term>
4689 <listitem>
4690 <para>
4691 <synopsis>
4692 char *PQescapeLiteral(PGconn *conn, const char *str, size_t length);
4693 </synopsis>
4694 </para>
4696 <para>
4697 <xref linkend="libpq-PQescapeLiteral"/> escapes a string for
4698 use within an SQL command. This is useful when inserting data
4699 values as literal constants in SQL commands. Certain characters
4700 (such as quotes and backslashes) must be escaped to prevent them
4701 from being interpreted specially by the SQL parser.
4702 <xref linkend="libpq-PQescapeLiteral"/> performs this operation.
4703 </para>
4705 <para>
4706 <xref linkend="libpq-PQescapeLiteral"/> returns an escaped version of the
4707 <parameter>str</parameter> parameter in memory allocated with
4708 <function>malloc()</function>. This memory should be freed using
4709 <function>PQfreemem()</function> when the result is no longer needed.
4710 A terminating zero byte is not required, and should not be
4711 counted in <parameter>length</parameter>. (If a terminating zero byte is found
4712 before <parameter>length</parameter> bytes are processed,
4713 <xref linkend="libpq-PQescapeLiteral"/> stops at the zero; the behavior is
4714 thus rather like <function>strncpy</function>.) The
4715 return string has all special characters replaced so that they can
4716 be properly processed by the <productname>PostgreSQL</productname>
4717 string literal parser. A terminating zero byte is also added. The
4718 single quotes that must surround <productname>PostgreSQL</productname>
4719 string literals are included in the result string.
4720 </para>
4722 <para>
4723 On error, <xref linkend="libpq-PQescapeLiteral"/> returns <symbol>NULL</symbol> and a suitable
4724 message is stored in the <parameter>conn</parameter> object.
4725 </para>
4727 <tip>
4728 <para>
4729 It is especially important to do proper escaping when handling
4730 strings that were received from an untrustworthy source.
4731 Otherwise there is a security risk: you are vulnerable to
4732 <quote>SQL injection</quote> attacks wherein unwanted SQL commands are
4733 fed to your database.
4734 </para>
4735 </tip>
4737 <para>
4738 Note that it is neither necessary nor correct to do escaping when a data
4739 value is passed as a separate parameter in <xref linkend="libpq-PQexecParams"/> or
4740 its sibling routines.
4741 </para>
4742 </listitem>
4743 </varlistentry>
4745 <varlistentry id="libpq-PQescapeIdentifier">
4746 <term><function>PQescapeIdentifier</function><indexterm><primary>PQescapeIdentifier</primary></indexterm></term>
4748 <listitem>
4749 <para>
4750 <synopsis>
4751 char *PQescapeIdentifier(PGconn *conn, const char *str, size_t length);
4752 </synopsis>
4753 </para>
4755 <para>
4756 <xref linkend="libpq-PQescapeIdentifier"/> escapes a string for
4757 use as an SQL identifier, such as a table, column, or function name.
4758 This is useful when a user-supplied identifier might contain
4759 special characters that would otherwise not be interpreted as part
4760 of the identifier by the SQL parser, or when the identifier might
4761 contain upper case characters whose case should be preserved.
4762 </para>
4764 <para>
4765 <xref linkend="libpq-PQescapeIdentifier"/> returns a version of the
4766 <parameter>str</parameter> parameter escaped as an SQL identifier
4767 in memory allocated with <function>malloc()</function>. This memory must be
4768 freed using <function>PQfreemem()</function> when the result is no longer
4769 needed. A terminating zero byte is not required, and should not be
4770 counted in <parameter>length</parameter>. (If a terminating zero byte is found
4771 before <parameter>length</parameter> bytes are processed,
4772 <xref linkend="libpq-PQescapeIdentifier"/> stops at the zero; the behavior is
4773 thus rather like <function>strncpy</function>.) The
4774 return string has all special characters replaced so that it
4775 will be properly processed as an SQL identifier. A terminating zero byte
4776 is also added. The return string will also be surrounded by double
4777 quotes.
4778 </para>
4780 <para>
4781 On error, <xref linkend="libpq-PQescapeIdentifier"/> returns <symbol>NULL</symbol> and a suitable
4782 message is stored in the <parameter>conn</parameter> object.
4783 </para>
4785 <tip>
4786 <para>
4787 As with string literals, to prevent SQL injection attacks,
4788 SQL identifiers must be escaped when they are received from an
4789 untrustworthy source.
4790 </para>
4791 </tip>
4792 </listitem>
4793 </varlistentry>
4795 <varlistentry id="libpq-PQescapeStringConn">
4796 <term><function>PQescapeStringConn</function><indexterm><primary>PQescapeStringConn</primary></indexterm></term>
4798 <listitem>
4799 <para>
4800 <synopsis>
4801 size_t PQescapeStringConn(PGconn *conn,
4802 char *to, const char *from, size_t length,
4803 int *error);
4804 </synopsis>
4805 </para>
4807 <para>
4808 <xref linkend="libpq-PQescapeStringConn"/> escapes string literals, much like
4809 <xref linkend="libpq-PQescapeLiteral"/>. Unlike <xref linkend="libpq-PQescapeLiteral"/>,
4810 the caller is responsible for providing an appropriately sized buffer.
4811 Furthermore, <xref linkend="libpq-PQescapeStringConn"/> does not generate the
4812 single quotes that must surround <productname>PostgreSQL</productname> string
4813 literals; they should be provided in the SQL command that the
4814 result is inserted into. The parameter <parameter>from</parameter> points to
4815 the first character of the string that is to be escaped, and the
4816 <parameter>length</parameter> parameter gives the number of bytes in this
4817 string. A terminating zero byte is not required, and should not be
4818 counted in <parameter>length</parameter>. (If a terminating zero byte is found
4819 before <parameter>length</parameter> bytes are processed,
4820 <xref linkend="libpq-PQescapeStringConn"/> stops at the zero; the behavior is
4821 thus rather like <function>strncpy</function>.) <parameter>to</parameter> shall point
4822 to a buffer that is able to hold at least one more byte than twice
4823 the value of <parameter>length</parameter>, otherwise the behavior is undefined.
4824 Behavior is likewise undefined if the <parameter>to</parameter> and
4825 <parameter>from</parameter> strings overlap.
4826 </para>
4828 <para>
4829 If the <parameter>error</parameter> parameter is not <symbol>NULL</symbol>, then
4830 <literal>*error</literal> is set to zero on success, nonzero on error.
4831 Presently the only possible error conditions involve invalid multibyte
4832 encoding in the source string. The output string is still generated
4833 on error, but it can be expected that the server will reject it as
4834 malformed. On error, a suitable message is stored in the
4835 <parameter>conn</parameter> object, whether or not <parameter>error</parameter> is <symbol>NULL</symbol>.
4836 </para>
4838 <para>
4839 <xref linkend="libpq-PQescapeStringConn"/> returns the number of bytes written
4840 to <parameter>to</parameter>, not including the terminating zero byte.
4841 </para>
4842 </listitem>
4843 </varlistentry>
4845 <varlistentry id="libpq-PQescapeString">
4846 <term><function>PQescapeString</function><indexterm><primary>PQescapeString</primary></indexterm></term>
4848 <listitem>
4849 <para>
4850 <xref linkend="libpq-PQescapeString"/> is an older, deprecated version of
4851 <xref linkend="libpq-PQescapeStringConn"/>.
4852 <synopsis>
4853 size_t PQescapeString (char *to, const char *from, size_t length);
4854 </synopsis>
4855 </para>
4857 <para>
4858 The only difference from <xref linkend="libpq-PQescapeStringConn"/> is that
4859 <xref linkend="libpq-PQescapeString"/> does not take <structname>PGconn</structname>
4860 or <parameter>error</parameter> parameters.
4861 Because of this, it cannot adjust its behavior depending on the
4862 connection properties (such as character encoding) and therefore
4863 <emphasis>it might give the wrong results</emphasis>. Also, it has no way
4864 to report error conditions.
4865 </para>
4867 <para>
4868 <xref linkend="libpq-PQescapeString"/> can be used safely in
4869 client programs that work with only one <productname>PostgreSQL</productname>
4870 connection at a time (in this case it can find out what it needs to
4871 know <quote>behind the scenes</quote>). In other contexts it is a security
4872 hazard and should be avoided in favor of
4873 <xref linkend="libpq-PQescapeStringConn"/>.
4874 </para>
4875 </listitem>
4876 </varlistentry>
4878 <varlistentry id="libpq-PQescapeByteaConn">
4879 <term><function>PQescapeByteaConn</function><indexterm><primary>PQescapeByteaConn</primary></indexterm></term>
4881 <listitem>
4882 <para>
4883 Escapes binary data for use within an SQL command with the type
4884 <type>bytea</type>. As with <xref linkend="libpq-PQescapeStringConn"/>,
4885 this is only used when inserting data directly into an SQL command string.
4886 <synopsis>
4887 unsigned char *PQescapeByteaConn(PGconn *conn,
4888 const unsigned char *from,
4889 size_t from_length,
4890 size_t *to_length);
4891 </synopsis>
4892 </para>
4894 <para>
4895 Certain byte values must be escaped when used as part of a
4896 <type>bytea</type> literal in an <acronym>SQL</acronym> statement.
4897 <xref linkend="libpq-PQescapeByteaConn"/> escapes bytes using
4898 either hex encoding or backslash escaping. See <xref
4899 linkend="datatype-binary"/> for more information.
4900 </para>
4902 <para>
4903 The <parameter>from</parameter> parameter points to the first
4904 byte of the string that is to be escaped, and the
4905 <parameter>from_length</parameter> parameter gives the number of
4906 bytes in this binary string. (A terminating zero byte is
4907 neither necessary nor counted.) The <parameter>to_length</parameter>
4908 parameter points to a variable that will hold the resultant
4909 escaped string length. This result string length includes the terminating
4910 zero byte of the result.
4911 </para>
4913 <para>
4914 <xref linkend="libpq-PQescapeByteaConn"/> returns an escaped version of the
4915 <parameter>from</parameter> parameter binary string in memory
4916 allocated with <function>malloc()</function>. This memory should be freed using
4917 <function>PQfreemem()</function> when the result is no longer needed. The
4918 return string has all special characters replaced so that they can
4919 be properly processed by the <productname>PostgreSQL</productname>
4920 string literal parser, and the <type>bytea</type> input function. A
4921 terminating zero byte is also added. The single quotes that must
4922 surround <productname>PostgreSQL</productname> string literals are
4923 not part of the result string.
4924 </para>
4926 <para>
4927 On error, a null pointer is returned, and a suitable error message
4928 is stored in the <parameter>conn</parameter> object. Currently, the only
4929 possible error is insufficient memory for the result string.
4930 </para>
4931 </listitem>
4932 </varlistentry>
4934 <varlistentry id="libpq-PQescapeBytea">
4935 <term><function>PQescapeBytea</function><indexterm><primary>PQescapeBytea</primary></indexterm></term>
4937 <listitem>
4938 <para>
4939 <xref linkend="libpq-PQescapeBytea"/> is an older, deprecated version of
4940 <xref linkend="libpq-PQescapeByteaConn"/>.
4941 <synopsis>
4942 unsigned char *PQescapeBytea(const unsigned char *from,
4943 size_t from_length,
4944 size_t *to_length);
4945 </synopsis>
4946 </para>
4948 <para>
4949 The only difference from <xref linkend="libpq-PQescapeByteaConn"/> is that
4950 <xref linkend="libpq-PQescapeBytea"/> does not take a <structname>PGconn</structname>
4951 parameter. Because of this, <xref linkend="libpq-PQescapeBytea"/> can
4952 only be used safely in client programs that use a single
4953 <productname>PostgreSQL</productname> connection at a time (in this case
4954 it can find out what it needs to know <quote>behind the
4955 scenes</quote>). It <emphasis>might give the wrong results</emphasis> if
4956 used in programs that use multiple database connections (use
4957 <xref linkend="libpq-PQescapeByteaConn"/> in such cases).
4958 </para>
4959 </listitem>
4960 </varlistentry>
4962 <varlistentry id="libpq-PQunescapeBytea">
4963 <term><function>PQunescapeBytea</function><indexterm><primary>PQunescapeBytea</primary></indexterm></term>
4965 <listitem>
4966 <para>
4967 Converts a string representation of binary data into binary data
4968 &mdash; the reverse of <xref linkend="libpq-PQescapeBytea"/>. This
4969 is needed when retrieving <type>bytea</type> data in text format,
4970 but not when retrieving it in binary format.
4972 <synopsis>
4973 unsigned char *PQunescapeBytea(const unsigned char *from, size_t *to_length);
4974 </synopsis>
4975 </para>
4977 <para>
4978 The <parameter>from</parameter> parameter points to a string
4979 such as might be returned by <xref linkend="libpq-PQgetvalue"/> when applied
4980 to a <type>bytea</type> column. <xref linkend="libpq-PQunescapeBytea"/>
4981 converts this string representation into its binary representation.
4982 It returns a pointer to a buffer allocated with
4983 <function>malloc()</function>, or <symbol>NULL</symbol> on error, and puts the size of
4984 the buffer in <parameter>to_length</parameter>. The result must be
4985 freed using <xref linkend="libpq-PQfreemem"/> when it is no longer needed.
4986 </para>
4988 <para>
4989 This conversion is not exactly the inverse of
4990 <xref linkend="libpq-PQescapeBytea"/>, because the string is not expected
4991 to be <quote>escaped</quote> when received from <xref linkend="libpq-PQgetvalue"/>.
4992 In particular this means there is no need for string quoting considerations,
4993 and so no need for a <structname>PGconn</structname> parameter.
4994 </para>
4995 </listitem>
4996 </varlistentry>
4997 </variablelist>
4999 </sect2>
5001 </sect1>
5003 <sect1 id="libpq-async">
5004 <title>Asynchronous Command Processing</title>
5006 <indexterm zone="libpq-async">
5007 <primary>nonblocking connection</primary>
5008 </indexterm>
5010 <para>
5011 The <xref linkend="libpq-PQexec"/> function is adequate for submitting
5012 commands in normal, synchronous applications. It has a few
5013 deficiencies, however, that can be of importance to some users:
5015 <itemizedlist>
5016 <listitem>
5017 <para>
5018 <xref linkend="libpq-PQexec"/> waits for the command to be completed.
5019 The application might have other work to do (such as maintaining a
5020 user interface), in which case it won't want to block waiting for
5021 the response.
5022 </para>
5023 </listitem>
5025 <listitem>
5026 <para>
5027 Since the execution of the client application is suspended while it
5028 waits for the result, it is hard for the application to decide that
5029 it would like to try to cancel the ongoing command. (It can be done
5030 from a signal handler, but not otherwise.)
5031 </para>
5032 </listitem>
5034 <listitem>
5035 <para>
5036 <xref linkend="libpq-PQexec"/> can return only one
5037 <structname>PGresult</structname> structure. If the submitted command
5038 string contains multiple <acronym>SQL</acronym> commands, all but
5039 the last <structname>PGresult</structname> are discarded by
5040 <xref linkend="libpq-PQexec"/>.
5041 </para>
5042 </listitem>
5044 <listitem>
5045 <para>
5046 <xref linkend="libpq-PQexec"/> always collects the command's entire result,
5047 buffering it in a single <structname>PGresult</structname>. While
5048 this simplifies error-handling logic for the application, it can be
5049 impractical for results containing many rows.
5050 </para>
5051 </listitem>
5052 </itemizedlist>
5053 </para>
5055 <para>
5056 Applications that do not like these limitations can instead use the
5057 underlying functions that <xref linkend="libpq-PQexec"/> is built from:
5058 <xref linkend="libpq-PQsendQuery"/> and <xref linkend="libpq-PQgetResult"/>.
5059 There are also
5060 <xref linkend="libpq-PQsendQueryParams"/>,
5061 <xref linkend="libpq-PQsendPrepare"/>,
5062 <xref linkend="libpq-PQsendQueryPrepared"/>,
5063 <xref linkend="libpq-PQsendDescribePrepared"/>,
5064 <xref linkend="libpq-PQsendDescribePortal"/>,
5065 <xref linkend="libpq-PQsendClosePrepared"/>, and
5066 <xref linkend="libpq-PQsendClosePortal"/>,
5067 which can be used with <xref linkend="libpq-PQgetResult"/> to duplicate
5068 the functionality of
5069 <xref linkend="libpq-PQexecParams"/>,
5070 <xref linkend="libpq-PQprepare"/>,
5071 <xref linkend="libpq-PQexecPrepared"/>,
5072 <xref linkend="libpq-PQdescribePrepared"/>,
5073 <xref linkend="libpq-PQdescribePortal"/>
5074 <xref linkend="libpq-PQclosePrepared"/>, and
5075 <xref linkend="libpq-PQclosePortal"/>
5076 respectively.
5078 <variablelist>
5079 <varlistentry id="libpq-PQsendQuery">
5080 <term><function>PQsendQuery</function><indexterm><primary>PQsendQuery</primary></indexterm></term>
5082 <listitem>
5083 <para>
5084 Submits a command to the server without waiting for the result(s).
5085 1 is returned if the command was successfully dispatched and 0 if
5086 not (in which case, use <xref linkend="libpq-PQerrorMessage"/> to get more
5087 information about the failure).
5088 <synopsis>
5089 int PQsendQuery(PGconn *conn, const char *command);
5090 </synopsis>
5092 After successfully calling <xref linkend="libpq-PQsendQuery"/>, call
5093 <xref linkend="libpq-PQgetResult"/> one or more times to obtain the
5094 results. <xref linkend="libpq-PQsendQuery"/> cannot be called again
5095 (on the same connection) until <xref linkend="libpq-PQgetResult"/>
5096 has returned a null pointer, indicating that the command is done.
5097 </para>
5099 <para>
5100 In pipeline mode, this function is disallowed.
5101 </para>
5102 </listitem>
5103 </varlistentry>
5105 <varlistentry id="libpq-PQsendQueryParams">
5106 <term><function>PQsendQueryParams</function><indexterm><primary>PQsendQueryParams</primary></indexterm></term>
5108 <listitem>
5109 <para>
5110 Submits a command and separate parameters to the server without
5111 waiting for the result(s).
5112 <synopsis>
5113 int PQsendQueryParams(PGconn *conn,
5114 const char *command,
5115 int nParams,
5116 const Oid *paramTypes,
5117 const char * const *paramValues,
5118 const int *paramLengths,
5119 const int *paramFormats,
5120 int resultFormat);
5121 </synopsis>
5123 This is equivalent to <xref linkend="libpq-PQsendQuery"/> except that
5124 query parameters can be specified separately from the query string.
5125 The function's parameters are handled identically to
5126 <xref linkend="libpq-PQexecParams"/>. Like
5127 <xref linkend="libpq-PQexecParams"/>, it allows only one command in the
5128 query string.
5129 </para>
5130 </listitem>
5131 </varlistentry>
5133 <varlistentry id="libpq-PQsendPrepare">
5134 <term><function>PQsendPrepare</function><indexterm><primary>PQsendPrepare</primary></indexterm></term>
5136 <listitem>
5137 <para>
5138 Sends a request to create a prepared statement with the given
5139 parameters, without waiting for completion.
5140 <synopsis>
5141 int PQsendPrepare(PGconn *conn,
5142 const char *stmtName,
5143 const char *query,
5144 int nParams,
5145 const Oid *paramTypes);
5146 </synopsis>
5148 This is an asynchronous version of <xref linkend="libpq-PQprepare"/>: it
5149 returns 1 if it was able to dispatch the request, and 0 if not.
5150 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
5151 determine whether the server successfully created the prepared
5152 statement. The function's parameters are handled identically to
5153 <xref linkend="libpq-PQprepare"/>.
5154 </para>
5155 </listitem>
5156 </varlistentry>
5158 <varlistentry id="libpq-PQsendQueryPrepared">
5159 <term><function>PQsendQueryPrepared</function><indexterm><primary>PQsendQueryPrepared</primary></indexterm></term>
5161 <listitem>
5162 <para>
5163 Sends a request to execute a prepared statement with given
5164 parameters, without waiting for the result(s).
5165 <synopsis>
5166 int PQsendQueryPrepared(PGconn *conn,
5167 const char *stmtName,
5168 int nParams,
5169 const char * const *paramValues,
5170 const int *paramLengths,
5171 const int *paramFormats,
5172 int resultFormat);
5173 </synopsis>
5175 This is similar to <xref linkend="libpq-PQsendQueryParams"/>, but
5176 the command to be executed is specified by naming a
5177 previously-prepared statement, instead of giving a query string.
5178 The function's parameters are handled identically to
5179 <xref linkend="libpq-PQexecPrepared"/>.
5180 </para>
5181 </listitem>
5182 </varlistentry>
5184 <varlistentry id="libpq-PQsendDescribePrepared">
5185 <term><function>PQsendDescribePrepared</function><indexterm><primary>PQsendDescribePrepared</primary></indexterm></term>
5187 <listitem>
5188 <para>
5189 Submits a request to obtain information about the specified
5190 prepared statement, without waiting for completion.
5191 <synopsis>
5192 int PQsendDescribePrepared(PGconn *conn, const char *stmtName);
5193 </synopsis>
5195 This is an asynchronous version of <xref linkend="libpq-PQdescribePrepared"/>:
5196 it returns 1 if it was able to dispatch the request, and 0 if not.
5197 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
5198 obtain the results. The function's parameters are handled
5199 identically to <xref linkend="libpq-PQdescribePrepared"/>.
5200 </para>
5201 </listitem>
5202 </varlistentry>
5204 <varlistentry id="libpq-PQsendDescribePortal">
5205 <term><function>PQsendDescribePortal</function><indexterm><primary>PQsendDescribePortal</primary></indexterm></term>
5207 <listitem>
5208 <para>
5209 Submits a request to obtain information about the specified
5210 portal, without waiting for completion.
5211 <synopsis>
5212 int PQsendDescribePortal(PGconn *conn, const char *portalName);
5213 </synopsis>
5215 This is an asynchronous version of <xref linkend="libpq-PQdescribePortal"/>:
5216 it returns 1 if it was able to dispatch the request, and 0 if not.
5217 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
5218 obtain the results. The function's parameters are handled
5219 identically to <xref linkend="libpq-PQdescribePortal"/>.
5220 </para>
5221 </listitem>
5222 </varlistentry>
5224 <varlistentry id="libpq-PQsendClosePrepared">
5225 <term><function>PQsendClosePrepared</function><indexterm><primary>PQsendClosePrepared</primary></indexterm></term>
5227 <listitem>
5228 <para>
5229 Submits a request to close the specified prepared statement, without
5230 waiting for completion.
5231 <synopsis>
5232 int PQsendClosePrepared(PGconn *conn, const char *stmtName);
5233 </synopsis>
5235 This is an asynchronous version of <xref linkend="libpq-PQclosePrepared"/>:
5236 it returns 1 if it was able to dispatch the request, and 0 if not.
5237 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
5238 obtain the results. The function's parameters are handled
5239 identically to <xref linkend="libpq-PQclosePrepared"/>.
5240 </para>
5241 </listitem>
5242 </varlistentry>
5244 <varlistentry id="libpq-PQsendClosePortal">
5245 <term><function>PQsendClosePortal</function><indexterm><primary>PQsendClosePortal</primary></indexterm></term>
5247 <listitem>
5248 <para>
5249 Submits a request to close specified portal, without waiting for
5250 completion.
5251 <synopsis>
5252 int PQsendClosePortal(PGconn *conn, const char *portalName);
5253 </synopsis>
5255 This is an asynchronous version of <xref linkend="libpq-PQclosePortal"/>:
5256 it returns 1 if it was able to dispatch the request, and 0 if not.
5257 After a successful call, call <xref linkend="libpq-PQgetResult"/> to
5258 obtain the results. The function's parameters are handled
5259 identically to <xref linkend="libpq-PQclosePortal"/>.
5260 </para>
5261 </listitem>
5262 </varlistentry>
5264 <varlistentry id="libpq-PQgetResult">
5265 <term><function>PQgetResult</function><indexterm><primary>PQgetResult</primary></indexterm></term>
5267 <listitem>
5268 <para>
5269 Waits for the next result from a prior
5270 <xref linkend="libpq-PQsendQuery"/>,
5271 <xref linkend="libpq-PQsendQueryParams"/>,
5272 <xref linkend="libpq-PQsendPrepare"/>,
5273 <xref linkend="libpq-PQsendQueryPrepared"/>,
5274 <xref linkend="libpq-PQsendDescribePrepared"/>,
5275 <xref linkend="libpq-PQsendDescribePortal"/>,
5276 <xref linkend="libpq-PQsendClosePrepared"/>,
5277 <xref linkend="libpq-PQsendClosePortal"/>,
5278 <xref linkend="libpq-PQsendPipelineSync"/>, or
5279 <xref linkend="libpq-PQpipelineSync"/>
5280 call, and returns it.
5281 A null pointer is returned when the command is complete and there
5282 will be no more results.
5283 <synopsis>
5284 PGresult *PQgetResult(PGconn *conn);
5285 </synopsis>
5286 </para>
5288 <para>
5289 <xref linkend="libpq-PQgetResult"/> must be called repeatedly until
5290 it returns a null pointer, indicating that the command is done.
5291 (If called when no command is active,
5292 <xref linkend="libpq-PQgetResult"/> will just return a null pointer
5293 at once.) Each non-null result from
5294 <xref linkend="libpq-PQgetResult"/> should be processed using the
5295 same <structname>PGresult</structname> accessor functions previously
5296 described. Don't forget to free each result object with
5297 <xref linkend="libpq-PQclear"/> when done with it. Note that
5298 <xref linkend="libpq-PQgetResult"/> will block only if a command is
5299 active and the necessary response data has not yet been read by
5300 <xref linkend="libpq-PQconsumeInput"/>.
5301 </para>
5303 <para>
5304 In pipeline mode, <function>PQgetResult</function> will return normally
5305 unless an error occurs; for any subsequent query sent after the one
5306 that caused the error until (and excluding) the next synchronization point,
5307 a special result of type <literal>PGRES_PIPELINE_ABORTED</literal> will
5308 be returned, and a null pointer will be returned after it.
5309 When the pipeline synchronization point is reached, a result of type
5310 <literal>PGRES_PIPELINE_SYNC</literal> will be returned.
5311 The result of the next query after the synchronization point follows
5312 immediately (that is, no null pointer is returned after
5313 the synchronization point.)
5314 </para>
5316 <note>
5317 <para>
5318 Even when <xref linkend="libpq-PQresultStatus"/> indicates a fatal
5319 error, <xref linkend="libpq-PQgetResult"/> should be called until it
5320 returns a null pointer, to allow <application>libpq</application> to
5321 process the error information completely.
5322 </para>
5323 </note>
5324 </listitem>
5325 </varlistentry>
5326 </variablelist>
5327 </para>
5329 <para>
5330 Using <xref linkend="libpq-PQsendQuery"/> and
5331 <xref linkend="libpq-PQgetResult"/> solves one of
5332 <xref linkend="libpq-PQexec"/>'s problems: If a command string contains
5333 multiple <acronym>SQL</acronym> commands, the results of those commands
5334 can be obtained individually. (This allows a simple form of overlapped
5335 processing, by the way: the client can be handling the results of one
5336 command while the server is still working on later queries in the same
5337 command string.)
5338 </para>
5340 <para>
5341 Another frequently-desired feature that can be obtained with
5342 <xref linkend="libpq-PQsendQuery"/> and <xref linkend="libpq-PQgetResult"/>
5343 is retrieving large query results a limited number of rows at a time.
5344 This is discussed
5345 in <xref linkend="libpq-single-row-mode"/>.
5346 </para>
5348 <para>
5349 By itself, calling <xref linkend="libpq-PQgetResult"/>
5350 will still cause the client to block until the server completes the
5351 next <acronym>SQL</acronym> command. This can be avoided by proper
5352 use of two more functions:
5354 <variablelist>
5355 <varlistentry id="libpq-PQconsumeInput">
5356 <term><function>PQconsumeInput</function><indexterm><primary>PQconsumeInput</primary></indexterm>
5357 </term>
5359 <listitem>
5360 <para>
5361 If input is available from the server, consume it.
5362 <synopsis>
5363 int PQconsumeInput(PGconn *conn);
5364 </synopsis>
5365 </para>
5367 <para>
5368 <xref linkend="libpq-PQconsumeInput"/> normally returns 1 indicating
5369 <quote>no error</quote>, but returns 0 if there was some kind of
5370 trouble (in which case <xref linkend="libpq-PQerrorMessage"/> can be
5371 consulted). Note that the result does not say whether any input
5372 data was actually collected. After calling
5373 <xref linkend="libpq-PQconsumeInput"/>, the application can check
5374 <xref linkend="libpq-PQisBusy"/> and/or
5375 <function>PQnotifies</function> to see if their state has changed.
5376 </para>
5378 <para>
5379 <xref linkend="libpq-PQconsumeInput"/> can be called even if the
5380 application is not prepared to deal with a result or notification
5381 just yet. The function will read available data and save it in
5382 a buffer, thereby causing a <function>select()</function>
5383 read-ready indication to go away. The application can thus use
5384 <xref linkend="libpq-PQconsumeInput"/> to clear the
5385 <function>select()</function> condition immediately, and then
5386 examine the results at leisure.
5387 </para>
5388 </listitem>
5389 </varlistentry>
5391 <varlistentry id="libpq-PQisBusy">
5392 <term><function>PQisBusy</function><indexterm><primary>PQisBusy</primary></indexterm></term>
5394 <listitem>
5395 <para>
5396 Returns 1 if a command is busy, that is,
5397 <xref linkend="libpq-PQgetResult"/> would block waiting for input.
5398 A 0 return indicates that <xref linkend="libpq-PQgetResult"/> can be
5399 called with assurance of not blocking.
5400 <synopsis>
5401 int PQisBusy(PGconn *conn);
5402 </synopsis>
5403 </para>
5405 <para>
5406 <xref linkend="libpq-PQisBusy"/> will not itself attempt to read data
5407 from the server; therefore <xref linkend="libpq-PQconsumeInput"/>
5408 must be invoked first, or the busy state will never end.
5409 </para>
5410 </listitem>
5411 </varlistentry>
5412 </variablelist>
5413 </para>
5415 <para>
5416 A typical application using these functions will have a main loop that
5417 uses <function>select()</function> or <function>poll()</function> to wait for
5418 all the conditions that it must respond to. One of the conditions
5419 will be input available from the server, which in terms of
5420 <function>select()</function> means readable data on the file
5421 descriptor identified by <xref linkend="libpq-PQsocket"/>. When the main
5422 loop detects input ready, it should call
5423 <xref linkend="libpq-PQconsumeInput"/> to read the input. It can then
5424 call <xref linkend="libpq-PQisBusy"/>, followed by
5425 <xref linkend="libpq-PQgetResult"/> if <xref linkend="libpq-PQisBusy"/>
5426 returns false (0). It can also call <function>PQnotifies</function>
5427 to detect <command>NOTIFY</command> messages (see <xref
5428 linkend="libpq-notify"/>).
5429 </para>
5431 <para>
5432 A client that uses
5433 <xref linkend="libpq-PQsendQuery"/>/<xref linkend="libpq-PQgetResult"/>
5434 can also attempt to cancel a command that is still being processed
5435 by the server; see <xref linkend="libpq-cancel"/>. But regardless of
5436 the return value of <xref linkend="libpq-PQcancelBlocking"/>, the application
5437 must continue with the normal result-reading sequence using
5438 <xref linkend="libpq-PQgetResult"/>. A successful cancellation will
5439 simply cause the command to terminate sooner than it would have
5440 otherwise.
5441 </para>
5443 <para>
5444 By using the functions described above, it is possible to avoid
5445 blocking while waiting for input from the database server. However,
5446 it is still possible that the application will block waiting to send
5447 output to the server. This is relatively uncommon but can happen if
5448 very long SQL commands or data values are sent. (It is much more
5449 probable if the application sends data via <command>COPY IN</command>,
5450 however.) To prevent this possibility and achieve completely
5451 nonblocking database operation, the following additional functions
5452 can be used.
5454 <variablelist>
5455 <varlistentry id="libpq-PQsetnonblocking">
5456 <term><function>PQsetnonblocking</function><indexterm><primary>PQsetnonblocking</primary></indexterm></term>
5458 <listitem>
5459 <para>
5460 Sets the nonblocking status of the connection.
5461 <synopsis>
5462 int PQsetnonblocking(PGconn *conn, int arg);
5463 </synopsis>
5464 </para>
5466 <para>
5467 Sets the state of the connection to nonblocking if
5468 <parameter>arg</parameter> is 1, or blocking if
5469 <parameter>arg</parameter> is 0. Returns 0 if OK, -1 if error.
5470 </para>
5472 <para>
5473 In the nonblocking state, successful calls to
5474 <xref linkend="libpq-PQsendQuery"/>, <xref linkend="libpq-PQputline"/>,
5475 <xref linkend="libpq-PQputnbytes"/>, <xref linkend="libpq-PQputCopyData"/>,
5476 and <xref linkend="libpq-PQendcopy"/> will not block; their changes
5477 are stored in the local output buffer until they are flushed.
5478 Unsuccessful calls will return an error and must be retried.
5479 </para>
5481 <para>
5482 Note that <xref linkend="libpq-PQexec"/> does not honor nonblocking
5483 mode; if it is called, it will act in blocking fashion anyway.
5484 </para>
5485 </listitem>
5486 </varlistentry>
5488 <varlistentry id="libpq-PQisnonblocking">
5489 <term><function>PQisnonblocking</function><indexterm><primary>PQisnonblocking</primary></indexterm></term>
5491 <listitem>
5492 <para>
5493 Returns the blocking status of the database connection.
5494 <synopsis>
5495 int PQisnonblocking(const PGconn *conn);
5496 </synopsis>
5497 </para>
5499 <para>
5500 Returns 1 if the connection is set to nonblocking mode and 0 if
5501 blocking.
5502 </para>
5503 </listitem>
5504 </varlistentry>
5506 <varlistentry id="libpq-PQflush">
5507 <term><function>PQflush</function><indexterm><primary>PQflush</primary></indexterm></term>
5509 <listitem>
5510 <para>
5511 Attempts to flush any queued output data to the server. Returns
5512 0 if successful (or if the send queue is empty), -1 if it failed
5513 for some reason, or 1 if it was unable to send all the data in
5514 the send queue yet (this case can only occur if the connection
5515 is nonblocking).
5516 <synopsis>
5517 int PQflush(PGconn *conn);
5518 </synopsis>
5519 </para>
5520 </listitem>
5521 </varlistentry>
5522 </variablelist>
5523 </para>
5525 <para>
5526 After sending any command or data on a nonblocking connection, call
5527 <xref linkend="libpq-PQflush"/>. If it returns 1, wait for the socket
5528 to become read- or write-ready. If it becomes write-ready, call
5529 <xref linkend="libpq-PQflush"/> again. If it becomes read-ready, call
5530 <xref linkend="libpq-PQconsumeInput"/>, then call
5531 <xref linkend="libpq-PQflush"/> again. Repeat until
5532 <xref linkend="libpq-PQflush"/> returns 0. (It is necessary to check for
5533 read-ready and drain the input with <xref linkend="libpq-PQconsumeInput"/>,
5534 because the server can block trying to send us data, e.g., NOTICE
5535 messages, and won't read our data until we read its.) Once
5536 <xref linkend="libpq-PQflush"/> returns 0, wait for the socket to be
5537 read-ready and then read the response as described above.
5538 </para>
5540 </sect1>
5542 <sect1 id="libpq-pipeline-mode">
5543 <title>Pipeline Mode</title>
5545 <indexterm zone="libpq-pipeline-mode">
5546 <primary>libpq</primary>
5547 <secondary>pipeline mode</secondary>
5548 </indexterm>
5550 <indexterm zone="libpq-pipeline-mode">
5551 <primary>pipelining</primary>
5552 <secondary>in libpq</secondary>
5553 </indexterm>
5555 <indexterm zone="libpq-pipeline-mode">
5556 <primary>batch mode</primary>
5557 <secondary>in libpq</secondary>
5558 </indexterm>
5560 <para>
5561 <application>libpq</application> pipeline mode allows applications to
5562 send a query without having to read the result of the previously
5563 sent query. Taking advantage of the pipeline mode, a client will wait
5564 less for the server, since multiple queries/results can be
5565 sent/received in a single network transaction.
5566 </para>
5568 <para>
5569 While pipeline mode provides a significant performance boost, writing
5570 clients using the pipeline mode is more complex because it involves
5571 managing a queue of pending queries and finding which result
5572 corresponds to which query in the queue.
5573 </para>
5575 <para>
5576 Pipeline mode also generally consumes more memory on both the client and server,
5577 though careful and aggressive management of the send/receive queue can mitigate
5578 this. This applies whether or not the connection is in blocking or non-blocking
5579 mode.
5580 </para>
5582 <para>
5583 While <application>libpq</application>'s pipeline API was introduced in
5584 <productname>PostgreSQL</productname> 14, it is a client-side feature
5585 which doesn't require special server support and works on any server
5586 that supports the v3 extended query protocol. For more information see
5587 <xref linkend="protocol-flow-pipelining"/>.
5588 </para>
5590 <sect2 id="libpq-pipeline-using">
5591 <title>Using Pipeline Mode</title>
5593 <para>
5594 To issue pipelines, the application must switch the connection
5595 into pipeline mode,
5596 which is done with <xref linkend="libpq-PQenterPipelineMode"/>.
5597 <xref linkend="libpq-PQpipelineStatus"/> can be used
5598 to test whether pipeline mode is active.
5599 In pipeline mode, only <link linkend="libpq-async">asynchronous operations</link>
5600 that utilize the extended query protocol
5601 are permitted, command strings containing multiple SQL commands are
5602 disallowed, and so is <literal>COPY</literal>.
5603 Using synchronous command execution functions
5604 such as <function>PQfn</function>,
5605 <function>PQexec</function>,
5606 <function>PQexecParams</function>,
5607 <function>PQprepare</function>,
5608 <function>PQexecPrepared</function>,
5609 <function>PQdescribePrepared</function>,
5610 <function>PQdescribePortal</function>,
5611 <function>PQclosePrepared</function>,
5612 <function>PQclosePortal</function>,
5613 is an error condition.
5614 <function>PQsendQuery</function> is
5615 also disallowed, because it uses the simple query protocol.
5616 Once all dispatched commands have had their results processed, and
5617 the end pipeline result has been consumed, the application may return
5618 to non-pipelined mode with <xref linkend="libpq-PQexitPipelineMode"/>.
5619 </para>
5621 <note>
5622 <para>
5623 It is best to use pipeline mode with <application>libpq</application> in
5624 <link linkend="libpq-PQsetnonblocking">non-blocking mode</link>. If used
5625 in blocking mode it is possible for a client/server deadlock to occur.
5626 <footnote>
5627 <para>
5628 The client will block trying to send queries to the server, but the
5629 server will block trying to send results to the client from queries
5630 it has already processed. This only occurs when the client sends
5631 enough queries to fill both its output buffer and the server's receive
5632 buffer before it switches to processing input from the server,
5633 but it's hard to predict exactly when that will happen.
5634 </para>
5635 </footnote>
5636 </para>
5637 </note>
5639 <sect3 id="libpq-pipeline-sending">
5640 <title>Issuing Queries</title>
5642 <para>
5643 After entering pipeline mode, the application dispatches requests using
5644 <xref linkend="libpq-PQsendQueryParams"/>
5645 or its prepared-query sibling
5646 <xref linkend="libpq-PQsendQueryPrepared"/>.
5647 These requests are queued on the client-side until flushed to the server;
5648 this occurs when <xref linkend="libpq-PQpipelineSync"/> is used to
5649 establish a synchronization point in the pipeline,
5650 or when <xref linkend="libpq-PQflush"/> is called.
5651 The functions <xref linkend="libpq-PQsendPrepare"/>,
5652 <xref linkend="libpq-PQsendDescribePrepared"/>,
5653 <xref linkend="libpq-PQsendDescribePortal"/>,
5654 <xref linkend="libpq-PQsendClosePrepared"/>, and
5655 <xref linkend="libpq-PQsendClosePortal"/> also work in pipeline mode.
5656 Result processing is described below.
5657 </para>
5659 <para>
5660 The server executes statements, and returns results, in the order the
5661 client sends them. The server will begin executing the commands in the
5662 pipeline immediately, not waiting for the end of the pipeline.
5663 Note that results are buffered on the server side; the server flushes
5664 that buffer when a synchronization point is established with either
5665 <function>PQpipelineSync</function> or
5666 <function>PQsendPipelineSync</function>, or when
5667 <function>PQsendFlushRequest</function> is called.
5668 If any statement encounters an error, the server aborts the current
5669 transaction and does not execute any subsequent command in the queue
5670 until the next synchronization point;
5671 a <literal>PGRES_PIPELINE_ABORTED</literal> result is produced for
5672 each such command.
5673 (This remains true even if the commands in the pipeline would rollback
5674 the transaction.)
5675 Query processing resumes after the synchronization point.
5676 </para>
5678 <para>
5679 It's fine for one operation to depend on the results of a
5680 prior one; for example, one query may define a table that the next
5681 query in the same pipeline uses. Similarly, an application may
5682 create a named prepared statement and execute it with later
5683 statements in the same pipeline.
5684 </para>
5685 </sect3>
5687 <sect3 id="libpq-pipeline-results">
5688 <title>Processing Results</title>
5690 <para>
5691 To process the result of one query in a pipeline, the application calls
5692 <function>PQgetResult</function> repeatedly and handles each result
5693 until <function>PQgetResult</function> returns null.
5694 The result from the next query in the pipeline may then be retrieved using
5695 <function>PQgetResult</function> again and the cycle repeated.
5696 The application handles individual statement results as normal.
5697 When the results of all the queries in the pipeline have been
5698 returned, <function>PQgetResult</function> returns a result
5699 containing the status value <literal>PGRES_PIPELINE_SYNC</literal>
5700 </para>
5702 <para>
5703 The client may choose to defer result processing until the complete
5704 pipeline has been sent, or interleave that with sending further
5705 queries in the pipeline; see <xref linkend="libpq-pipeline-interleave"/>.
5706 </para>
5708 <para>
5709 <function>PQgetResult</function> behaves the same as for normal
5710 asynchronous processing except that it may contain the new
5711 <type>PGresult</type> types <literal>PGRES_PIPELINE_SYNC</literal>
5712 and <literal>PGRES_PIPELINE_ABORTED</literal>.
5713 <literal>PGRES_PIPELINE_SYNC</literal> is reported exactly once for each
5714 <function>PQpipelineSync</function> or
5715 <function>PQsendPipelineSync</function> at the corresponding point
5716 in the pipeline.
5717 <literal>PGRES_PIPELINE_ABORTED</literal> is emitted in place of a normal
5718 query result for the first error and all subsequent results
5719 until the next <literal>PGRES_PIPELINE_SYNC</literal>;
5720 see <xref linkend="libpq-pipeline-errors"/>.
5721 </para>
5723 <para>
5724 <function>PQisBusy</function>, <function>PQconsumeInput</function>, etc
5725 operate as normal when processing pipeline results. In particular,
5726 a call to <function>PQisBusy</function> in the middle of a pipeline
5727 returns 0 if the results for all the queries issued so far have been
5728 consumed.
5729 </para>
5731 <para>
5732 <application>libpq</application> does not provide any information to the
5733 application about the query currently being processed (except that
5734 <function>PQgetResult</function> returns null to indicate that we start
5735 returning the results of next query). The application must keep track
5736 of the order in which it sent queries, to associate them with their
5737 corresponding results.
5738 Applications will typically use a state machine or a FIFO queue for this.
5739 </para>
5741 </sect3>
5743 <sect3 id="libpq-pipeline-errors">
5744 <title>Error Handling</title>
5746 <para>
5747 From the client's perspective, after <function>PQresultStatus</function>
5748 returns <literal>PGRES_FATAL_ERROR</literal>,
5749 the pipeline is flagged as aborted.
5750 <function>PQresultStatus</function> will report a
5751 <literal>PGRES_PIPELINE_ABORTED</literal> result for each remaining queued
5752 operation in an aborted pipeline. The result for
5753 <function>PQpipelineSync</function> or
5754 <function>PQsendPipelineSync</function> is reported as
5755 <literal>PGRES_PIPELINE_SYNC</literal> to signal the end of the aborted pipeline
5756 and resumption of normal result processing.
5757 </para>
5759 <para>
5760 The client <emphasis>must</emphasis> process results with
5761 <function>PQgetResult</function> during error recovery.
5762 </para>
5764 <para>
5765 If the pipeline used an implicit transaction, then operations that have
5766 already executed are rolled back and operations that were queued to follow
5767 the failed operation are skipped entirely. The same behavior holds if the
5768 pipeline starts and commits a single explicit transaction (i.e. the first
5769 statement is <literal>BEGIN</literal> and the last is
5770 <literal>COMMIT</literal>) except that the session remains in an aborted
5771 transaction state at the end of the pipeline. If a pipeline contains
5772 <emphasis>multiple explicit transactions</emphasis>, all transactions that
5773 committed prior to the error remain committed, the currently in-progress
5774 transaction is aborted, and all subsequent operations are skipped completely,
5775 including subsequent transactions. If a pipeline synchronization point
5776 occurs with an explicit transaction block in aborted state, the next pipeline
5777 will become aborted immediately unless the next command puts the transaction
5778 in normal mode with <command>ROLLBACK</command>.
5779 </para>
5781 <note>
5782 <para>
5783 The client must not assume that work is committed when it
5784 <emphasis>sends</emphasis> a <literal>COMMIT</literal> &mdash; only when the
5785 corresponding result is received to confirm the commit is complete.
5786 Because errors arrive asynchronously, the application needs to be able to
5787 restart from the last <emphasis>received</emphasis> committed change and
5788 resend work done after that point if something goes wrong.
5789 </para>
5790 </note>
5791 </sect3>
5793 <sect3 id="libpq-pipeline-interleave">
5794 <title>Interleaving Result Processing and Query Dispatch</title>
5796 <para>
5797 To avoid deadlocks on large pipelines the client should be structured
5798 around a non-blocking event loop using operating system facilities
5799 such as <function>select</function>, <function>poll</function>,
5800 <function>WaitForMultipleObjectEx</function>, etc.
5801 </para>
5803 <para>
5804 The client application should generally maintain a queue of work
5805 remaining to be dispatched and a queue of work that has been dispatched
5806 but not yet had its results processed. When the socket is writable
5807 it should dispatch more work. When the socket is readable it should
5808 read results and process them, matching them up to the next entry in
5809 its corresponding results queue. Based on available memory, results from the
5810 socket should be read frequently: there's no need to wait until the
5811 pipeline end to read the results. Pipelines should be scoped to logical
5812 units of work, usually (but not necessarily) one transaction per pipeline.
5813 There's no need to exit pipeline mode and re-enter it between pipelines,
5814 or to wait for one pipeline to finish before sending the next.
5815 </para>
5817 <para>
5818 An example using <function>select()</function> and a simple state
5819 machine to track sent and received work is in
5820 <filename>src/test/modules/libpq_pipeline/libpq_pipeline.c</filename>
5821 in the PostgreSQL source distribution.
5822 </para>
5823 </sect3>
5824 </sect2>
5826 <sect2 id="libpq-pipeline-functions">
5827 <title>Functions Associated with Pipeline Mode</title>
5829 <variablelist>
5831 <varlistentry id="libpq-PQpipelineStatus">
5832 <term><function>PQpipelineStatus</function><indexterm><primary>PQpipelineStatus</primary></indexterm></term>
5834 <listitem>
5835 <para>
5836 Returns the current pipeline mode status of the
5837 <application>libpq</application> connection.
5838 <synopsis>
5839 PGpipelineStatus PQpipelineStatus(const PGconn *conn);
5840 </synopsis>
5841 </para>
5843 <para>
5844 <function>PQpipelineStatus</function> can return one of the following values:
5846 <variablelist>
5847 <varlistentry>
5848 <term>
5849 <literal>PQ_PIPELINE_ON</literal>
5850 </term>
5851 <listitem>
5852 <para>
5853 The <application>libpq</application> connection is in
5854 pipeline mode.
5855 </para>
5856 </listitem>
5857 </varlistentry>
5859 <varlistentry>
5860 <term>
5861 <literal>PQ_PIPELINE_OFF</literal>
5862 </term>
5863 <listitem>
5864 <para>
5865 The <application>libpq</application> connection is
5866 <emphasis>not</emphasis> in pipeline mode.
5867 </para>
5868 </listitem>
5869 </varlistentry>
5871 <varlistentry>
5872 <term>
5873 <literal>PQ_PIPELINE_ABORTED</literal>
5874 </term>
5875 <listitem>
5876 <para>
5877 The <application>libpq</application> connection is in pipeline
5878 mode and an error occurred while processing the current pipeline.
5879 The aborted flag is cleared when <function>PQgetResult</function>
5880 returns a result of type <literal>PGRES_PIPELINE_SYNC</literal>.
5881 </para>
5882 </listitem>
5883 </varlistentry>
5885 </variablelist>
5886 </para>
5887 </listitem>
5888 </varlistentry>
5890 <varlistentry id="libpq-PQenterPipelineMode">
5891 <term><function>PQenterPipelineMode</function><indexterm><primary>PQenterPipelineMode</primary></indexterm></term>
5893 <listitem>
5894 <para>
5895 Causes a connection to enter pipeline mode if it is currently idle or
5896 already in pipeline mode.
5898 <synopsis>
5899 int PQenterPipelineMode(PGconn *conn);
5900 </synopsis>
5902 </para>
5903 <para>
5904 Returns 1 for success.
5905 Returns 0 and has no effect if the connection is not currently
5906 idle, i.e., it has a result ready, or it is waiting for more
5907 input from the server, etc.
5908 This function does not actually send anything to the server,
5909 it just changes the <application>libpq</application> connection
5910 state.
5911 </para>
5912 </listitem>
5913 </varlistentry>
5915 <varlistentry id="libpq-PQexitPipelineMode">
5916 <term><function>PQexitPipelineMode</function><indexterm><primary>PQexitPipelineMode</primary></indexterm></term>
5918 <listitem>
5919 <para>
5920 Causes a connection to exit pipeline mode if it is currently in pipeline mode
5921 with an empty queue and no pending results.
5922 <synopsis>
5923 int PQexitPipelineMode(PGconn *conn);
5924 </synopsis>
5925 </para>
5926 <para>
5927 Returns 1 for success. Returns 1 and takes no action if not in
5928 pipeline mode. If the current statement isn't finished processing,
5929 or <function>PQgetResult</function> has not been called to collect
5930 results from all previously sent query, returns 0 (in which case,
5931 use <xref linkend="libpq-PQerrorMessage"/> to get more information
5932 about the failure).
5933 </para>
5934 </listitem>
5935 </varlistentry>
5937 <varlistentry id="libpq-PQpipelineSync">
5938 <term><function>PQpipelineSync</function><indexterm><primary>PQpipelineSync</primary></indexterm></term>
5940 <listitem>
5941 <para>
5942 Marks a synchronization point in a pipeline by sending a
5943 <link linkend="protocol-flow-ext-query">sync message</link>
5944 and flushing the send buffer. This serves as
5945 the delimiter of an implicit transaction and an error recovery
5946 point; see <xref linkend="libpq-pipeline-errors"/>.
5948 <synopsis>
5949 int PQpipelineSync(PGconn *conn);
5950 </synopsis>
5951 </para>
5952 <para>
5953 Returns 1 for success. Returns 0 if the connection is not in
5954 pipeline mode or sending a
5955 <link linkend="protocol-flow-ext-query">sync message</link>
5956 failed.
5957 </para>
5958 </listitem>
5959 </varlistentry>
5961 <varlistentry id="libpq-PQsendPipelineSync">
5962 <term><function>PQsendPipelineSync</function><indexterm><primary>PQsendPipelineSync</primary></indexterm></term>
5964 <listitem>
5965 <para>
5966 Marks a synchronization point in a pipeline by sending a
5967 <link linkend="protocol-flow-ext-query">sync message</link>
5968 without flushing the send buffer. This serves as
5969 the delimiter of an implicit transaction and an error recovery
5970 point; see <xref linkend="libpq-pipeline-errors"/>.
5972 <synopsis>
5973 int PQsendPipelineSync(PGconn *conn);
5974 </synopsis>
5975 </para>
5976 <para>
5977 Returns 1 for success. Returns 0 if the connection is not in
5978 pipeline mode or sending a
5979 <link linkend="protocol-flow-ext-query">sync message</link>
5980 failed.
5981 Note that the message is not itself flushed to the server automatically;
5982 use <function>PQflush</function> if necessary.
5983 </para>
5984 </listitem>
5985 </varlistentry>
5987 <varlistentry id="libpq-PQsendFlushRequest">
5988 <term><function>PQsendFlushRequest</function><indexterm><primary>PQsendFlushRequest</primary></indexterm></term>
5990 <listitem>
5991 <para>
5992 Sends a request for the server to flush its output buffer.
5993 <synopsis>
5994 int PQsendFlushRequest(PGconn *conn);
5995 </synopsis>
5996 </para>
5998 <para>
5999 Returns 1 for success. Returns 0 on any failure.
6000 </para>
6001 <para>
6002 The server flushes its output buffer automatically as a result of
6003 <function>PQpipelineSync</function> being called, or
6004 on any request when not in pipeline mode; this function is useful
6005 to cause the server to flush its output buffer in pipeline mode
6006 without establishing a synchronization point.
6007 Note that the request is not itself flushed to the server automatically;
6008 use <function>PQflush</function> if necessary.
6009 </para>
6010 </listitem>
6011 </varlistentry>
6012 </variablelist>
6013 </sect2>
6015 <sect2 id="libpq-pipeline-tips">
6016 <title>When to Use Pipeline Mode</title>
6018 <para>
6019 Much like asynchronous query mode, there is no meaningful performance
6020 overhead when using pipeline mode. It increases client application complexity,
6021 and extra caution is required to prevent client/server deadlocks, but
6022 pipeline mode can offer considerable performance improvements, in exchange for
6023 increased memory usage from leaving state around longer.
6024 </para>
6026 <para>
6027 Pipeline mode is most useful when the server is distant, i.e., network latency
6028 (<quote>ping time</quote>) is high, and also when many small operations
6029 are being performed in rapid succession. There is usually less benefit
6030 in using pipelined commands when each query takes many multiples of the client/server
6031 round-trip time to execute. A 100-statement operation run on a server
6032 300 ms round-trip-time away would take 30 seconds in network latency alone
6033 without pipelining; with pipelining it may spend as little as 0.3 s waiting for
6034 results from the server.
6035 </para>
6037 <para>
6038 Use pipelined commands when your application does lots of small
6039 <literal>INSERT</literal>, <literal>UPDATE</literal> and
6040 <literal>DELETE</literal> operations that can't easily be transformed
6041 into operations on sets, or into a <literal>COPY</literal> operation.
6042 </para>
6044 <para>
6045 Pipeline mode is not useful when information from one operation is required by
6046 the client to produce the next operation. In such cases, the client
6047 would have to introduce a synchronization point and wait for a full client/server
6048 round-trip to get the results it needs. However, it's often possible to
6049 adjust the client design to exchange the required information server-side.
6050 Read-modify-write cycles are especially good candidates; for example:
6051 <programlisting>
6052 BEGIN;
6053 SELECT x FROM mytable WHERE id = 42 FOR UPDATE;
6054 -- result: x=2
6055 -- client adds 1 to x:
6056 UPDATE mytable SET x = 3 WHERE id = 42;
6057 COMMIT;
6058 </programlisting>
6059 could be much more efficiently done with:
6060 <programlisting>
6061 UPDATE mytable SET x = x + 1 WHERE id = 42;
6062 </programlisting>
6063 </para>
6065 <para>
6066 Pipelining is less useful, and more complex, when a single pipeline contains
6067 multiple transactions (see <xref linkend="libpq-pipeline-errors"/>).
6068 </para>
6069 </sect2>
6070 </sect1>
6072 <!-- keep this not-too-apropos sect1 ID for stability of doc URLs -->
6073 <sect1 id="libpq-single-row-mode">
6074 <title>Retrieving Query Results in Chunks</title>
6076 <indexterm zone="libpq-single-row-mode">
6077 <primary>libpq</primary>
6078 <secondary>single-row mode</secondary>
6079 </indexterm>
6081 <indexterm zone="libpq-single-row-mode">
6082 <primary>libpq</primary>
6083 <secondary>chunked mode</secondary>
6084 </indexterm>
6086 <para>
6087 Ordinarily, <application>libpq</application> collects an SQL command's
6088 entire result and returns it to the application as a single
6089 <structname>PGresult</structname>. This can be unworkable for commands
6090 that return a large number of rows. For such cases, applications can use
6091 <xref linkend="libpq-PQsendQuery"/> and <xref linkend="libpq-PQgetResult"/> in
6092 <firstterm>single-row mode</firstterm> or <firstterm>chunked
6093 mode</firstterm>. In these modes, result row(s) are returned to the
6094 application as they are received from the server, one at a time for
6095 single-row mode or in groups for chunked mode.
6096 </para>
6098 <para>
6099 To enter one of these modes, call <xref linkend="libpq-PQsetSingleRowMode"/>
6100 or <xref linkend="libpq-PQsetChunkedRowsMode"/>
6101 immediately after a successful call of <xref linkend="libpq-PQsendQuery"/>
6102 (or a sibling function). This mode selection is effective only for the
6103 currently executing query. Then call <xref linkend="libpq-PQgetResult"/>
6104 repeatedly, until it returns null, as documented in <xref
6105 linkend="libpq-async"/>. If the query returns any rows, they are returned
6106 as one or more <structname>PGresult</structname> objects, which look like
6107 normal query results except for having status code
6108 <literal>PGRES_SINGLE_TUPLE</literal> for single-row mode or
6109 <literal>PGRES_TUPLES_CHUNK</literal> for chunked mode, instead of
6110 <literal>PGRES_TUPLES_OK</literal>. There is exactly one result row in
6111 each <literal>PGRES_SINGLE_TUPLE</literal> object, while
6112 a <literal>PGRES_TUPLES_CHUNK</literal> object contains at least one
6113 row but not more than the specified number of rows per chunk.
6114 After the last row, or immediately if
6115 the query returns zero rows, a zero-row object with status
6116 <literal>PGRES_TUPLES_OK</literal> is returned; this is the signal that no
6117 more rows will arrive. (But note that it is still necessary to continue
6118 calling <xref linkend="libpq-PQgetResult"/> until it returns null.) All of
6119 these <structname>PGresult</structname> objects will contain the same row
6120 description data (column names, types, etc.) that an ordinary
6121 <structname>PGresult</structname> object for the query would have.
6122 Each object should be freed with <xref linkend="libpq-PQclear"/> as usual.
6123 </para>
6125 <para>
6126 When using pipeline mode, single-row or chunked mode needs to be
6127 activated for each query in the pipeline before retrieving results for
6128 that query with <function>PQgetResult</function>.
6129 See <xref linkend="libpq-pipeline-mode"/> for more information.
6130 </para>
6132 <para>
6133 <variablelist>
6134 <varlistentry id="libpq-PQsetSingleRowMode">
6135 <term><function>PQsetSingleRowMode</function><indexterm><primary>PQsetSingleRowMode</primary></indexterm></term>
6137 <listitem>
6138 <para>
6139 Select single-row mode for the currently-executing query.
6141 <synopsis>
6142 int PQsetSingleRowMode(PGconn *conn);
6143 </synopsis>
6144 </para>
6146 <para>
6147 This function can only be called immediately after
6148 <xref linkend="libpq-PQsendQuery"/> or one of its sibling functions,
6149 before any other operation on the connection such as
6150 <xref linkend="libpq-PQconsumeInput"/> or
6151 <xref linkend="libpq-PQgetResult"/>. If called at the correct time,
6152 the function activates single-row mode for the current query and
6153 returns 1. Otherwise the mode stays unchanged and the function
6154 returns 0. In any case, the mode reverts to normal after
6155 completion of the current query.
6156 </para>
6157 </listitem>
6158 </varlistentry>
6160 <varlistentry id="libpq-PQsetChunkedRowsMode">
6161 <term><function>PQsetChunkedRowsMode</function><indexterm><primary>PQsetChunkedRowsMode</primary></indexterm></term>
6163 <listitem>
6164 <para>
6165 Select chunked mode for the currently-executing query.
6167 <synopsis>
6168 int PQsetChunkedRowsMode(PGconn *conn, int chunkSize);
6169 </synopsis>
6170 </para>
6172 <para>
6173 This function is similar to
6174 <xref linkend="libpq-PQsetSingleRowMode"/>, except that it
6175 specifies retrieval of up to <replaceable>chunkSize</replaceable> rows
6176 per <structname>PGresult</structname>, not necessarily just one row.
6177 This function can only be called immediately after
6178 <xref linkend="libpq-PQsendQuery"/> or one of its sibling functions,
6179 before any other operation on the connection such as
6180 <xref linkend="libpq-PQconsumeInput"/> or
6181 <xref linkend="libpq-PQgetResult"/>. If called at the correct time,
6182 the function activates chunked mode for the current query and
6183 returns 1. Otherwise the mode stays unchanged and the function
6184 returns 0. In any case, the mode reverts to normal after
6185 completion of the current query.
6186 </para>
6187 </listitem>
6188 </varlistentry>
6189 </variablelist>
6190 </para>
6192 <caution>
6193 <para>
6194 While processing a query, the server may return some rows and then
6195 encounter an error, causing the query to be aborted. Ordinarily,
6196 <application>libpq</application> discards any such rows and reports only the
6197 error. But in single-row or chunked mode, some rows may have already
6198 been returned to the application. Hence, the application will see some
6199 <literal>PGRES_SINGLE_TUPLE</literal> or <literal>PGRES_TUPLES_CHUNK</literal>
6200 <structname>PGresult</structname>
6201 objects followed by a <literal>PGRES_FATAL_ERROR</literal> object. For
6202 proper transactional behavior, the application must be designed to
6203 discard or undo whatever has been done with the previously-processed
6204 rows, if the query ultimately fails.
6205 </para>
6206 </caution>
6208 </sect1>
6210 <sect1 id="libpq-cancel">
6211 <title>Canceling Queries in Progress</title>
6213 <indexterm zone="libpq-cancel">
6214 <primary>canceling SQL queries</primary>
6215 </indexterm>
6216 <indexterm zone="libpq-cancel">
6217 <primary>query cancellation</primary>
6218 </indexterm>
6220 <sect2 id="libpq-cancel-functions">
6221 <title>Functions for Sending Cancel Requests</title>
6222 <variablelist>
6223 <varlistentry id="libpq-PQcancelCreate">
6224 <term><function>PQcancelCreate</function><indexterm><primary>PQcancelCreate</primary></indexterm></term>
6226 <listitem>
6227 <para>
6228 Prepares a connection over which a cancel request can be sent.
6229 <synopsis>
6230 PGcancelConn *PQcancelCreate(PGconn *conn);
6231 </synopsis>
6232 </para>
6234 <para>
6235 <xref linkend="libpq-PQcancelCreate"/> creates a
6236 <structname>PGcancelConn</structname><indexterm><primary>PGcancelConn</primary></indexterm>
6237 object, but it won't instantly start sending a cancel request over this
6238 connection. A cancel request can be sent over this connection in a
6239 blocking manner using <xref linkend="libpq-PQcancelBlocking"/> and in a
6240 non-blocking manner using <xref linkend="libpq-PQcancelStart"/>.
6241 The return value can be passed to <xref linkend="libpq-PQcancelStatus"/>
6242 to check if the <structname>PGcancelConn</structname> object was
6243 created successfully. The <structname>PGcancelConn</structname> object
6244 is an opaque structure that is not meant to be accessed directly by the
6245 application. This <structname>PGcancelConn</structname> object can be
6246 used to cancel the query that's running on the original connection in a
6247 thread-safe way.
6248 </para>
6250 <para>
6251 Many connection parameters of the original client will be reused when
6252 setting up the connection for the cancel request. Importantly, if the
6253 original connection requires encryption of the connection and/or
6254 verification of the target host (using <literal>sslmode</literal> or
6255 <literal>gssencmode</literal>), then the connection for the cancel
6256 request is made with these same requirements. Any connection options
6257 that are only used during authentication or after authentication of the
6258 client are ignored though, because cancellation requests do not require
6259 authentication and the connection is closed right after the cancellation
6260 request is submitted.
6261 </para>
6263 <para>
6264 Note that when <function>PQcancelCreate</function> returns a non-null
6265 pointer, you must call <xref linkend="libpq-PQcancelFinish"/> when you
6266 are finished with it, in order to dispose of the structure and any
6267 associated memory blocks. This must be done even if the cancel request
6268 failed or was abandoned.
6269 </para>
6270 </listitem>
6271 </varlistentry>
6273 <varlistentry id="libpq-PQcancelBlocking">
6274 <term><function>PQcancelBlocking</function><indexterm><primary>PQcancelBlocking</primary></indexterm></term>
6276 <listitem>
6277 <para>
6278 Requests that the server abandons processing of the current command
6279 in a blocking manner.
6280 <synopsis>
6281 int PQcancelBlocking(PGcancelConn *cancelConn);
6282 </synopsis>
6283 </para>
6285 <para>
6286 The request is made over the given <structname>PGcancelConn</structname>,
6287 which needs to be created with <xref linkend="libpq-PQcancelCreate"/>.
6288 The return value of <xref linkend="libpq-PQcancelBlocking"/>
6289 is 1 if the cancel request was successfully
6290 dispatched and 0 if not. If it was unsuccessful, the error message can be
6291 retrieved using <xref linkend="libpq-PQcancelErrorMessage"/>.
6292 </para>
6294 <para>
6295 Successful dispatch of the cancellation is no guarantee that the request
6296 will have any effect, however. If the cancellation is effective, the
6297 command being canceled will terminate early and return an error result.
6298 If the cancellation fails (say, because the server was already done
6299 processing the command), then there will be no visible result at all.
6300 </para>
6302 </listitem>
6303 </varlistentry>
6305 <varlistentry id="libpq-PQcancelStart">
6306 <term><function>PQcancelStart</function><indexterm><primary>PQcancelStart</primary></indexterm></term>
6307 <term><function>PQcancelPoll</function><indexterm><primary>PQcancelPoll</primary></indexterm></term>
6309 <listitem>
6310 <para>
6311 Requests that the server abandons processing of the current command
6312 in a non-blocking manner.
6313 <synopsis>
6314 int PQcancelStart(PGcancelConn *cancelConn);
6316 PostgresPollingStatusType PQcancelPoll(PGcancelConn *cancelConn);
6317 </synopsis>
6318 </para>
6320 <para>
6321 The request is made over the given <structname>PGcancelConn</structname>,
6322 which needs to be created with <xref linkend="libpq-PQcancelCreate"/>.
6323 The return value of <xref linkend="libpq-PQcancelStart"/>
6324 is 1 if the cancellation request could be started and 0 if not.
6325 If it was unsuccessful, the error message can be
6326 retrieved using <xref linkend="libpq-PQcancelErrorMessage"/>.
6327 </para>
6329 <para>
6330 If <function>PQcancelStart</function> succeeds, the next stage
6331 is to poll <application>libpq</application> so that it can proceed with
6332 the cancel connection sequence.
6333 Use <xref linkend="libpq-PQcancelSocket"/> to obtain the descriptor of the
6334 socket underlying the database connection.
6335 (Caution: do not assume that the socket remains the same
6336 across <function>PQcancelPoll</function> calls.)
6337 Loop thus: If <function>PQcancelPoll(cancelConn)</function> last returned
6338 <symbol>PGRES_POLLING_READING</symbol>, wait until the socket is ready to
6339 read (as indicated by <function>select()</function>,
6340 <function>poll()</function>, or similar system function).
6341 Then call <function>PQcancelPoll(cancelConn)</function> again.
6342 Conversely, if <function>PQcancelPoll(cancelConn)</function> last returned
6343 <symbol>PGRES_POLLING_WRITING</symbol>, wait until the socket is ready
6344 to write, then call <function>PQcancelPoll(cancelConn)</function> again.
6345 On the first iteration, i.e., if you have yet to call
6346 <function>PQcancelPoll(cancelConn)</function>, behave as if it last returned
6347 <symbol>PGRES_POLLING_WRITING</symbol>. Continue this loop until
6348 <function>PQcancelPoll(cancelConn)</function> returns
6349 <symbol>PGRES_POLLING_FAILED</symbol>, indicating the connection procedure
6350 has failed, or <symbol>PGRES_POLLING_OK</symbol>, indicating cancel
6351 request was successfully dispatched.
6352 </para>
6354 <para>
6355 Successful dispatch of the cancellation is no guarantee that the request
6356 will have any effect, however. If the cancellation is effective, the
6357 command being canceled will terminate early and return an error result.
6358 If the cancellation fails (say, because the server was already done
6359 processing the command), then there will be no visible result at all.
6360 </para>
6362 <para>
6363 At any time during connection, the status of the connection can be
6364 checked by calling <xref linkend="libpq-PQcancelStatus"/>.
6365 If this call returns <symbol>CONNECTION_BAD</symbol>, then
6366 the cancel procedure has failed; if the call returns
6367 <function>CONNECTION_OK</function>, then cancel request was
6368 successfully dispatched.
6369 Both of these states are equally detectable from the return value of
6370 <function>PQcancelPoll</function>, described above.
6371 Other states might also occur during (and only during) an asynchronous
6372 connection procedure.
6373 These indicate the current stage of the connection procedure and might
6374 be useful to provide feedback to the user for example.
6375 These statuses are:
6377 <variablelist>
6378 <varlistentry id="libpq-cancel-connection-allocated">
6379 <term><symbol>CONNECTION_ALLOCATED</symbol></term>
6380 <listitem>
6381 <para>
6382 Waiting for a call to <xref linkend="libpq-PQcancelStart"/> or
6383 <xref linkend="libpq-PQcancelBlocking"/>, to actually open the
6384 socket. This is the connection state right after
6385 calling <xref linkend="libpq-PQcancelCreate"/>
6386 or <xref linkend="libpq-PQcancelReset"/>. No connection to the
6387 server has been initiated yet at this point. To actually start
6388 sending the cancel request use <xref linkend="libpq-PQcancelStart"/> or
6389 <xref linkend="libpq-PQcancelBlocking"/>.
6390 </para>
6391 </listitem>
6392 </varlistentry>
6394 <varlistentry id="libpq-cancel-connection-started">
6395 <term><symbol>CONNECTION_STARTED</symbol></term>
6396 <listitem>
6397 <para>
6398 Waiting for connection to be made.
6399 </para>
6400 </listitem>
6401 </varlistentry>
6403 <varlistentry id="libpq-cancel-connection-made">
6404 <term><symbol>CONNECTION_MADE</symbol></term>
6405 <listitem>
6406 <para>
6407 Connection OK; waiting to send.
6408 </para>
6409 </listitem>
6410 </varlistentry>
6412 <varlistentry id="libpq-cancel-connection-awaiting-response">
6413 <term><symbol>CONNECTION_AWAITING_RESPONSE</symbol></term>
6414 <listitem>
6415 <para>
6416 Waiting for a response from the server.
6417 </para>
6418 </listitem>
6419 </varlistentry>
6421 <varlistentry id="libpq-cancel-connection-ssl-startup">
6422 <term><symbol>CONNECTION_SSL_STARTUP</symbol></term>
6423 <listitem>
6424 <para>
6425 Negotiating SSL encryption.
6426 </para>
6427 </listitem>
6428 </varlistentry>
6430 <varlistentry id="libpq-cancel-connection-gss-startup">
6431 <term><symbol>CONNECTION_GSS_STARTUP</symbol></term>
6432 <listitem>
6433 <para>
6434 Negotiating GSS encryption.
6435 </para>
6436 </listitem>
6437 </varlistentry>
6438 </variablelist>
6440 Note that, although these constants will remain (in order to maintain
6441 compatibility), an application should never rely upon these occurring in a
6442 particular order, or at all, or on the status always being one of these
6443 documented values. An application might do something like this:
6444 <programlisting>
6445 switch(PQcancelStatus(conn))
6447 case CONNECTION_STARTED:
6448 feedback = "Connecting...";
6449 break;
6451 case CONNECTION_MADE:
6452 feedback = "Connected to server...";
6453 break;
6457 default:
6458 feedback = "Connecting...";
6460 </programlisting>
6461 </para>
6463 <para>
6464 The <literal>connect_timeout</literal> connection parameter is ignored
6465 when using <function>PQcancelPoll</function>; it is the application's
6466 responsibility to decide whether an excessive amount of time has elapsed.
6467 Otherwise, <function>PQcancelStart</function> followed by a
6468 <function>PQcancelPoll</function> loop is equivalent to
6469 <xref linkend="libpq-PQcancelBlocking"/>.
6470 </para>
6472 </listitem>
6473 </varlistentry>
6475 <varlistentry id="libpq-PQcancelStatus">
6476 <term><function>PQcancelStatus</function><indexterm><primary>PQcancelStatus</primary></indexterm></term>
6478 <listitem>
6479 <para>
6480 Returns the status of the cancel connection.
6481 <synopsis>
6482 ConnStatusType PQcancelStatus(const PGcancelConn *cancelConn);
6483 </synopsis>
6484 </para>
6486 <para>
6487 The status can be one of a number of values. However, only three of
6488 these are seen outside of an asynchronous cancel procedure:
6489 <literal>CONNECTION_ALLOCATED</literal>,
6490 <literal>CONNECTION_OK</literal> and
6491 <literal>CONNECTION_BAD</literal>. The initial state of a
6492 <function>PGcancelConn</function> that's successfully created using
6493 <xref linkend="libpq-PQcancelCreate"/> is <literal>CONNECTION_ALLOCATED</literal>.
6494 A cancel request that was successfully dispatched
6495 has the status <literal>CONNECTION_OK</literal>. A failed
6496 cancel attempt is signaled by status
6497 <literal>CONNECTION_BAD</literal>. An OK status will
6498 remain so until <xref linkend="libpq-PQcancelFinish"/> or
6499 <xref linkend="libpq-PQcancelReset"/> is called.
6500 </para>
6502 <para>
6503 See the entry for <xref linkend="libpq-PQcancelStart"/> with regards
6504 to other status codes that might be returned.
6505 </para>
6507 <para>
6508 Successful dispatch of the cancellation is no guarantee that the request
6509 will have any effect, however. If the cancellation is effective, the
6510 command being canceled will terminate early and return an error result.
6511 If the cancellation fails (say, because the server was already done
6512 processing the command), then there will be no visible result at all.
6513 </para>
6515 </listitem>
6516 </varlistentry>
6518 <varlistentry id="libpq-PQcancelSocket">
6519 <term><function>PQcancelSocket</function><indexterm><primary>PQcancelSocket</primary></indexterm></term>
6521 <listitem>
6522 <para>
6523 Obtains the file descriptor number of the cancel connection socket to
6524 the server.
6525 <synopsis>
6526 int PQcancelSocket(const PGcancelConn *cancelConn);
6527 </synopsis>
6528 </para>
6530 <para>
6531 A valid descriptor will be greater than or equal to 0;
6532 a result of -1 indicates that no server connection is currently open.
6533 This might change as a result of calling any of the functions
6534 in this section on the <structname>PGcancelConn</structname>
6535 (except for <xref linkend="libpq-PQcancelErrorMessage"/> and
6536 <function>PQcancelSocket</function> itself).
6537 </para>
6538 </listitem>
6539 </varlistentry>
6541 <varlistentry id="libpq-PQcancelErrorMessage">
6542 <term>
6543 <function>PQcancelErrorMessage</function><indexterm><primary>PQcancelErrorMessage</primary></indexterm>
6544 <indexterm><primary>error message</primary><secondary>in <structname>PGcancelConn</structname></secondary></indexterm>
6545 </term>
6547 <listitem>
6548 <para>
6549 Returns the error message most recently generated by an
6550 operation on the cancel connection.
6551 <synopsis>
6552 char *PQcancelErrorMessage(const PGcancelConn *cancelconn);
6553 </synopsis>
6554 </para>
6556 <para>
6557 Nearly all <application>libpq</application> functions that take a
6558 <structname>PGcancelConn</structname> will set a message for
6559 <xref linkend="libpq-PQcancelErrorMessage"/> if they fail.
6560 Note that by <application>libpq</application> convention,
6561 a nonempty <xref linkend="libpq-PQcancelErrorMessage"/> result
6562 can consist of multiple lines, and will include a trailing newline.
6563 The caller should not free the result directly.
6564 It will be freed when the associated
6565 <structname>PGcancelConn</structname> handle is passed to
6566 <xref linkend="libpq-PQcancelFinish"/>. The result string should not be
6567 expected to remain the same across operations on the
6568 <literal>PGcancelConn</literal> structure.
6569 </para>
6570 </listitem>
6571 </varlistentry>
6573 <varlistentry id="libpq-PQcancelFinish">
6574 <term><function>PQcancelFinish</function><indexterm><primary>PQcancelFinish</primary></indexterm></term>
6575 <listitem>
6576 <para>
6577 Closes the cancel connection (if it did not finish sending the
6578 cancel request yet). Also frees memory used by the
6579 <structname>PGcancelConn</structname> object.
6580 <synopsis>
6581 void PQcancelFinish(PGcancelConn *cancelConn);
6582 </synopsis>
6583 </para>
6585 <para>
6586 Note that even if the cancel attempt fails (as
6587 indicated by <xref linkend="libpq-PQcancelStatus"/>), the
6588 application should call <xref linkend="libpq-PQcancelFinish"/>
6589 to free the memory used by the <structname>PGcancelConn</structname>
6590 object.
6591 The <structname>PGcancelConn</structname> pointer must not be used
6592 again after <xref linkend="libpq-PQcancelFinish"/> has been called.
6593 </para>
6594 </listitem>
6595 </varlistentry>
6597 <varlistentry id="libpq-PQcancelReset">
6598 <term><function>PQcancelReset</function><indexterm><primary>PQcancelReset</primary></indexterm></term>
6599 <listitem>
6600 <para>
6601 Resets the <symbol>PGcancelConn</symbol> so it can be reused for a new
6602 cancel connection.
6603 <synopsis>
6604 void PQcancelReset(PGcancelConn *cancelConn);
6605 </synopsis>
6606 </para>
6608 <para>
6609 If the <symbol>PGcancelConn</symbol> is currently used to send a cancel
6610 request, then this connection is closed. It will then prepare the
6611 <symbol>PGcancelConn</symbol> object such that it can be used to send a
6612 new cancel request.
6613 </para>
6615 <para>
6616 This can be used to create one <structname>PGcancelConn</structname>
6617 for a <structname>PGconn</structname> and reuse it multiple times
6618 throughout the lifetime of the original <structname>PGconn</structname>.
6619 </para>
6620 </listitem>
6621 </varlistentry>
6622 </variablelist>
6623 </sect2>
6625 <sect2 id="libpq-cancel-deprecated">
6626 <title>Obsolete Functions for Sending Cancel Requests</title>
6628 <para>
6629 These functions represent older methods of sending cancel requests.
6630 Although they still work, they are deprecated due to not sending the cancel
6631 requests in an encrypted manner, even when the original connection
6632 specified <literal>sslmode</literal> or <literal>gssencmode</literal> to
6633 require encryption. Thus these older methods are heavily discouraged from
6634 being used in new code, and it is recommended to change existing code to
6635 use the new functions instead.
6636 </para>
6638 <variablelist>
6639 <varlistentry id="libpq-PQgetCancel">
6640 <term><function>PQgetCancel</function><indexterm><primary>PQgetCancel</primary></indexterm></term>
6642 <listitem>
6643 <para>
6644 Creates a data structure containing the information needed to cancel
6645 a command using <xref linkend="libpq-PQcancel"/>.
6646 <synopsis>
6647 PGcancel *PQgetCancel(PGconn *conn);
6648 </synopsis>
6649 </para>
6651 <para>
6652 <xref linkend="libpq-PQgetCancel"/> creates a
6653 <structname>PGcancel</structname><indexterm><primary>PGcancel</primary></indexterm>
6654 object given a <structname>PGconn</structname> connection object.
6655 It will return <symbol>NULL</symbol> if the given <parameter>conn</parameter>
6656 is <symbol>NULL</symbol> or an invalid connection.
6657 The <structname>PGcancel</structname> object is an opaque
6658 structure that is not meant to be accessed directly by the
6659 application; it can only be passed to <xref linkend="libpq-PQcancel"/>
6660 or <xref linkend="libpq-PQfreeCancel"/>.
6661 </para>
6662 </listitem>
6663 </varlistentry>
6665 <varlistentry id="libpq-PQfreeCancel">
6666 <term><function>PQfreeCancel</function><indexterm><primary>PQfreeCancel</primary></indexterm></term>
6668 <listitem>
6669 <para>
6670 Frees a data structure created by <xref linkend="libpq-PQgetCancel"/>.
6671 <synopsis>
6672 void PQfreeCancel(PGcancel *cancel);
6673 </synopsis>
6674 </para>
6676 <para>
6677 <xref linkend="libpq-PQfreeCancel"/> frees a data object previously created
6678 by <xref linkend="libpq-PQgetCancel"/>.
6679 </para>
6680 </listitem>
6681 </varlistentry>
6683 <varlistentry id="libpq-PQcancel">
6684 <term><function>PQcancel</function><indexterm><primary>PQcancel</primary></indexterm></term>
6686 <listitem>
6687 <para>
6688 <xref linkend="libpq-PQcancel"/> is a deprecated and insecure
6689 variant of <xref linkend="libpq-PQcancelBlocking"/>, but one that can be
6690 used safely from within a signal handler.
6691 <synopsis>
6692 int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize);
6693 </synopsis>
6694 </para>
6696 <para>
6697 <xref linkend="libpq-PQcancel"/> only exists because of backwards
6698 compatibility reasons. <xref linkend="libpq-PQcancelBlocking"/> should be
6699 used instead. The only benefit that <xref linkend="libpq-PQcancel"/> has
6700 is that it can be safely invoked from a signal handler, if the
6701 <parameter>errbuf</parameter> is a local variable in the signal handler.
6702 However, this is generally not considered a big enough benefit to be
6703 worth the security issues that this function has.
6704 </para>
6706 <para>
6707 The <structname>PGcancel</structname> object is read-only as far as
6708 <xref linkend="libpq-PQcancel"/> is concerned, so it can also be invoked
6709 from a thread that is separate from the one manipulating the
6710 <structname>PGconn</structname> object.
6711 </para>
6713 <para>
6714 The return value of <xref linkend="libpq-PQcancel"/> is 1 if the
6715 cancel request was successfully dispatched and 0 if not.
6716 If not, <parameter>errbuf</parameter> is filled with an explanatory
6717 error message.
6718 <parameter>errbuf</parameter> must be a char array of size
6719 <parameter>errbufsize</parameter> (the recommended size is 256 bytes).
6720 </para>
6721 </listitem>
6722 </varlistentry>
6723 </variablelist>
6725 <variablelist>
6726 <varlistentry id="libpq-PQrequestCancel">
6727 <term><function>PQrequestCancel</function><indexterm><primary>PQrequestCancel</primary></indexterm></term>
6729 <listitem>
6730 <para>
6731 <xref linkend="libpq-PQrequestCancel"/> is a deprecated and insecure
6732 variant of <xref linkend="libpq-PQcancelBlocking"/>.
6733 <synopsis>
6734 int PQrequestCancel(PGconn *conn);
6735 </synopsis>
6736 </para>
6738 <para>
6739 <xref linkend="libpq-PQrequestCancel"/> only exists because of backwards
6740 compatibility reasons. <xref linkend="libpq-PQcancelBlocking"/> should be
6741 used instead. There is no benefit to using
6742 <xref linkend="libpq-PQrequestCancel"/> over
6743 <xref linkend="libpq-PQcancelBlocking"/>.
6744 </para>
6746 <para>
6747 Requests that the server abandon processing of the current
6748 command. It operates directly on the
6749 <structname>PGconn</structname> object, and in case of failure stores the
6750 error message in the <structname>PGconn</structname> object (whence it can
6751 be retrieved by <xref linkend="libpq-PQerrorMessage"/>). Although
6752 the functionality is the same, this approach is not safe within
6753 multiple-thread programs or signal handlers, since it is possible
6754 that overwriting the <structname>PGconn</structname>'s error message will
6755 mess up the operation currently in progress on the connection.
6756 </para>
6757 </listitem>
6758 </varlistentry>
6759 </variablelist>
6760 </sect2>
6761 </sect1>
6763 <sect1 id="libpq-fastpath">
6764 <title>The Fast-Path Interface</title>
6766 <indexterm zone="libpq-fastpath">
6767 <primary>fast path</primary>
6768 </indexterm>
6770 <para>
6771 <productname>PostgreSQL</productname> provides a fast-path interface
6772 to send simple function calls to the server.
6773 </para>
6775 <tip>
6776 <para>
6777 This interface is somewhat obsolete, as one can achieve similar
6778 performance and greater functionality by setting up a prepared
6779 statement to define the function call. Then, executing the statement
6780 with binary transmission of parameters and results substitutes for a
6781 fast-path function call.
6782 </para>
6783 </tip>
6785 <para>
6786 The function <function id="libpq-PQfn">PQfn</function><indexterm><primary>PQfn</primary></indexterm>
6787 requests execution of a server function via the fast-path interface:
6788 <synopsis>
6789 PGresult *PQfn(PGconn *conn,
6790 int fnid,
6791 int *result_buf,
6792 int *result_len,
6793 int result_is_int,
6794 const PQArgBlock *args,
6795 int nargs);
6797 typedef struct
6799 int len;
6800 int isint;
6801 union
6803 int *ptr;
6804 int integer;
6805 } u;
6806 } PQArgBlock;
6807 </synopsis>
6808 </para>
6810 <para>
6811 The <parameter>fnid</parameter> argument is the OID of the function to be
6812 executed. <parameter>args</parameter> and <parameter>nargs</parameter> define the
6813 parameters to be passed to the function; they must match the declared
6814 function argument list. When the <parameter>isint</parameter> field of a
6815 parameter structure is true, the <parameter>u.integer</parameter> value is sent
6816 to the server as an integer of the indicated length (this must be
6817 2 or 4 bytes); proper byte-swapping occurs. When <parameter>isint</parameter>
6818 is false, the indicated number of bytes at <parameter>*u.ptr</parameter> are
6819 sent with no processing; the data must be in the format expected by
6820 the server for binary transmission of the function's argument data
6821 type. (The declaration of <parameter>u.ptr</parameter> as being of
6822 type <type>int *</type> is historical; it would be better to consider
6823 it <type>void *</type>.)
6824 <parameter>result_buf</parameter> points to the buffer in which to place
6825 the function's return value. The caller must have allocated sufficient
6826 space to store the return value. (There is no check!) The actual result
6827 length in bytes will be returned in the integer pointed to by
6828 <parameter>result_len</parameter>. If a 2- or 4-byte integer result
6829 is expected, set <parameter>result_is_int</parameter> to 1, otherwise
6830 set it to 0. Setting <parameter>result_is_int</parameter> to 1 causes
6831 <application>libpq</application> to byte-swap the value if necessary, so that it
6832 is delivered as a proper <type>int</type> value for the client machine;
6833 note that a 4-byte integer is delivered into <parameter>*result_buf</parameter>
6834 for either allowed result size.
6835 When <parameter>result_is_int</parameter> is 0, the binary-format byte string
6836 sent by the server is returned unmodified. (In this case it's better
6837 to consider <parameter>result_buf</parameter> as being of
6838 type <type>void *</type>.)
6839 </para>
6841 <para>
6842 <function>PQfn</function> always returns a valid
6843 <structname>PGresult</structname> pointer, with
6844 status <literal>PGRES_COMMAND_OK</literal> for success
6845 or <literal>PGRES_FATAL_ERROR</literal> if some problem was encountered.
6846 The result status should be
6847 checked before the result is used. The caller is responsible for
6848 freeing the <structname>PGresult</structname> with
6849 <xref linkend="libpq-PQclear"/> when it is no longer needed.
6850 </para>
6852 <para>
6853 To pass a NULL argument to the function, set
6854 the <parameter>len</parameter> field of that parameter structure
6855 to <literal>-1</literal>; the <parameter>isint</parameter>
6856 and <parameter>u</parameter> fields are then irrelevant.
6857 </para>
6859 <para>
6860 If the function returns NULL, <parameter>*result_len</parameter> is set
6861 to <literal>-1</literal>, and <parameter>*result_buf</parameter> is not
6862 modified.
6863 </para>
6865 <para>
6866 Note that it is not possible to handle set-valued results when using
6867 this interface. Also, the function must be a plain function, not an
6868 aggregate, window function, or procedure.
6869 </para>
6871 </sect1>
6873 <sect1 id="libpq-notify">
6874 <title>Asynchronous Notification</title>
6876 <indexterm zone="libpq-notify">
6877 <primary>NOTIFY</primary>
6878 <secondary>in libpq</secondary>
6879 </indexterm>
6881 <para>
6882 <productname>PostgreSQL</productname> offers asynchronous notification
6883 via the <command>LISTEN</command> and <command>NOTIFY</command>
6884 commands. A client session registers its interest in a particular
6885 notification channel with the <command>LISTEN</command> command (and
6886 can stop listening with the <command>UNLISTEN</command> command). All
6887 sessions listening on a particular channel will be notified
6888 asynchronously when a <command>NOTIFY</command> command with that
6889 channel name is executed by any session. A <quote>payload</quote> string can
6890 be passed to communicate additional data to the listeners.
6891 </para>
6893 <para>
6894 <application>libpq</application> applications submit
6895 <command>LISTEN</command>, <command>UNLISTEN</command>,
6896 and <command>NOTIFY</command> commands as
6897 ordinary SQL commands. The arrival of <command>NOTIFY</command>
6898 messages can subsequently be detected by calling
6899 <function id="libpq-PQnotifies">PQnotifies</function>.<indexterm><primary>PQnotifies</primary></indexterm>
6900 </para>
6902 <para>
6903 The function <function>PQnotifies</function> returns the next notification
6904 from a list of unhandled notification messages received from the server.
6905 It returns a null pointer if there are no pending notifications. Once a
6906 notification is returned from <function>PQnotifies</function>, it is considered
6907 handled and will be removed from the list of notifications.
6909 <synopsis>
6910 PGnotify *PQnotifies(PGconn *conn);
6912 typedef struct pgNotify
6914 char *relname; /* notification channel name */
6915 int be_pid; /* process ID of notifying server process */
6916 char *extra; /* notification payload string */
6917 } PGnotify;
6918 </synopsis>
6920 After processing a <structname>PGnotify</structname> object returned
6921 by <function>PQnotifies</function>, be sure to free it with
6922 <xref linkend="libpq-PQfreemem"/>. It is sufficient to free the
6923 <structname>PGnotify</structname> pointer; the
6924 <structfield>relname</structfield> and <structfield>extra</structfield>
6925 fields do not represent separate allocations. (The names of these fields
6926 are historical; in particular, channel names need not have anything to
6927 do with relation names.)
6928 </para>
6930 <para>
6931 <xref linkend="libpq-example-2"/> gives a sample program that illustrates
6932 the use of asynchronous notification.
6933 </para>
6935 <para>
6936 <function>PQnotifies</function> does not actually read data from the
6937 server; it just returns messages previously absorbed by another
6938 <application>libpq</application> function. In ancient releases of
6939 <application>libpq</application>, the only way to ensure timely receipt
6940 of <command>NOTIFY</command> messages was to constantly submit commands, even
6941 empty ones, and then check <function>PQnotifies</function> after each
6942 <xref linkend="libpq-PQexec"/>. While this still works, it is deprecated
6943 as a waste of processing power.
6944 </para>
6946 <para>
6947 A better way to check for <command>NOTIFY</command> messages when you have no
6948 useful commands to execute is to call
6949 <xref linkend="libpq-PQconsumeInput"/>, then check
6950 <function>PQnotifies</function>. You can use
6951 <function>select()</function> to wait for data to arrive from the
6952 server, thereby using no <acronym>CPU</acronym> power unless there is
6953 something to do. (See <xref linkend="libpq-PQsocket"/> to obtain the file
6954 descriptor number to use with <function>select()</function>.) Note that
6955 this will work OK whether you submit commands with
6956 <xref linkend="libpq-PQsendQuery"/>/<xref linkend="libpq-PQgetResult"/> or
6957 simply use <xref linkend="libpq-PQexec"/>. You should, however, remember
6958 to check <function>PQnotifies</function> after each
6959 <xref linkend="libpq-PQgetResult"/> or <xref linkend="libpq-PQexec"/>, to
6960 see if any notifications came in during the processing of the command.
6961 </para>
6963 </sect1>
6965 <sect1 id="libpq-copy">
6966 <title>Functions Associated with the <command>COPY</command> Command</title>
6968 <indexterm zone="libpq-copy">
6969 <primary>COPY</primary>
6970 <secondary>with libpq</secondary>
6971 </indexterm>
6973 <para>
6974 The <command>COPY</command> command in
6975 <productname>PostgreSQL</productname> has options to read from or write
6976 to the network connection used by <application>libpq</application>.
6977 The functions described in this section allow applications to take
6978 advantage of this capability by supplying or consuming copied data.
6979 </para>
6981 <para>
6982 The overall process is that the application first issues the SQL
6983 <command>COPY</command> command via <xref linkend="libpq-PQexec"/> or one
6984 of the equivalent functions. The response to this (if there is no
6985 error in the command) will be a <structname>PGresult</structname> object bearing
6986 a status code of <literal>PGRES_COPY_OUT</literal> or
6987 <literal>PGRES_COPY_IN</literal> (depending on the specified copy
6988 direction). The application should then use the functions of this
6989 section to receive or transmit data rows. When the data transfer is
6990 complete, another <structname>PGresult</structname> object is returned to indicate
6991 success or failure of the transfer. Its status will be
6992 <literal>PGRES_COMMAND_OK</literal> for success or
6993 <literal>PGRES_FATAL_ERROR</literal> if some problem was encountered.
6994 At this point further SQL commands can be issued via
6995 <xref linkend="libpq-PQexec"/>. (It is not possible to execute other SQL
6996 commands using the same connection while the <command>COPY</command>
6997 operation is in progress.)
6998 </para>
7000 <para>
7001 If a <command>COPY</command> command is issued via
7002 <xref linkend="libpq-PQexec"/> in a string that could contain additional
7003 commands, the application must continue fetching results via
7004 <xref linkend="libpq-PQgetResult"/> after completing the <command>COPY</command>
7005 sequence. Only when <xref linkend="libpq-PQgetResult"/> returns
7006 <symbol>NULL</symbol> is it certain that the <xref linkend="libpq-PQexec"/>
7007 command string is done and it is safe to issue more commands.
7008 </para>
7010 <para>
7011 The functions of this section should be executed only after obtaining
7012 a result status of <literal>PGRES_COPY_OUT</literal> or
7013 <literal>PGRES_COPY_IN</literal> from <xref linkend="libpq-PQexec"/> or
7014 <xref linkend="libpq-PQgetResult"/>.
7015 </para>
7017 <para>
7018 A <structname>PGresult</structname> object bearing one of these status values
7019 carries some additional data about the <command>COPY</command> operation
7020 that is starting. This additional data is available using functions
7021 that are also used in connection with query results:
7023 <variablelist>
7024 <varlistentry id="libpq-PQnfields-1">
7025 <term><function>PQnfields</function><indexterm
7026 ><primary>PQnfields</primary><secondary>with COPY</secondary></indexterm></term>
7028 <listitem>
7029 <para>
7030 Returns the number of columns (fields) to be copied.
7031 </para>
7032 </listitem>
7033 </varlistentry>
7035 <varlistentry id="libpq-PQbinaryTuples-1">
7036 <term><function>PQbinaryTuples</function><indexterm
7037 ><primary>PQbinaryTuples</primary><secondary>with COPY</secondary></indexterm></term>
7039 <listitem>
7040 <para>
7041 0 indicates the overall copy format is textual (rows separated by
7042 newlines, columns separated by separator characters, etc.). 1
7043 indicates the overall copy format is binary. See <xref
7044 linkend="sql-copy"/> for more information.
7045 </para>
7046 </listitem>
7047 </varlistentry>
7049 <varlistentry id="libpq-PQfformat-1">
7050 <term><function>PQfformat</function><indexterm
7051 ><primary>PQfformat</primary><secondary>with COPY</secondary></indexterm></term>
7053 <listitem>
7054 <para>
7055 Returns the format code (0 for text, 1 for binary) associated with
7056 each column of the copy operation. The per-column format codes
7057 will always be zero when the overall copy format is textual, but
7058 the binary format can support both text and binary columns.
7059 (However, as of the current implementation of <command>COPY</command>,
7060 only binary columns appear in a binary copy; so the per-column
7061 formats always match the overall format at present.)
7062 </para>
7063 </listitem>
7064 </varlistentry>
7065 </variablelist>
7066 </para>
7068 <sect2 id="libpq-copy-send">
7069 <title>Functions for Sending <command>COPY</command> Data</title>
7071 <para>
7072 These functions are used to send data during <literal>COPY FROM
7073 STDIN</literal>. They will fail if called when the connection is not in
7074 <literal>COPY_IN</literal> state.
7075 </para>
7077 <variablelist>
7078 <varlistentry id="libpq-PQputCopyData">
7079 <term><function>PQputCopyData</function><indexterm><primary>PQputCopyData</primary></indexterm></term>
7081 <listitem>
7082 <para>
7083 Sends data to the server during <literal>COPY_IN</literal> state.
7084 <synopsis>
7085 int PQputCopyData(PGconn *conn,
7086 const char *buffer,
7087 int nbytes);
7088 </synopsis>
7089 </para>
7091 <para>
7092 Transmits the <command>COPY</command> data in the specified
7093 <parameter>buffer</parameter>, of length <parameter>nbytes</parameter>, to the server.
7094 The result is 1 if the data was queued, zero if it was not queued
7095 because of full buffers (this will only happen in nonblocking mode),
7096 or -1 if an error occurred.
7097 (Use <xref linkend="libpq-PQerrorMessage"/> to retrieve details if
7098 the return value is -1. If the value is zero, wait for write-ready
7099 and try again.)
7100 </para>
7102 <para>
7103 The application can divide the <command>COPY</command> data stream
7104 into buffer loads of any convenient size. Buffer-load boundaries
7105 have no semantic significance when sending. The contents of the
7106 data stream must match the data format expected by the
7107 <command>COPY</command> command; see <xref linkend="sql-copy"/> for details.
7108 </para>
7109 </listitem>
7110 </varlistentry>
7112 <varlistentry id="libpq-PQputCopyEnd">
7113 <term><function>PQputCopyEnd</function><indexterm><primary>PQputCopyEnd</primary></indexterm></term>
7115 <listitem>
7116 <para>
7117 Sends end-of-data indication to the server during <literal>COPY_IN</literal> state.
7118 <synopsis>
7119 int PQputCopyEnd(PGconn *conn,
7120 const char *errormsg);
7121 </synopsis>
7122 </para>
7124 <para>
7125 Ends the <literal>COPY_IN</literal> operation successfully if
7126 <parameter>errormsg</parameter> is <symbol>NULL</symbol>. If
7127 <parameter>errormsg</parameter> is not <symbol>NULL</symbol> then the
7128 <command>COPY</command> is forced to fail, with the string pointed to by
7129 <parameter>errormsg</parameter> used as the error message. (One should not
7130 assume that this exact error message will come back from the server,
7131 however, as the server might have already failed the
7132 <command>COPY</command> for its own reasons.)
7133 </para>
7135 <para>
7136 The result is 1 if the termination message was sent; or in
7137 nonblocking mode, this may only indicate that the termination
7138 message was successfully queued. (In nonblocking mode, to be
7139 certain that the data has been sent, you should next wait for
7140 write-ready and call <xref linkend="libpq-PQflush"/>, repeating until it
7141 returns zero.) Zero indicates that the function could not queue
7142 the termination message because of full buffers; this will only
7143 happen in nonblocking mode. (In this case, wait for
7144 write-ready and try the <xref linkend="libpq-PQputCopyEnd"/> call
7145 again.) If a hard error occurs, -1 is returned; you can use
7146 <xref linkend="libpq-PQerrorMessage"/> to retrieve details.
7147 </para>
7149 <para>
7150 After successfully calling <xref linkend="libpq-PQputCopyEnd"/>, call
7151 <xref linkend="libpq-PQgetResult"/> to obtain the final result status of the
7152 <command>COPY</command> command. One can wait for this result to be
7153 available in the usual way. Then return to normal operation.
7154 </para>
7155 </listitem>
7156 </varlistentry>
7157 </variablelist>
7159 </sect2>
7161 <sect2 id="libpq-copy-receive">
7162 <title>Functions for Receiving <command>COPY</command> Data</title>
7164 <para>
7165 These functions are used to receive data during <literal>COPY TO
7166 STDOUT</literal>. They will fail if called when the connection is not in
7167 <literal>COPY_OUT</literal> state.
7168 </para>
7170 <variablelist>
7171 <varlistentry id="libpq-PQgetCopyData">
7172 <term><function>PQgetCopyData</function><indexterm><primary>PQgetCopyData</primary></indexterm></term>
7174 <listitem>
7175 <para>
7176 Receives data from the server during <literal>COPY_OUT</literal> state.
7177 <synopsis>
7178 int PQgetCopyData(PGconn *conn,
7179 char **buffer,
7180 int async);
7181 </synopsis>
7182 </para>
7184 <para>
7185 Attempts to obtain another row of data from the server during a
7186 <command>COPY</command>. Data is always returned one data row at
7187 a time; if only a partial row is available, it is not returned.
7188 Successful return of a data row involves allocating a chunk of
7189 memory to hold the data. The <parameter>buffer</parameter> parameter must
7190 be non-<symbol>NULL</symbol>. <parameter>*buffer</parameter> is set to
7191 point to the allocated memory, or to <symbol>NULL</symbol> in cases
7192 where no buffer is returned. A non-<symbol>NULL</symbol> result
7193 buffer should be freed using <xref linkend="libpq-PQfreemem"/> when no longer
7194 needed.
7195 </para>
7197 <para>
7198 When a row is successfully returned, the return value is the number
7199 of data bytes in the row (this will always be greater than zero).
7200 The returned string is always null-terminated, though this is
7201 probably only useful for textual <command>COPY</command>. A result
7202 of zero indicates that the <command>COPY</command> is still in
7203 progress, but no row is yet available (this is only possible when
7204 <parameter>async</parameter> is true). A result of -1 indicates that the
7205 <command>COPY</command> is done. A result of -2 indicates that an
7206 error occurred (consult <xref linkend="libpq-PQerrorMessage"/> for the reason).
7207 </para>
7209 <para>
7210 When <parameter>async</parameter> is true (not zero),
7211 <xref linkend="libpq-PQgetCopyData"/> will not block waiting for input; it
7212 will return zero if the <command>COPY</command> is still in progress
7213 but no complete row is available. (In this case wait for read-ready
7214 and then call <xref linkend="libpq-PQconsumeInput"/> before calling
7215 <xref linkend="libpq-PQgetCopyData"/> again.) When <parameter>async</parameter> is
7216 false (zero), <xref linkend="libpq-PQgetCopyData"/> will block until data is
7217 available or the operation completes.
7218 </para>
7220 <para>
7221 After <xref linkend="libpq-PQgetCopyData"/> returns -1, call
7222 <xref linkend="libpq-PQgetResult"/> to obtain the final result status of the
7223 <command>COPY</command> command. One can wait for this result to be
7224 available in the usual way. Then return to normal operation.
7225 </para>
7226 </listitem>
7227 </varlistentry>
7228 </variablelist>
7230 </sect2>
7232 <sect2 id="libpq-copy-deprecated">
7233 <title>Obsolete Functions for <command>COPY</command></title>
7235 <para>
7236 These functions represent older methods of handling <command>COPY</command>.
7237 Although they still work, they are deprecated due to poor error handling,
7238 inconvenient methods of detecting end-of-data, and lack of support for binary
7239 or nonblocking transfers.
7240 </para>
7242 <variablelist>
7243 <varlistentry id="libpq-PQgetline">
7244 <term><function>PQgetline</function><indexterm><primary>PQgetline</primary></indexterm></term>
7246 <listitem>
7247 <para>
7248 Reads a newline-terminated line of characters (transmitted
7249 by the server) into a buffer string of size <parameter>length</parameter>.
7250 <synopsis>
7251 int PQgetline(PGconn *conn,
7252 char *buffer,
7253 int length);
7254 </synopsis>
7255 </para>
7257 <para>
7258 This function copies up to <parameter>length</parameter>-1 characters into
7259 the buffer and converts the terminating newline into a zero byte.
7260 <xref linkend="libpq-PQgetline"/> returns <symbol>EOF</symbol> at the
7261 end of input, 0 if the entire line has been read, and 1 if the
7262 buffer is full but the terminating newline has not yet been read.
7263 </para>
7264 <para>
7265 Note that the application must check to see if a new line consists
7266 of the two characters <literal>\.</literal>, which indicates
7267 that the server has finished sending the results of the
7268 <command>COPY</command> command. If the application might receive
7269 lines that are more than <parameter>length</parameter>-1 characters long,
7270 care is needed to be sure it recognizes the <literal>\.</literal>
7271 line correctly (and does not, for example, mistake the end of a
7272 long data line for a terminator line).
7273 </para>
7274 </listitem>
7275 </varlistentry>
7277 <varlistentry id="libpq-PQgetlineAsync">
7278 <term><function>PQgetlineAsync</function><indexterm><primary>PQgetlineAsync</primary></indexterm></term>
7280 <listitem>
7281 <para>
7282 Reads a row of <command>COPY</command> data (transmitted by the
7283 server) into a buffer without blocking.
7284 <synopsis>
7285 int PQgetlineAsync(PGconn *conn,
7286 char *buffer,
7287 int bufsize);
7288 </synopsis>
7289 </para>
7291 <para>
7292 This function is similar to <xref linkend="libpq-PQgetline"/>, but it can be used
7293 by applications
7294 that must read <command>COPY</command> data asynchronously, that is, without blocking.
7295 Having issued the <command>COPY</command> command and gotten a <literal>PGRES_COPY_OUT</literal>
7296 response, the
7297 application should call <xref linkend="libpq-PQconsumeInput"/> and
7298 <xref linkend="libpq-PQgetlineAsync"/> until the
7299 end-of-data signal is detected.
7300 </para>
7301 <para>
7302 Unlike <xref linkend="libpq-PQgetline"/>, this function takes
7303 responsibility for detecting end-of-data.
7304 </para>
7306 <para>
7307 On each call, <xref linkend="libpq-PQgetlineAsync"/> will return data if a
7308 complete data row is available in <application>libpq</application>'s input buffer.
7309 Otherwise, no data is returned until the rest of the row arrives.
7310 The function returns -1 if the end-of-copy-data marker has been recognized,
7311 or 0 if no data is available, or a positive number giving the number of
7312 bytes of data returned. If -1 is returned, the caller must next call
7313 <xref linkend="libpq-PQendcopy"/>, and then return to normal processing.
7314 </para>
7316 <para>
7317 The data returned will not extend beyond a data-row boundary. If possible
7318 a whole row will be returned at one time. But if the buffer offered by
7319 the caller is too small to hold a row sent by the server, then a partial
7320 data row will be returned. With textual data this can be detected by testing
7321 whether the last returned byte is <literal>\n</literal> or not. (In a binary
7322 <command>COPY</command>, actual parsing of the <command>COPY</command> data format will be needed to make the
7323 equivalent determination.)
7324 The returned string is not null-terminated. (If you want to add a
7325 terminating null, be sure to pass a <parameter>bufsize</parameter> one smaller
7326 than the room actually available.)
7327 </para>
7328 </listitem>
7329 </varlistentry>
7331 <varlistentry id="libpq-PQputline">
7332 <term><function>PQputline</function><indexterm><primary>PQputline</primary></indexterm></term>
7334 <listitem>
7335 <para>
7336 Sends a null-terminated string to the server. Returns 0 if
7337 OK and <symbol>EOF</symbol> if unable to send the string.
7338 <synopsis>
7339 int PQputline(PGconn *conn,
7340 const char *string);
7341 </synopsis>
7342 </para>
7344 <para>
7345 The <command>COPY</command> data stream sent by a series of calls
7346 to <xref linkend="libpq-PQputline"/> has the same format as that
7347 returned by <xref linkend="libpq-PQgetlineAsync"/>, except that
7348 applications are not obliged to send exactly one data row per
7349 <xref linkend="libpq-PQputline"/> call; it is okay to send a partial
7350 line or multiple lines per call.
7351 </para>
7353 <note>
7354 <para>
7355 Before <productname>PostgreSQL</productname> protocol 3.0, it was necessary
7356 for the application to explicitly send the two characters
7357 <literal>\.</literal> as a final line to indicate to the server that it had
7358 finished sending <command>COPY</command> data. While this still works, it is deprecated and the
7359 special meaning of <literal>\.</literal> can be expected to be removed in a
7360 future release. It is sufficient to call <xref linkend="libpq-PQendcopy"/> after
7361 having sent the actual data.
7362 </para>
7363 </note>
7364 </listitem>
7365 </varlistentry>
7367 <varlistentry id="libpq-PQputnbytes">
7368 <term><function>PQputnbytes</function><indexterm><primary>PQputnbytes</primary></indexterm></term>
7370 <listitem>
7371 <para>
7372 Sends a non-null-terminated string to the server. Returns
7373 0 if OK and <symbol>EOF</symbol> if unable to send the string.
7374 <synopsis>
7375 int PQputnbytes(PGconn *conn,
7376 const char *buffer,
7377 int nbytes);
7378 </synopsis>
7379 </para>
7381 <para>
7382 This is exactly like <xref linkend="libpq-PQputline"/>, except that the data
7383 buffer need not be null-terminated since the number of bytes to send is
7384 specified directly. Use this procedure when sending binary data.
7385 </para>
7386 </listitem>
7387 </varlistentry>
7389 <varlistentry id="libpq-PQendcopy">
7390 <term><function>PQendcopy</function><indexterm><primary>PQendcopy</primary></indexterm></term>
7392 <listitem>
7393 <para>
7394 Synchronizes with the server.
7395 <synopsis>
7396 int PQendcopy(PGconn *conn);
7397 </synopsis>
7398 This function waits until the server has finished the copying.
7399 It should either be issued when the last string has been sent
7400 to the server using <xref linkend="libpq-PQputline"/> or when the
7401 last string has been received from the server using
7402 <function>PQgetline</function>. It must be issued or the server
7403 will get <quote>out of sync</quote> with the client. Upon return
7404 from this function, the server is ready to receive the next SQL
7405 command. The return value is 0 on successful completion,
7406 nonzero otherwise. (Use <xref linkend="libpq-PQerrorMessage"/> to
7407 retrieve details if the return value is nonzero.)
7408 </para>
7410 <para>
7411 When using <xref linkend="libpq-PQgetResult"/>, the application should
7412 respond to a <literal>PGRES_COPY_OUT</literal> result by executing
7413 <xref linkend="libpq-PQgetline"/> repeatedly, followed by
7414 <xref linkend="libpq-PQendcopy"/> after the terminator line is seen.
7415 It should then return to the <xref linkend="libpq-PQgetResult"/> loop
7416 until <xref linkend="libpq-PQgetResult"/> returns a null pointer.
7417 Similarly a <literal>PGRES_COPY_IN</literal> result is processed
7418 by a series of <xref linkend="libpq-PQputline"/> calls followed by
7419 <xref linkend="libpq-PQendcopy"/>, then return to the
7420 <xref linkend="libpq-PQgetResult"/> loop. This arrangement will
7421 ensure that a <command>COPY</command> command embedded in a series
7422 of <acronym>SQL</acronym> commands will be executed correctly.
7423 </para>
7425 <para>
7426 Older applications are likely to submit a <command>COPY</command>
7427 via <xref linkend="libpq-PQexec"/> and assume that the transaction
7428 is done after <xref linkend="libpq-PQendcopy"/>. This will work
7429 correctly only if the <command>COPY</command> is the only
7430 <acronym>SQL</acronym> command in the command string.
7431 </para>
7432 </listitem>
7433 </varlistentry>
7434 </variablelist>
7436 </sect2>
7438 </sect1>
7440 <sect1 id="libpq-control">
7441 <title>Control Functions</title>
7443 <para>
7444 These functions control miscellaneous details of <application>libpq</application>'s
7445 behavior.
7446 </para>
7448 <variablelist>
7449 <varlistentry id="libpq-PQclientEncoding">
7450 <term><function>PQclientEncoding</function><indexterm><primary>PQclientEncoding</primary></indexterm></term>
7452 <listitem>
7453 <para>
7454 Returns the client encoding.
7455 <synopsis>
7456 int PQclientEncoding(const PGconn *<replaceable>conn</replaceable>);
7457 </synopsis>
7459 Note that it returns the encoding ID, not a symbolic string
7460 such as <literal>EUC_JP</literal>. If unsuccessful, it returns -1.
7461 To convert an encoding ID to an encoding name, you
7462 can use:
7464 <synopsis>
7465 char *pg_encoding_to_char(int <replaceable>encoding_id</replaceable>);
7466 </synopsis>
7467 </para>
7468 </listitem>
7469 </varlistentry>
7471 <varlistentry id="libpq-PQsetClientEncoding">
7472 <term><function>PQsetClientEncoding</function><indexterm><primary>PQsetClientEncoding</primary></indexterm></term>
7474 <listitem>
7475 <para>
7476 Sets the client encoding.
7477 <synopsis>
7478 int PQsetClientEncoding(PGconn *<replaceable>conn</replaceable>, const char *<replaceable>encoding</replaceable>);
7479 </synopsis>
7481 <replaceable>conn</replaceable> is a connection to the server,
7482 and <replaceable>encoding</replaceable> is the encoding you want to
7483 use. If the function successfully sets the encoding, it returns 0,
7484 otherwise -1. The current encoding for this connection can be
7485 determined by using <xref linkend="libpq-PQclientEncoding"/>.
7486 </para>
7487 </listitem>
7488 </varlistentry>
7490 <varlistentry id="libpq-PQsetErrorVerbosity">
7491 <term><function>PQsetErrorVerbosity</function><indexterm><primary>PQsetErrorVerbosity</primary></indexterm></term>
7493 <listitem>
7494 <para>
7495 Determines the verbosity of messages returned by
7496 <xref linkend="libpq-PQerrorMessage"/> and <xref linkend="libpq-PQresultErrorMessage"/>.
7497 <synopsis>
7498 typedef enum
7500 PQERRORS_TERSE,
7501 PQERRORS_DEFAULT,
7502 PQERRORS_VERBOSE,
7503 PQERRORS_SQLSTATE
7504 } PGVerbosity;
7506 PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity);
7507 </synopsis>
7509 <xref linkend="libpq-PQsetErrorVerbosity"/> sets the verbosity mode,
7510 returning the connection's previous setting.
7511 In <firstterm>TERSE</firstterm> mode, returned messages include
7512 severity, primary text, and position only; this will normally fit on a
7513 single line. The <firstterm>DEFAULT</firstterm> mode produces messages
7514 that include the above plus any detail, hint, or context fields (these
7515 might span multiple lines). The <firstterm>VERBOSE</firstterm> mode
7516 includes all available fields. The <firstterm>SQLSTATE</firstterm>
7517 mode includes only the error severity and the <symbol>SQLSTATE</symbol>
7518 error code, if one is available (if not, the output is like
7519 <firstterm>TERSE</firstterm> mode).
7520 </para>
7522 <para>
7523 Changing the verbosity setting does not affect the messages available
7524 from already-existing <structname>PGresult</structname> objects, only
7525 subsequently-created ones.
7526 (But see <xref linkend="libpq-PQresultVerboseErrorMessage"/> if you
7527 want to print a previous error with a different verbosity.)
7528 </para>
7529 </listitem>
7530 </varlistentry>
7532 <varlistentry id="libpq-PQsetErrorContextVisibility">
7533 <term><function>PQsetErrorContextVisibility</function><indexterm><primary>PQsetErrorContextVisibility</primary></indexterm></term>
7535 <listitem>
7536 <para>
7537 Determines the handling of <literal>CONTEXT</literal> fields in messages
7538 returned by <xref linkend="libpq-PQerrorMessage"/>
7539 and <xref linkend="libpq-PQresultErrorMessage"/>.
7540 <synopsis>
7541 typedef enum
7543 PQSHOW_CONTEXT_NEVER,
7544 PQSHOW_CONTEXT_ERRORS,
7545 PQSHOW_CONTEXT_ALWAYS
7546 } PGContextVisibility;
7548 PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context);
7549 </synopsis>
7551 <xref linkend="libpq-PQsetErrorContextVisibility"/> sets the context display mode,
7552 returning the connection's previous setting. This mode controls
7553 whether the <literal>CONTEXT</literal> field is included in messages.
7554 The <firstterm>NEVER</firstterm> mode
7555 never includes <literal>CONTEXT</literal>, while <firstterm>ALWAYS</firstterm> always
7556 includes it if available. In <firstterm>ERRORS</firstterm> mode (the
7557 default), <literal>CONTEXT</literal> fields are included only in error
7558 messages, not in notices and warnings.
7559 (However, if the verbosity setting is <firstterm>TERSE</firstterm>
7560 or <firstterm>SQLSTATE</firstterm>, <literal>CONTEXT</literal> fields
7561 are omitted regardless of the context display mode.)
7562 </para>
7564 <para>
7565 Changing this mode does not
7566 affect the messages available from
7567 already-existing <structname>PGresult</structname> objects, only
7568 subsequently-created ones.
7569 (But see <xref linkend="libpq-PQresultVerboseErrorMessage"/> if you
7570 want to print a previous error with a different display mode.)
7571 </para>
7572 </listitem>
7573 </varlistentry>
7575 <varlistentry id="libpq-PQtrace">
7576 <term><function>PQtrace</function><indexterm><primary>PQtrace</primary></indexterm></term>
7578 <listitem>
7579 <para>
7580 Enables tracing of the client/server communication to a debugging file
7581 stream.
7582 <synopsis>
7583 void PQtrace(PGconn *conn, FILE *stream);
7584 </synopsis>
7585 </para>
7587 <para>
7588 Each line consists of: an optional timestamp, a direction indicator
7589 (<literal>F</literal> for messages from client to server
7590 or <literal>B</literal> for messages from server to client),
7591 message length, message type, and message contents.
7592 Non-message contents fields (timestamp, direction, length and message type)
7593 are separated by a tab. Message contents are separated by a space.
7594 Protocol strings are enclosed in double quotes, while strings used as data
7595 values are enclosed in single quotes. Non-printable chars are printed as
7596 hexadecimal escapes.
7597 Further message-type-specific detail can be found in
7598 <xref linkend="protocol-message-formats"/>.
7599 </para>
7601 <note>
7602 <para>
7603 On Windows, if the <application>libpq</application> library and an application are
7604 compiled with different flags, this function call will crash the
7605 application because the internal representation of the <literal>FILE</literal>
7606 pointers differ. Specifically, multithreaded/single-threaded,
7607 release/debug, and static/dynamic flags should be the same for the
7608 library and all applications using that library.
7609 </para>
7610 </note>
7612 </listitem>
7613 </varlistentry>
7615 <varlistentry id="libpq-PQsetTraceFlags">
7616 <term><function>PQsetTraceFlags</function><indexterm><primary>PQsetTraceFlags</primary></indexterm></term>
7618 <listitem>
7619 <para>
7620 Controls the tracing behavior of client/server communication.
7621 <synopsis>
7622 void PQsetTraceFlags(PGconn *conn, int flags);
7623 </synopsis>
7624 </para>
7626 <para>
7627 <literal>flags</literal> contains flag bits describing the operating mode
7628 of tracing.
7629 If <literal>flags</literal> contains <literal>PQTRACE_SUPPRESS_TIMESTAMPS</literal>,
7630 then the timestamp is not included when printing each message.
7631 If <literal>flags</literal> contains <literal>PQTRACE_REGRESS_MODE</literal>,
7632 then some fields are redacted when printing each message, such as object
7633 OIDs, to make the output more convenient to use in testing frameworks.
7634 This function must be called after calling <function>PQtrace</function>.
7635 </para>
7637 </listitem>
7638 </varlistentry>
7640 <varlistentry id="libpq-PQuntrace">
7641 <term><function>PQuntrace</function><indexterm><primary>PQuntrace</primary></indexterm></term>
7643 <listitem>
7644 <para>
7645 Disables tracing started by <xref linkend="libpq-PQtrace"/>.
7646 <synopsis>
7647 void PQuntrace(PGconn *conn);
7648 </synopsis>
7649 </para>
7650 </listitem>
7651 </varlistentry>
7652 </variablelist>
7654 </sect1>
7656 <sect1 id="libpq-misc">
7657 <title>Miscellaneous Functions</title>
7659 <para>
7660 As always, there are some functions that just don't fit anywhere.
7661 </para>
7663 <variablelist>
7664 <varlistentry id="libpq-PQfreemem">
7665 <term><function>PQfreemem</function><indexterm><primary>PQfreemem</primary></indexterm></term>
7667 <listitem>
7668 <para>
7669 Frees memory allocated by <application>libpq</application>.
7670 <synopsis>
7671 void PQfreemem(void *ptr);
7672 </synopsis>
7673 </para>
7675 <para>
7676 Frees memory allocated by <application>libpq</application>, particularly
7677 <xref linkend="libpq-PQescapeByteaConn"/>,
7678 <xref linkend="libpq-PQescapeBytea"/>,
7679 <xref linkend="libpq-PQunescapeBytea"/>,
7680 and <function>PQnotifies</function>.
7681 It is particularly important that this function, rather than
7682 <function>free()</function>, be used on Microsoft Windows. This is because
7683 allocating memory in a DLL and releasing it in the application works
7684 only if multithreaded/single-threaded, release/debug, and static/dynamic
7685 flags are the same for the DLL and the application. On non-Microsoft
7686 Windows platforms, this function is the same as the standard library
7687 function <function>free()</function>.
7688 </para>
7689 </listitem>
7690 </varlistentry>
7692 <varlistentry id="libpq-PQconninfoFree">
7693 <term><function>PQconninfoFree</function><indexterm><primary>PQconninfoFree</primary></indexterm></term>
7695 <listitem>
7696 <para>
7697 Frees the data structures allocated by
7698 <xref linkend="libpq-PQconndefaults"/> or <xref linkend="libpq-PQconninfoParse"/>.
7699 <synopsis>
7700 void PQconninfoFree(PQconninfoOption *connOptions);
7701 </synopsis>
7702 If the argument is a <symbol>NULL</symbol> pointer, no operation is
7703 performed.
7704 </para>
7706 <para>
7707 A simple <xref linkend="libpq-PQfreemem"/> will not do for this, since
7708 the array contains references to subsidiary strings.
7709 </para>
7710 </listitem>
7711 </varlistentry>
7713 <varlistentry id="libpq-PQencryptPasswordConn">
7714 <term><function>PQencryptPasswordConn</function><indexterm><primary>PQencryptPasswordConn</primary></indexterm></term>
7716 <listitem>
7717 <para>
7718 Prepares the encrypted form of a <productname>PostgreSQL</productname> password.
7719 <synopsis>
7720 char *PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm);
7721 </synopsis>
7722 This function is intended to be used by client applications that
7723 wish to send commands like <literal>ALTER USER joe PASSWORD
7724 'pwd'</literal>. It is good practice not to send the original cleartext
7725 password in such a command, because it might be exposed in command
7726 logs, activity displays, and so on. Instead, use this function to
7727 convert the password to encrypted form before it is sent.
7728 </para>
7730 <para>
7731 The <parameter>passwd</parameter> and <parameter>user</parameter> arguments
7732 are the cleartext password, and the SQL name of the user it is for.
7733 <parameter>algorithm</parameter> specifies the encryption algorithm
7734 to use to encrypt the password. Currently supported algorithms are
7735 <literal>md5</literal> and <literal>scram-sha-256</literal> (<literal>on</literal> and
7736 <literal>off</literal> are also accepted as aliases for <literal>md5</literal>, for
7737 compatibility with older server versions). Note that support for
7738 <literal>scram-sha-256</literal> was introduced in <productname>PostgreSQL</productname>
7739 version 10, and will not work correctly with older server versions. If
7740 <parameter>algorithm</parameter> is <symbol>NULL</symbol>, this function will query
7741 the server for the current value of the
7742 <xref linkend="guc-password-encryption"/> setting. That can block, and
7743 will fail if the current transaction is aborted, or if the connection
7744 is busy executing another query. If you wish to use the default
7745 algorithm for the server but want to avoid blocking, query
7746 <varname>password_encryption</varname> yourself before calling
7747 <xref linkend="libpq-PQencryptPasswordConn"/>, and pass that value as the
7748 <parameter>algorithm</parameter>.
7749 </para>
7751 <para>
7752 The return value is a string allocated by <function>malloc</function>.
7753 The caller can assume the string doesn't contain any special characters
7754 that would require escaping. Use <xref linkend="libpq-PQfreemem"/> to free the
7755 result when done with it. On error, returns <symbol>NULL</symbol>, and
7756 a suitable message is stored in the connection object.
7757 </para>
7759 </listitem>
7760 </varlistentry>
7762 <varlistentry id="libpq-PQchangePassword">
7763 <term><function>PQchangePassword</function><indexterm><primary>PQchangePassword</primary></indexterm></term>
7765 <listitem>
7766 <para>
7767 Changes a <productname>PostgreSQL</productname> password.
7768 <synopsis>
7769 PGresult *PQchangePassword(PGconn *conn, const char *user, const char *passwd);
7770 </synopsis>
7771 This function uses <function>PQencryptPasswordConn</function>
7772 to build and execute the command <literal>ALTER USER ... PASSWORD
7773 '...'</literal>, thereby changing the user's password. It exists for
7774 the same reason as <function>PQencryptPasswordConn</function>, but
7775 is more convenient as it both builds and runs the command for you.
7776 <xref linkend="libpq-PQencryptPasswordConn"/> is passed a
7777 <symbol>NULL</symbol> for the algorithm argument, hence encryption is
7778 done according to the server's <xref linkend="guc-password-encryption"/>
7779 setting.
7780 </para>
7782 <para>
7783 The <parameter>user</parameter> and <parameter>passwd</parameter> arguments
7784 are the SQL name of the target user, and the new cleartext password.
7785 </para>
7787 <para>
7788 Returns a <structname>PGresult</structname> pointer representing
7789 the result of the <literal>ALTER USER</literal> command, or
7790 a null pointer if the routine failed before issuing any command.
7791 The <xref linkend="libpq-PQresultStatus"/> function should be called
7792 to check the return value for any errors (including the value of a null
7793 pointer, in which case it will return
7794 <symbol>PGRES_FATAL_ERROR</symbol>). Use
7795 <xref linkend="libpq-PQerrorMessage"/> to get more information about
7796 such errors.
7797 </para>
7798 </listitem>
7799 </varlistentry>
7801 <varlistentry id="libpq-PQencryptPassword">
7802 <term><function>PQencryptPassword</function><indexterm><primary>PQencryptPassword</primary></indexterm></term>
7804 <listitem>
7805 <para>
7806 Prepares the md5-encrypted form of a <productname>PostgreSQL</productname> password.
7807 <synopsis>
7808 char *PQencryptPassword(const char *passwd, const char *user);
7809 </synopsis>
7810 <xref linkend="libpq-PQencryptPassword"/> is an older, deprecated version of
7811 <xref linkend="libpq-PQencryptPasswordConn"/>. The difference is that
7812 <xref linkend="libpq-PQencryptPassword"/> does not
7813 require a connection object, and <literal>md5</literal> is always used as the
7814 encryption algorithm.
7815 </para>
7816 </listitem>
7817 </varlistentry>
7819 <varlistentry id="libpq-PQmakeEmptyPGresult">
7820 <term><function>PQmakeEmptyPGresult</function><indexterm><primary>PQmakeEmptyPGresult</primary></indexterm></term>
7822 <listitem>
7823 <para>
7824 Constructs an empty <structname>PGresult</structname> object with the given status.
7825 <synopsis>
7826 PGresult *PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status);
7827 </synopsis>
7828 </para>
7830 <para>
7831 This is <application>libpq</application>'s internal function to allocate and
7832 initialize an empty <structname>PGresult</structname> object. This
7833 function returns <symbol>NULL</symbol> if memory could not be allocated. It is
7834 exported because some applications find it useful to generate result
7835 objects (particularly objects with error status) themselves. If
7836 <parameter>conn</parameter> is not null and <parameter>status</parameter>
7837 indicates an error, the current error message of the specified
7838 connection is copied into the <structname>PGresult</structname>.
7839 Also, if <parameter>conn</parameter> is not null, any event procedures
7840 registered in the connection are copied into the
7841 <structname>PGresult</structname>. (They do not get
7842 <literal>PGEVT_RESULTCREATE</literal> calls, but see
7843 <xref linkend="libpq-PQfireResultCreateEvents"/>.)
7844 Note that <xref linkend="libpq-PQclear"/> should eventually be called
7845 on the object, just as with a <structname>PGresult</structname>
7846 returned by <application>libpq</application> itself.
7847 </para>
7848 </listitem>
7849 </varlistentry>
7851 <varlistentry id="libpq-PQfireResultCreateEvents">
7852 <term><function>PQfireResultCreateEvents</function><indexterm><primary>PQfireResultCreateEvents</primary></indexterm></term>
7853 <listitem>
7854 <para>
7855 Fires a <literal>PGEVT_RESULTCREATE</literal> event (see <xref
7856 linkend="libpq-events"/>) for each event procedure registered in the
7857 <structname>PGresult</structname> object. Returns non-zero for success,
7858 zero if any event procedure fails.
7860 <synopsis>
7861 int PQfireResultCreateEvents(PGconn *conn, PGresult *res);
7862 </synopsis>
7863 </para>
7865 <para>
7866 The <literal>conn</literal> argument is passed through to event procedures
7867 but not used directly. It can be <symbol>NULL</symbol> if the event
7868 procedures won't use it.
7869 </para>
7871 <para>
7872 Event procedures that have already received a
7873 <literal>PGEVT_RESULTCREATE</literal> or <literal>PGEVT_RESULTCOPY</literal> event
7874 for this object are not fired again.
7875 </para>
7877 <para>
7878 The main reason that this function is separate from
7879 <xref linkend="libpq-PQmakeEmptyPGresult"/> is that it is often appropriate
7880 to create a <structname>PGresult</structname> and fill it with data
7881 before invoking the event procedures.
7882 </para>
7883 </listitem>
7884 </varlistentry>
7886 <varlistentry id="libpq-PQcopyResult">
7887 <term><function>PQcopyResult</function><indexterm><primary>PQcopyResult</primary></indexterm></term>
7889 <listitem>
7890 <para>
7891 Makes a copy of a <structname>PGresult</structname> object. The copy is
7892 not linked to the source result in any way and
7893 <xref linkend="libpq-PQclear"/> must be called when the copy is no longer
7894 needed. If the function fails, <symbol>NULL</symbol> is returned.
7896 <synopsis>
7897 PGresult *PQcopyResult(const PGresult *src, int flags);
7898 </synopsis>
7899 </para>
7901 <para>
7902 This is not intended to make an exact copy. The returned result is
7903 always put into <literal>PGRES_TUPLES_OK</literal> status, and does not
7904 copy any error message in the source. (It does copy the command status
7905 string, however.) The <parameter>flags</parameter> argument determines
7906 what else is copied. It is a bitwise OR of several flags.
7907 <literal>PG_COPYRES_ATTRS</literal> specifies copying the source
7908 result's attributes (column definitions).
7909 <literal>PG_COPYRES_TUPLES</literal> specifies copying the source
7910 result's tuples. (This implies copying the attributes, too.)
7911 <literal>PG_COPYRES_NOTICEHOOKS</literal> specifies
7912 copying the source result's notify hooks.
7913 <literal>PG_COPYRES_EVENTS</literal> specifies copying the source
7914 result's events. (But any instance data associated with the source
7915 is not copied.)
7916 The event procedures receive <literal>PGEVT_RESULTCOPY</literal> events.
7917 </para>
7918 </listitem>
7919 </varlistentry>
7921 <varlistentry id="libpq-PQsetResultAttrs">
7922 <term><function>PQsetResultAttrs</function><indexterm><primary>PQsetResultAttrs</primary></indexterm></term>
7924 <listitem>
7925 <para>
7926 Sets the attributes of a <structname>PGresult</structname> object.
7927 <synopsis>
7928 int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs);
7929 </synopsis>
7930 </para>
7932 <para>
7933 The provided <parameter>attDescs</parameter> are copied into the result.
7934 If the <parameter>attDescs</parameter> pointer is <symbol>NULL</symbol> or
7935 <parameter>numAttributes</parameter> is less than one, the request is
7936 ignored and the function succeeds. If <parameter>res</parameter>
7937 already contains attributes, the function will fail. If the function
7938 fails, the return value is zero. If the function succeeds, the return
7939 value is non-zero.
7940 </para>
7941 </listitem>
7942 </varlistentry>
7944 <varlistentry id="libpq-PQsetvalue">
7945 <term><function>PQsetvalue</function><indexterm><primary>PQsetvalue</primary></indexterm></term>
7947 <listitem>
7948 <para>
7949 Sets a tuple field value of a <structname>PGresult</structname> object.
7950 <synopsis>
7951 int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len);
7952 </synopsis>
7953 </para>
7955 <para>
7956 The function will automatically grow the result's internal tuples array
7957 as needed. However, the <parameter>tup_num</parameter> argument must be
7958 less than or equal to <xref linkend="libpq-PQntuples"/>, meaning this
7959 function can only grow the tuples array one tuple at a time. But any
7960 field of any existing tuple can be modified in any order. If a value at
7961 <parameter>field_num</parameter> already exists, it will be overwritten.
7962 If <parameter>len</parameter> is -1 or
7963 <parameter>value</parameter> is <symbol>NULL</symbol>, the field value
7964 will be set to an SQL null value. The
7965 <parameter>value</parameter> is copied into the result's private storage,
7966 thus is no longer needed after the function
7967 returns. If the function fails, the return value is zero. If the
7968 function succeeds, the return value is non-zero.
7969 </para>
7970 </listitem>
7971 </varlistentry>
7973 <varlistentry id="libpq-PQresultAlloc">
7974 <term><function>PQresultAlloc</function><indexterm><primary>PQresultAlloc</primary></indexterm></term>
7976 <listitem>
7977 <para>
7978 Allocate subsidiary storage for a <structname>PGresult</structname> object.
7979 <synopsis>
7980 void *PQresultAlloc(PGresult *res, size_t nBytes);
7981 </synopsis>
7982 </para>
7984 <para>
7985 Any memory allocated with this function will be freed when
7986 <parameter>res</parameter> is cleared. If the function fails,
7987 the return value is <symbol>NULL</symbol>. The result is
7988 guaranteed to be adequately aligned for any type of data,
7989 just as for <function>malloc</function>.
7990 </para>
7991 </listitem>
7992 </varlistentry>
7994 <varlistentry id="libpq-PQresultMemorySize">
7995 <term><function>PQresultMemorySize</function><indexterm><primary>PQresultMemorySize</primary></indexterm></term>
7997 <listitem>
7998 <para>
7999 Retrieves the number of bytes allocated for
8000 a <structname>PGresult</structname> object.
8001 <synopsis>
8002 size_t PQresultMemorySize(const PGresult *res);
8003 </synopsis>
8004 </para>
8006 <para>
8007 This value is the sum of all <function>malloc</function> requests
8008 associated with the <structname>PGresult</structname> object, that is,
8009 all the memory that will be freed by <xref linkend="libpq-PQclear"/>.
8010 This information can be useful for managing memory consumption.
8011 </para>
8012 </listitem>
8013 </varlistentry>
8015 <varlistentry id="libpq-PQlibVersion">
8016 <term><function>PQlibVersion</function><indexterm
8017 ><primary>PQlibVersion</primary><seealso>PQserverVersion</seealso></indexterm></term>
8019 <listitem>
8020 <para>
8021 Return the version of <productname>libpq</productname> that is being used.
8022 <synopsis>
8023 int PQlibVersion(void);
8024 </synopsis>
8025 </para>
8027 <para>
8028 The result of this function can be used to determine, at
8029 run time, whether specific functionality is available in the currently
8030 loaded version of libpq. The function can be used, for example,
8031 to determine which connection options are available in
8032 <xref linkend="libpq-PQconnectdb"/>.
8033 </para>
8035 <para>
8036 The result is formed by multiplying the library's major version
8037 number by 10000 and adding the minor version number. For example,
8038 version 10.1 will be returned as 100001, and version 11.0 will be
8039 returned as 110000.
8040 </para>
8042 <para>
8043 Prior to major version 10, <productname>PostgreSQL</productname> used
8044 three-part version numbers in which the first two parts together
8045 represented the major version. For those
8046 versions, <xref linkend="libpq-PQlibVersion"/> uses two digits for each
8047 part; for example version 9.1.5 will be returned as 90105, and
8048 version 9.2.0 will be returned as 90200.
8049 </para>
8051 <para>
8052 Therefore, for purposes of determining feature compatibility,
8053 applications should divide the result of <xref linkend="libpq-PQlibVersion"/>
8054 by 100 not 10000 to determine a logical major version number.
8055 In all release series, only the last two digits differ between
8056 minor releases (bug-fix releases).
8057 </para>
8059 <note>
8060 <para>
8061 This function appeared in <productname>PostgreSQL</productname> version 9.1, so
8062 it cannot be used to detect required functionality in earlier
8063 versions, since calling it will create a link dependency
8064 on version 9.1 or later.
8065 </para>
8066 </note>
8067 </listitem>
8068 </varlistentry>
8070 <varlistentry id="libpq-PQgetCurrentTimeUSec">
8071 <term><function>PQgetCurrentTimeUSec</function><indexterm><primary>PQgetCurrentTimeUSec</primary></indexterm></term>
8073 <listitem>
8074 <para>
8075 Retrieves the current time, expressed as the number of microseconds
8076 since the Unix epoch (that is, <type>time_t</type> times 1 million).
8077 <synopsis>
8078 pg_usec_time_t PQgetCurrentTimeUSec(void);
8079 </synopsis>
8080 </para>
8082 <para>
8083 This is primarily useful for calculating timeout values to use with
8084 <xref linkend="libpq-PQsocketPoll"/>.
8085 </para>
8086 </listitem>
8087 </varlistentry>
8089 </variablelist>
8091 </sect1>
8093 <sect1 id="libpq-notice-processing">
8094 <title>Notice Processing</title>
8096 <indexterm zone="libpq-notice-processing">
8097 <primary>notice processing</primary>
8098 <secondary>in libpq</secondary>
8099 </indexterm>
8101 <para>
8102 Notice and warning messages generated by the server are not returned
8103 by the query execution functions, since they do not imply failure of
8104 the query. Instead they are passed to a notice handling function, and
8105 execution continues normally after the handler returns. The default
8106 notice handling function prints the message on
8107 <filename>stderr</filename>, but the application can override this
8108 behavior by supplying its own handling function.
8109 </para>
8111 <para>
8112 For historical reasons, there are two levels of notice handling, called
8113 the notice receiver and notice processor. The default behavior is for
8114 the notice receiver to format the notice and pass a string to the notice
8115 processor for printing. However, an application that chooses to provide
8116 its own notice receiver will typically ignore the notice processor
8117 layer and just do all the work in the notice receiver.
8118 </para>
8120 <para>
8121 The function <function id="libpq-PQsetNoticeReceiver">PQsetNoticeReceiver</function>
8122 <indexterm><primary>notice receiver</primary></indexterm>
8123 <indexterm><primary>PQsetNoticeReceiver</primary></indexterm> sets or
8124 examines the current notice receiver for a connection object.
8125 Similarly, <function id="libpq-PQsetNoticeProcessor">PQsetNoticeProcessor</function>
8126 <indexterm><primary>notice processor</primary></indexterm>
8127 <indexterm><primary>PQsetNoticeProcessor</primary></indexterm> sets or
8128 examines the current notice processor.
8130 <synopsis>
8131 typedef void (*PQnoticeReceiver) (void *arg, const PGresult *res);
8133 PQnoticeReceiver
8134 PQsetNoticeReceiver(PGconn *conn,
8135 PQnoticeReceiver proc,
8136 void *arg);
8138 typedef void (*PQnoticeProcessor) (void *arg, const char *message);
8140 PQnoticeProcessor
8141 PQsetNoticeProcessor(PGconn *conn,
8142 PQnoticeProcessor proc,
8143 void *arg);
8144 </synopsis>
8146 Each of these functions returns the previous notice receiver or
8147 processor function pointer, and sets the new value. If you supply a
8148 null function pointer, no action is taken, but the current pointer is
8149 returned.
8150 </para>
8152 <para>
8153 When a notice or warning message is received from the server, or
8154 generated internally by <application>libpq</application>, the notice
8155 receiver function is called. It is passed the message in the form of
8156 a <symbol>PGRES_NONFATAL_ERROR</symbol>
8157 <structname>PGresult</structname>. (This allows the receiver to extract
8158 individual fields using <xref linkend="libpq-PQresultErrorField"/>, or obtain a
8159 complete preformatted message using <xref linkend="libpq-PQresultErrorMessage"/>
8160 or <xref linkend="libpq-PQresultVerboseErrorMessage"/>.) The same
8161 void pointer passed to <function>PQsetNoticeReceiver</function> is also
8162 passed. (This pointer can be used to access application-specific state
8163 if needed.)
8164 </para>
8166 <para>
8167 The default notice receiver simply extracts the message (using
8168 <xref linkend="libpq-PQresultErrorMessage"/>) and passes it to the notice
8169 processor.
8170 </para>
8172 <para>
8173 The notice processor is responsible for handling a notice or warning
8174 message given in text form. It is passed the string text of the message
8175 (including a trailing newline), plus a void pointer that is the same
8176 one passed to <function>PQsetNoticeProcessor</function>. (This pointer
8177 can be used to access application-specific state if needed.)
8178 </para>
8180 <para>
8181 The default notice processor is simply:
8182 <programlisting>
8183 static void
8184 defaultNoticeProcessor(void *arg, const char *message)
8186 fprintf(stderr, "%s", message);
8188 </programlisting>
8189 </para>
8191 <para>
8192 Once you have set a notice receiver or processor, you should expect
8193 that that function could be called as long as either the
8194 <structname>PGconn</structname> object or <structname>PGresult</structname> objects made
8195 from it exist. At creation of a <structname>PGresult</structname>, the
8196 <structname>PGconn</structname>'s current notice handling pointers are copied
8197 into the <structname>PGresult</structname> for possible use by functions like
8198 <xref linkend="libpq-PQgetvalue"/>.
8199 </para>
8201 </sect1>
8203 <sect1 id="libpq-events">
8204 <title>Event System</title>
8206 <para>
8207 <application>libpq</application>'s event system is designed to notify
8208 registered event handlers about interesting
8209 <application>libpq</application> events, such as the creation or
8210 destruction of <structname>PGconn</structname> and
8211 <structname>PGresult</structname> objects. A principal use case is that
8212 this allows applications to associate their own data with a
8213 <structname>PGconn</structname> or <structname>PGresult</structname>
8214 and ensure that that data is freed at an appropriate time.
8215 </para>
8217 <para>
8218 Each registered event handler is associated with two pieces of data,
8219 known to <application>libpq</application> only as opaque <literal>void *</literal>
8220 pointers. There is a <firstterm>pass-through</firstterm> pointer that is provided
8221 by the application when the event handler is registered with a
8222 <structname>PGconn</structname>. The pass-through pointer never changes for the
8223 life of the <structname>PGconn</structname> and all <structname>PGresult</structname>s
8224 generated from it; so if used, it must point to long-lived data.
8225 In addition there is an <firstterm>instance data</firstterm> pointer, which starts
8226 out <symbol>NULL</symbol> in every <structname>PGconn</structname> and <structname>PGresult</structname>.
8227 This pointer can be manipulated using the
8228 <xref linkend="libpq-PQinstanceData"/>,
8229 <xref linkend="libpq-PQsetInstanceData"/>,
8230 <xref linkend="libpq-PQresultInstanceData"/> and
8231 <xref linkend="libpq-PQresultSetInstanceData"/> functions. Note that
8232 unlike the pass-through pointer, instance data of a <structname>PGconn</structname>
8233 is not automatically inherited by <structname>PGresult</structname>s created from
8234 it. <application>libpq</application> does not know what pass-through
8235 and instance data pointers point to (if anything) and will never attempt
8236 to free them &mdash; that is the responsibility of the event handler.
8237 </para>
8239 <sect2 id="libpq-events-types">
8240 <title>Event Types</title>
8242 <para>
8243 The enum <literal>PGEventId</literal> names the types of events handled by
8244 the event system. All its values have names beginning with
8245 <literal>PGEVT</literal>. For each event type, there is a corresponding
8246 event info structure that carries the parameters passed to the event
8247 handlers. The event types are:
8248 </para>
8250 <variablelist>
8251 <varlistentry id="libpq-pgevt-register">
8252 <term><literal>PGEVT_REGISTER</literal></term>
8253 <listitem>
8254 <para>
8255 The register event occurs when <xref linkend="libpq-PQregisterEventProc"/>
8256 is called. It is the ideal time to initialize any
8257 <literal>instanceData</literal> an event procedure may need. Only one
8258 register event will be fired per event handler per connection. If the
8259 event procedure fails (returns zero), the registration is canceled.
8261 <synopsis>
8262 typedef struct
8264 PGconn *conn;
8265 } PGEventRegister;
8266 </synopsis>
8268 When a <literal>PGEVT_REGISTER</literal> event is received, the
8269 <parameter>evtInfo</parameter> pointer should be cast to a
8270 <structname>PGEventRegister *</structname>. This structure contains a
8271 <structname>PGconn</structname> that should be in the
8272 <literal>CONNECTION_OK</literal> status; guaranteed if one calls
8273 <xref linkend="libpq-PQregisterEventProc"/> right after obtaining a good
8274 <structname>PGconn</structname>. When returning a failure code, all
8275 cleanup must be performed as no <literal>PGEVT_CONNDESTROY</literal>
8276 event will be sent.
8277 </para>
8278 </listitem>
8279 </varlistentry>
8281 <varlistentry id="libpq-pgevt-connreset">
8282 <term><literal>PGEVT_CONNRESET</literal></term>
8283 <listitem>
8284 <para>
8285 The connection reset event is fired on completion of
8286 <xref linkend="libpq-PQreset"/> or <function>PQresetPoll</function>. In
8287 both cases, the event is only fired if the reset was successful.
8288 The return value of the event procedure is ignored
8289 in <productname>PostgreSQL</productname> v15 and later.
8290 With earlier versions, however, it's important to return success
8291 (nonzero) or the connection will be aborted.
8293 <synopsis>
8294 typedef struct
8296 PGconn *conn;
8297 } PGEventConnReset;
8298 </synopsis>
8300 When a <literal>PGEVT_CONNRESET</literal> event is received, the
8301 <parameter>evtInfo</parameter> pointer should be cast to a
8302 <structname>PGEventConnReset *</structname>. Although the contained
8303 <structname>PGconn</structname> was just reset, all event data remains
8304 unchanged. This event should be used to reset/reload/requery any
8305 associated <literal>instanceData</literal>. Note that even if the
8306 event procedure fails to process <literal>PGEVT_CONNRESET</literal>, it will
8307 still receive a <literal>PGEVT_CONNDESTROY</literal> event when the connection
8308 is closed.
8309 </para>
8310 </listitem>
8311 </varlistentry>
8313 <varlistentry id="libpq-pgevt-conndestroy">
8314 <term><literal>PGEVT_CONNDESTROY</literal></term>
8315 <listitem>
8316 <para>
8317 The connection destroy event is fired in response to
8318 <xref linkend="libpq-PQfinish"/>. It is the event procedure's
8319 responsibility to properly clean up its event data as libpq has no
8320 ability to manage this memory. Failure to clean up will lead
8321 to memory leaks.
8323 <synopsis>
8324 typedef struct
8326 PGconn *conn;
8327 } PGEventConnDestroy;
8328 </synopsis>
8330 When a <literal>PGEVT_CONNDESTROY</literal> event is received, the
8331 <parameter>evtInfo</parameter> pointer should be cast to a
8332 <structname>PGEventConnDestroy *</structname>. This event is fired
8333 prior to <xref linkend="libpq-PQfinish"/> performing any other cleanup.
8334 The return value of the event procedure is ignored since there is no
8335 way of indicating a failure from <xref linkend="libpq-PQfinish"/>. Also,
8336 an event procedure failure should not abort the process of cleaning up
8337 unwanted memory.
8338 </para>
8339 </listitem>
8340 </varlistentry>
8342 <varlistentry id="libpq-pgevt-resultcreate">
8343 <term><literal>PGEVT_RESULTCREATE</literal></term>
8344 <listitem>
8345 <para>
8346 The result creation event is fired in response to any query execution
8347 function that generates a result, including
8348 <xref linkend="libpq-PQgetResult"/>. This event will only be fired after
8349 the result has been created successfully.
8351 <synopsis>
8352 typedef struct
8354 PGconn *conn;
8355 PGresult *result;
8356 } PGEventResultCreate;
8357 </synopsis>
8359 When a <literal>PGEVT_RESULTCREATE</literal> event is received, the
8360 <parameter>evtInfo</parameter> pointer should be cast to a
8361 <structname>PGEventResultCreate *</structname>. The
8362 <parameter>conn</parameter> is the connection used to generate the
8363 result. This is the ideal place to initialize any
8364 <literal>instanceData</literal> that needs to be associated with the
8365 result. If an event procedure fails (returns zero), that event
8366 procedure will be ignored for the remaining lifetime of the result;
8367 that is, it will not receive <literal>PGEVT_RESULTCOPY</literal>
8368 or <literal>PGEVT_RESULTDESTROY</literal> events for this result or
8369 results copied from it.
8370 </para>
8371 </listitem>
8372 </varlistentry>
8374 <varlistentry id="libpq-pgevt-resultcopy">
8375 <term><literal>PGEVT_RESULTCOPY</literal></term>
8376 <listitem>
8377 <para>
8378 The result copy event is fired in response to
8379 <xref linkend="libpq-PQcopyResult"/>. This event will only be fired after
8380 the copy is complete. Only event procedures that have
8381 successfully handled the <literal>PGEVT_RESULTCREATE</literal>
8382 or <literal>PGEVT_RESULTCOPY</literal> event for the source result
8383 will receive <literal>PGEVT_RESULTCOPY</literal> events.
8385 <synopsis>
8386 typedef struct
8388 const PGresult *src;
8389 PGresult *dest;
8390 } PGEventResultCopy;
8391 </synopsis>
8393 When a <literal>PGEVT_RESULTCOPY</literal> event is received, the
8394 <parameter>evtInfo</parameter> pointer should be cast to a
8395 <structname>PGEventResultCopy *</structname>. The
8396 <parameter>src</parameter> result is what was copied while the
8397 <parameter>dest</parameter> result is the copy destination. This event
8398 can be used to provide a deep copy of <literal>instanceData</literal>,
8399 since <literal>PQcopyResult</literal> cannot do that. If an event
8400 procedure fails (returns zero), that event procedure will be
8401 ignored for the remaining lifetime of the new result; that is, it
8402 will not receive <literal>PGEVT_RESULTCOPY</literal>
8403 or <literal>PGEVT_RESULTDESTROY</literal> events for that result or
8404 results copied from it.
8405 </para>
8406 </listitem>
8407 </varlistentry>
8409 <varlistentry id="libpq-pgevt-resultdestroy">
8410 <term><literal>PGEVT_RESULTDESTROY</literal></term>
8411 <listitem>
8412 <para>
8413 The result destroy event is fired in response to a
8414 <xref linkend="libpq-PQclear"/>. It is the event procedure's
8415 responsibility to properly clean up its event data as libpq has no
8416 ability to manage this memory. Failure to clean up will lead
8417 to memory leaks.
8419 <synopsis>
8420 typedef struct
8422 PGresult *result;
8423 } PGEventResultDestroy;
8424 </synopsis>
8426 When a <literal>PGEVT_RESULTDESTROY</literal> event is received, the
8427 <parameter>evtInfo</parameter> pointer should be cast to a
8428 <structname>PGEventResultDestroy *</structname>. This event is fired
8429 prior to <xref linkend="libpq-PQclear"/> performing any other cleanup.
8430 The return value of the event procedure is ignored since there is no
8431 way of indicating a failure from <xref linkend="libpq-PQclear"/>. Also,
8432 an event procedure failure should not abort the process of cleaning up
8433 unwanted memory.
8434 </para>
8435 </listitem>
8436 </varlistentry>
8437 </variablelist>
8438 </sect2>
8440 <sect2 id="libpq-events-proc">
8441 <title>Event Callback Procedure</title>
8443 <variablelist>
8444 <varlistentry id="libpq-PGEventProc">
8445 <term><literal>PGEventProc</literal><indexterm><primary>PGEventProc</primary></indexterm></term>
8447 <listitem>
8448 <para>
8449 <literal>PGEventProc</literal> is a typedef for a pointer to an
8450 event procedure, that is, the user callback function that receives
8451 events from libpq. The signature of an event procedure must be
8453 <synopsis>
8454 int eventproc(PGEventId evtId, void *evtInfo, void *passThrough)
8455 </synopsis>
8457 The <parameter>evtId</parameter> parameter indicates which
8458 <literal>PGEVT</literal> event occurred. The
8459 <parameter>evtInfo</parameter> pointer must be cast to the appropriate
8460 structure type to obtain further information about the event.
8461 The <parameter>passThrough</parameter> parameter is the pointer
8462 provided to <xref linkend="libpq-PQregisterEventProc"/> when the event
8463 procedure was registered. The function should return a non-zero value
8464 if it succeeds and zero if it fails.
8465 </para>
8467 <para>
8468 A particular event procedure can be registered only once in any
8469 <structname>PGconn</structname>. This is because the address of the procedure
8470 is used as a lookup key to identify the associated instance data.
8471 </para>
8473 <caution>
8474 <para>
8475 On Windows, functions can have two different addresses: one visible
8476 from outside a DLL and another visible from inside the DLL. One
8477 should be careful that only one of these addresses is used with
8478 <application>libpq</application>'s event-procedure functions, else confusion will
8479 result. The simplest rule for writing code that will work is to
8480 ensure that event procedures are declared <literal>static</literal>. If the
8481 procedure's address must be available outside its own source file,
8482 expose a separate function to return the address.
8483 </para>
8484 </caution>
8485 </listitem>
8486 </varlistentry>
8487 </variablelist>
8488 </sect2>
8490 <sect2 id="libpq-events-funcs">
8491 <title>Event Support Functions</title>
8493 <variablelist>
8494 <varlistentry id="libpq-PQregisterEventProc">
8495 <term><function>PQregisterEventProc</function><indexterm><primary>PQregisterEventProc</primary></indexterm></term>
8497 <listitem>
8498 <para>
8499 Registers an event callback procedure with libpq.
8501 <synopsis>
8502 int PQregisterEventProc(PGconn *conn, PGEventProc proc,
8503 const char *name, void *passThrough);
8504 </synopsis>
8505 </para>
8507 <para>
8508 An event procedure must be registered once on each
8509 <structname>PGconn</structname> you want to receive events about. There is no
8510 limit, other than memory, on the number of event procedures that
8511 can be registered with a connection. The function returns a non-zero
8512 value if it succeeds and zero if it fails.
8513 </para>
8515 <para>
8516 The <parameter>proc</parameter> argument will be called when a libpq
8517 event is fired. Its memory address is also used to lookup
8518 <literal>instanceData</literal>. The <parameter>name</parameter>
8519 argument is used to refer to the event procedure in error messages.
8520 This value cannot be <symbol>NULL</symbol> or a zero-length string. The name string is
8521 copied into the <structname>PGconn</structname>, so what is passed need not be
8522 long-lived. The <parameter>passThrough</parameter> pointer is passed
8523 to the <parameter>proc</parameter> whenever an event occurs. This
8524 argument can be <symbol>NULL</symbol>.
8525 </para>
8526 </listitem>
8527 </varlistentry>
8529 <varlistentry id="libpq-PQsetInstanceData">
8530 <term><function>PQsetInstanceData</function><indexterm><primary>PQsetInstanceData</primary></indexterm></term>
8531 <listitem>
8532 <para>
8533 Sets the connection <parameter>conn</parameter>'s <literal>instanceData</literal>
8534 for procedure <parameter>proc</parameter> to <parameter>data</parameter>. This
8535 returns non-zero for success and zero for failure. (Failure is
8536 only possible if <parameter>proc</parameter> has not been properly
8537 registered in <parameter>conn</parameter>.)
8539 <synopsis>
8540 int PQsetInstanceData(PGconn *conn, PGEventProc proc, void *data);
8541 </synopsis>
8542 </para>
8543 </listitem>
8544 </varlistentry>
8546 <varlistentry id="libpq-PQinstanceData">
8547 <term><function>PQinstanceData</function><indexterm><primary>PQinstanceData</primary></indexterm></term>
8548 <listitem>
8549 <para>
8550 Returns the
8551 connection <parameter>conn</parameter>'s <literal>instanceData</literal>
8552 associated with procedure <parameter>proc</parameter>,
8553 or <symbol>NULL</symbol> if there is none.
8555 <synopsis>
8556 void *PQinstanceData(const PGconn *conn, PGEventProc proc);
8557 </synopsis>
8558 </para>
8559 </listitem>
8560 </varlistentry>
8562 <varlistentry id="libpq-PQresultSetInstanceData">
8563 <term><function>PQresultSetInstanceData</function><indexterm><primary>PQresultSetInstanceData</primary></indexterm></term>
8564 <listitem>
8565 <para>
8566 Sets the result's <literal>instanceData</literal>
8567 for <parameter>proc</parameter> to <parameter>data</parameter>. This returns
8568 non-zero for success and zero for failure. (Failure is only
8569 possible if <parameter>proc</parameter> has not been properly registered
8570 in the result.)
8572 <synopsis>
8573 int PQresultSetInstanceData(PGresult *res, PGEventProc proc, void *data);
8574 </synopsis>
8575 </para>
8577 <para>
8578 Beware that any storage represented by <parameter>data</parameter>
8579 will not be accounted for by <xref linkend="libpq-PQresultMemorySize"/>,
8580 unless it is allocated using <xref linkend="libpq-PQresultAlloc"/>.
8581 (Doing so is recommendable because it eliminates the need to free
8582 such storage explicitly when the result is destroyed.)
8583 </para>
8584 </listitem>
8585 </varlistentry>
8587 <varlistentry id="libpq-PQresultInstanceData">
8588 <term><function>PQresultInstanceData</function><indexterm><primary>PQresultInstanceData</primary></indexterm></term>
8589 <listitem>
8590 <para>
8591 Returns the result's <literal>instanceData</literal> associated with <parameter>proc</parameter>, or <symbol>NULL</symbol>
8592 if there is none.
8594 <synopsis>
8595 void *PQresultInstanceData(const PGresult *res, PGEventProc proc);
8596 </synopsis>
8597 </para>
8598 </listitem>
8599 </varlistentry>
8600 </variablelist>
8601 </sect2>
8603 <sect2 id="libpq-events-example">
8604 <title>Event Example</title>
8606 <para>
8607 Here is a skeleton example of managing private data associated with
8608 libpq connections and results.
8609 </para>
8611 <programlisting>
8612 <![CDATA[
8613 /* required header for libpq events (note: includes libpq-fe.h) */
8614 #include <libpq-events.h>
8616 /* The instanceData */
8617 typedef struct
8619 int n;
8620 char *str;
8621 } mydata;
8623 /* PGEventProc */
8624 static int myEventProc(PGEventId evtId, void *evtInfo, void *passThrough);
8627 main(void)
8629 mydata *data;
8630 PGresult *res;
8631 PGconn *conn =
8632 PQconnectdb("dbname=postgres options=-csearch_path=");
8634 if (PQstatus(conn) != CONNECTION_OK)
8636 /* PQerrorMessage's result includes a trailing newline */
8637 fprintf(stderr, "%s", PQerrorMessage(conn));
8638 PQfinish(conn);
8639 return 1;
8642 /* called once on any connection that should receive events.
8643 * Sends a PGEVT_REGISTER to myEventProc.
8645 if (!PQregisterEventProc(conn, myEventProc, "mydata_proc", NULL))
8647 fprintf(stderr, "Cannot register PGEventProc\n");
8648 PQfinish(conn);
8649 return 1;
8652 /* conn instanceData is available */
8653 data = PQinstanceData(conn, myEventProc);
8655 /* Sends a PGEVT_RESULTCREATE to myEventProc */
8656 res = PQexec(conn, "SELECT 1 + 1");
8658 /* result instanceData is available */
8659 data = PQresultInstanceData(res, myEventProc);
8661 /* If PG_COPYRES_EVENTS is used, sends a PGEVT_RESULTCOPY to myEventProc */
8662 res_copy = PQcopyResult(res, PG_COPYRES_TUPLES | PG_COPYRES_EVENTS);
8664 /* result instanceData is available if PG_COPYRES_EVENTS was
8665 * used during the PQcopyResult call.
8667 data = PQresultInstanceData(res_copy, myEventProc);
8669 /* Both clears send a PGEVT_RESULTDESTROY to myEventProc */
8670 PQclear(res);
8671 PQclear(res_copy);
8673 /* Sends a PGEVT_CONNDESTROY to myEventProc */
8674 PQfinish(conn);
8676 return 0;
8679 static int
8680 myEventProc(PGEventId evtId, void *evtInfo, void *passThrough)
8682 switch (evtId)
8684 case PGEVT_REGISTER:
8686 PGEventRegister *e = (PGEventRegister *)evtInfo;
8687 mydata *data = get_mydata(e->conn);
8689 /* associate app specific data with connection */
8690 PQsetInstanceData(e->conn, myEventProc, data);
8691 break;
8694 case PGEVT_CONNRESET:
8696 PGEventConnReset *e = (PGEventConnReset *)evtInfo;
8697 mydata *data = PQinstanceData(e->conn, myEventProc);
8699 if (data)
8700 memset(data, 0, sizeof(mydata));
8701 break;
8704 case PGEVT_CONNDESTROY:
8706 PGEventConnDestroy *e = (PGEventConnDestroy *)evtInfo;
8707 mydata *data = PQinstanceData(e->conn, myEventProc);
8709 /* free instance data because the conn is being destroyed */
8710 if (data)
8711 free_mydata(data);
8712 break;
8715 case PGEVT_RESULTCREATE:
8717 PGEventResultCreate *e = (PGEventResultCreate *)evtInfo;
8718 mydata *conn_data = PQinstanceData(e->conn, myEventProc);
8719 mydata *res_data = dup_mydata(conn_data);
8721 /* associate app specific data with result (copy it from conn) */
8722 PQresultSetInstanceData(e->result, myEventProc, res_data);
8723 break;
8726 case PGEVT_RESULTCOPY:
8728 PGEventResultCopy *e = (PGEventResultCopy *)evtInfo;
8729 mydata *src_data = PQresultInstanceData(e->src, myEventProc);
8730 mydata *dest_data = dup_mydata(src_data);
8732 /* associate app specific data with result (copy it from a result) */
8733 PQresultSetInstanceData(e->dest, myEventProc, dest_data);
8734 break;
8737 case PGEVT_RESULTDESTROY:
8739 PGEventResultDestroy *e = (PGEventResultDestroy *)evtInfo;
8740 mydata *data = PQresultInstanceData(e->result, myEventProc);
8742 /* free instance data because the result is being destroyed */
8743 if (data)
8744 free_mydata(data);
8745 break;
8748 /* unknown event ID, just return true. */
8749 default:
8750 break;
8753 return true; /* event processing succeeded */
8756 </programlisting>
8757 </sect2>
8758 </sect1>
8760 <sect1 id="libpq-envars">
8761 <title>Environment Variables</title>
8763 <indexterm zone="libpq-envars">
8764 <primary>environment variable</primary>
8765 </indexterm>
8767 <para>
8768 The following environment variables can be used to select default
8769 connection parameter values, which will be used by
8770 <xref linkend="libpq-PQconnectdb"/>, <xref linkend="libpq-PQsetdbLogin"/> and
8771 <xref linkend="libpq-PQsetdb"/> if no value is directly specified by the calling
8772 code. These are useful to avoid hard-coding database connection
8773 information into simple client applications, for example.
8775 <itemizedlist>
8776 <listitem>
8777 <para>
8778 <indexterm>
8779 <primary><envar>PGHOST</envar></primary>
8780 </indexterm>
8781 <envar>PGHOST</envar> behaves the same as the <xref
8782 linkend="libpq-connect-host"/> connection parameter.
8783 </para>
8784 </listitem>
8786 <listitem>
8787 <para>
8788 <indexterm>
8789 <primary><envar>PGSSLNEGOTIATION</envar></primary>
8790 </indexterm>
8791 <envar>PGSSLNEGOTIATION</envar> behaves the same as the <xref
8792 linkend="libpq-connect-sslnegotiation"/> connection parameter.
8793 </para>
8794 </listitem>
8796 <listitem>
8797 <para>
8798 <indexterm>
8799 <primary><envar>PGHOSTADDR</envar></primary>
8800 </indexterm>
8801 <envar>PGHOSTADDR</envar> behaves the same as the <xref
8802 linkend="libpq-connect-hostaddr"/> connection parameter.
8803 This can be set instead of or in addition to <envar>PGHOST</envar>
8804 to avoid DNS lookup overhead.
8805 </para>
8806 </listitem>
8808 <listitem>
8809 <para>
8810 <indexterm>
8811 <primary><envar>PGPORT</envar></primary>
8812 </indexterm>
8813 <envar>PGPORT</envar> behaves the same as the <xref
8814 linkend="libpq-connect-port"/> connection parameter.
8815 </para>
8816 </listitem>
8818 <listitem>
8819 <para>
8820 <indexterm>
8821 <primary><envar>PGDATABASE</envar></primary>
8822 </indexterm>
8823 <envar>PGDATABASE</envar> behaves the same as the <xref
8824 linkend="libpq-connect-dbname"/> connection parameter.
8825 </para>
8826 </listitem>
8828 <listitem>
8829 <para>
8830 <indexterm>
8831 <primary><envar>PGUSER</envar></primary>
8832 </indexterm>
8833 <envar>PGUSER</envar> behaves the same as the <xref
8834 linkend="libpq-connect-user"/> connection parameter.
8835 </para>
8836 </listitem>
8838 <listitem>
8839 <para>
8840 <indexterm>
8841 <primary><envar>PGPASSWORD</envar></primary>
8842 </indexterm>
8843 <envar>PGPASSWORD</envar> behaves the same as the <xref
8844 linkend="libpq-connect-password"/> connection parameter.
8845 Use of this environment variable
8846 is not recommended for security reasons, as some operating systems
8847 allow non-root users to see process environment variables via
8848 <application>ps</application>; instead consider using a password file
8849 (see <xref linkend="libpq-pgpass"/>).
8850 </para>
8851 </listitem>
8853 <listitem>
8854 <para>
8855 <indexterm>
8856 <primary><envar>PGPASSFILE</envar></primary>
8857 </indexterm>
8858 <envar>PGPASSFILE</envar> behaves the same as the <xref
8859 linkend="libpq-connect-passfile"/> connection parameter.
8860 </para>
8861 </listitem>
8863 <listitem>
8864 <para>
8865 <indexterm>
8866 <primary><envar>PGREQUIREAUTH</envar></primary>
8867 </indexterm>
8868 <envar>PGREQUIREAUTH</envar> behaves the same as the <xref
8869 linkend="libpq-connect-require-auth"/> connection parameter.
8870 </para>
8871 </listitem>
8873 <listitem>
8874 <para>
8875 <indexterm>
8876 <primary><envar>PGCHANNELBINDING</envar></primary>
8877 </indexterm>
8878 <envar>PGCHANNELBINDING</envar> behaves the same as the <xref
8879 linkend="libpq-connect-channel-binding"/> connection parameter.
8880 </para>
8881 </listitem>
8883 <listitem>
8884 <para>
8885 <indexterm>
8886 <primary><envar>PGSERVICE</envar></primary>
8887 </indexterm>
8888 <envar>PGSERVICE</envar> behaves the same as the <xref
8889 linkend="libpq-connect-service"/> connection parameter.
8890 </para>
8891 </listitem>
8893 <listitem>
8894 <para>
8895 <indexterm>
8896 <primary><envar>PGSERVICEFILE</envar></primary>
8897 </indexterm>
8898 <envar>PGSERVICEFILE</envar> specifies the name of the per-user
8899 connection service file
8900 (see <xref linkend="libpq-pgservice"/>).
8901 Defaults to <filename>~/.pg_service.conf</filename>, or
8902 <filename>%APPDATA%\postgresql\.pg_service.conf</filename> on
8903 Microsoft Windows.
8904 </para>
8905 </listitem>
8907 <listitem>
8908 <para>
8909 <indexterm>
8910 <primary><envar>PGOPTIONS</envar></primary>
8911 </indexterm>
8912 <envar>PGOPTIONS</envar> behaves the same as the <xref
8913 linkend="libpq-connect-options"/> connection parameter.
8914 </para>
8915 </listitem>
8917 <listitem>
8918 <para>
8919 <indexterm>
8920 <primary><envar>PGAPPNAME</envar></primary>
8921 </indexterm>
8922 <envar>PGAPPNAME</envar> behaves the same as the <xref
8923 linkend="libpq-connect-application-name"/> connection parameter.
8924 </para>
8925 </listitem>
8927 <listitem>
8928 <para>
8929 <indexterm>
8930 <primary><envar>PGSSLMODE</envar></primary>
8931 </indexterm>
8932 <envar>PGSSLMODE</envar> behaves the same as the <xref
8933 linkend="libpq-connect-sslmode"/> connection parameter.
8934 </para>
8935 </listitem>
8937 <listitem>
8938 <para>
8939 <indexterm>
8940 <primary><envar>PGREQUIRESSL</envar></primary>
8941 </indexterm>
8942 <envar>PGREQUIRESSL</envar> behaves the same as the <xref
8943 linkend="libpq-connect-requiressl"/> connection parameter.
8944 This environment variable is deprecated in favor of the
8945 <envar>PGSSLMODE</envar> variable; setting both variables suppresses the
8946 effect of this one.
8947 </para>
8948 </listitem>
8950 <listitem>
8951 <para>
8952 <indexterm>
8953 <primary><envar>PGSSLCOMPRESSION</envar></primary>
8954 </indexterm>
8955 <envar>PGSSLCOMPRESSION</envar> behaves the same as the <xref
8956 linkend="libpq-connect-sslcompression"/> connection parameter.
8957 </para>
8958 </listitem>
8960 <listitem>
8961 <para>
8962 <indexterm>
8963 <primary><envar>PGSSLCERT</envar></primary>
8964 </indexterm>
8965 <envar>PGSSLCERT</envar> behaves the same as the <xref
8966 linkend="libpq-connect-sslcert"/> connection parameter.
8967 </para>
8968 </listitem>
8970 <listitem>
8971 <para>
8972 <indexterm>
8973 <primary><envar>PGSSLKEY</envar></primary>
8974 </indexterm>
8975 <envar>PGSSLKEY</envar> behaves the same as the <xref
8976 linkend="libpq-connect-sslkey"/> connection parameter.
8977 </para>
8978 </listitem>
8980 <listitem>
8981 <para>
8982 <indexterm>
8983 <primary><envar>PGSSLCERTMODE</envar></primary>
8984 </indexterm>
8985 <envar>PGSSLCERTMODE</envar> behaves the same as the <xref
8986 linkend="libpq-connect-sslcertmode"/> connection parameter.
8987 </para>
8988 </listitem>
8990 <listitem>
8991 <para>
8992 <indexterm>
8993 <primary><envar>PGSSLROOTCERT</envar></primary>
8994 </indexterm>
8995 <envar>PGSSLROOTCERT</envar> behaves the same as the <xref
8996 linkend="libpq-connect-sslrootcert"/> connection parameter.
8997 </para>
8998 </listitem>
9000 <listitem>
9001 <para>
9002 <indexterm>
9003 <primary><envar>PGSSLCRL</envar></primary>
9004 </indexterm>
9005 <envar>PGSSLCRL</envar> behaves the same as the <xref
9006 linkend="libpq-connect-sslcrl"/> connection parameter.
9007 </para>
9008 </listitem>
9010 <listitem>
9011 <para>
9012 <indexterm>
9013 <primary><envar>PGSSLCRLDIR</envar></primary>
9014 </indexterm>
9015 <envar>PGSSLCRLDIR</envar> behaves the same as the <xref
9016 linkend="libpq-connect-sslcrldir"/> connection parameter.
9017 </para>
9018 </listitem>
9020 <listitem>
9021 <para>
9022 <indexterm>
9023 <primary><envar>PGSSLSNI</envar></primary>
9024 </indexterm>
9025 <envar>PGSSLSNI</envar> behaves the same as the <xref
9026 linkend="libpq-connect-sslsni"/> connection parameter.
9027 </para>
9028 </listitem>
9030 <listitem>
9031 <para>
9032 <indexterm>
9033 <primary><envar>PGREQUIREPEER</envar></primary>
9034 </indexterm>
9035 <envar>PGREQUIREPEER</envar> behaves the same as the <xref
9036 linkend="libpq-connect-requirepeer"/> connection parameter.
9037 </para>
9038 </listitem>
9040 <listitem>
9041 <para>
9042 <indexterm>
9043 <primary><envar>PGSSLMINPROTOCOLVERSION</envar></primary>
9044 </indexterm>
9045 <envar>PGSSLMINPROTOCOLVERSION</envar> behaves the same as the <xref
9046 linkend="libpq-connect-ssl-min-protocol-version"/> connection parameter.
9047 </para>
9048 </listitem>
9050 <listitem>
9051 <para>
9052 <indexterm>
9053 <primary><envar>PGSSLMAXPROTOCOLVERSION</envar></primary>
9054 </indexterm>
9055 <envar>PGSSLMAXPROTOCOLVERSION</envar> behaves the same as the <xref
9056 linkend="libpq-connect-ssl-max-protocol-version"/> connection parameter.
9057 </para>
9058 </listitem>
9060 <listitem>
9061 <para>
9062 <indexterm>
9063 <primary><envar>PGGSSENCMODE</envar></primary>
9064 </indexterm>
9065 <envar>PGGSSENCMODE</envar> behaves the same as the <xref
9066 linkend="libpq-connect-gssencmode"/> connection parameter.
9067 </para>
9068 </listitem>
9070 <listitem>
9071 <para>
9072 <indexterm>
9073 <primary><envar>PGKRBSRVNAME</envar></primary>
9074 </indexterm>
9075 <envar>PGKRBSRVNAME</envar> behaves the same as the <xref
9076 linkend="libpq-connect-krbsrvname"/> connection parameter.
9077 </para>
9078 </listitem>
9080 <listitem>
9081 <para>
9082 <indexterm>
9083 <primary><envar>PGGSSLIB</envar></primary>
9084 </indexterm>
9085 <envar>PGGSSLIB</envar> behaves the same as the <xref
9086 linkend="libpq-connect-gsslib"/> connection parameter.
9087 </para>
9088 </listitem>
9090 <listitem>
9091 <para>
9092 <indexterm>
9093 <primary><envar>PGGSSDELEGATION</envar></primary>
9094 </indexterm>
9095 <envar>PGGSSDELEGATION</envar> behaves the same as the <xref
9096 linkend="libpq-connect-gssdelegation"/> connection parameter.
9097 </para>
9098 </listitem>
9100 <listitem>
9101 <para>
9102 <indexterm>
9103 <primary><envar>PGCONNECT_TIMEOUT</envar></primary>
9104 </indexterm>
9105 <envar>PGCONNECT_TIMEOUT</envar> behaves the same as the <xref
9106 linkend="libpq-connect-connect-timeout"/> connection parameter.
9107 </para>
9108 </listitem>
9110 <listitem>
9111 <para>
9112 <indexterm>
9113 <primary><envar>PGCLIENTENCODING</envar></primary>
9114 </indexterm>
9115 <envar>PGCLIENTENCODING</envar> behaves the same as the <xref
9116 linkend="libpq-connect-client-encoding"/> connection parameter.
9117 </para>
9118 </listitem>
9120 <listitem>
9121 <para>
9122 <indexterm>
9123 <primary><envar>PGTARGETSESSIONATTRS</envar></primary>
9124 </indexterm>
9125 <envar>PGTARGETSESSIONATTRS</envar> behaves the same as the <xref
9126 linkend="libpq-connect-target-session-attrs"/> connection parameter.
9127 </para>
9128 </listitem>
9130 <listitem>
9131 <para>
9132 <indexterm>
9133 <primary><envar>PGLOADBALANCEHOSTS</envar></primary>
9134 </indexterm>
9135 <envar>PGLOADBALANCEHOSTS</envar> behaves the same as the <xref
9136 linkend="libpq-connect-load-balance-hosts"/> connection parameter.
9137 </para>
9138 </listitem>
9139 </itemizedlist>
9140 </para>
9142 <para>
9143 The following environment variables can be used to specify default
9144 behavior for each <productname>PostgreSQL</productname> session. (See
9145 also the <xref linkend="sql-alterrole"/>
9146 and <xref linkend="sql-alterdatabase"/>
9147 commands for ways to set default behavior on a per-user or per-database
9148 basis.)
9150 <itemizedlist>
9151 <listitem>
9152 <para>
9153 <indexterm>
9154 <primary><envar>PGDATESTYLE</envar></primary>
9155 </indexterm>
9156 <envar>PGDATESTYLE</envar> sets the default style of date/time
9157 representation. (Equivalent to <literal>SET datestyle TO
9158 ...</literal>.)
9159 </para>
9160 </listitem>
9162 <listitem>
9163 <para>
9164 <indexterm>
9165 <primary><envar>PGTZ</envar></primary>
9166 </indexterm>
9167 <envar>PGTZ</envar> sets the default time zone. (Equivalent to
9168 <literal>SET timezone TO ...</literal>.)
9169 </para>
9170 </listitem>
9172 <listitem>
9173 <para>
9174 <indexterm>
9175 <primary><envar>PGGEQO</envar></primary>
9176 </indexterm>
9177 <envar>PGGEQO</envar> sets the default mode for the genetic query
9178 optimizer. (Equivalent to <literal>SET geqo TO ...</literal>.)
9179 </para>
9180 </listitem>
9181 </itemizedlist>
9183 Refer to the <acronym>SQL</acronym> command <xref linkend="sql-set"/>
9184 for information on correct values for these
9185 environment variables.
9186 </para>
9188 <para>
9189 The following environment variables determine internal behavior of
9190 <application>libpq</application>; they override compiled-in defaults.
9192 <itemizedlist>
9193 <listitem>
9194 <para>
9195 <indexterm>
9196 <primary><envar>PGSYSCONFDIR</envar></primary>
9197 </indexterm>
9198 <envar>PGSYSCONFDIR</envar> sets the directory containing the
9199 <filename>pg_service.conf</filename> file and in a future version
9200 possibly other system-wide configuration files.
9201 </para>
9202 </listitem>
9204 <listitem>
9205 <para>
9206 <indexterm>
9207 <primary><envar>PGLOCALEDIR</envar></primary>
9208 </indexterm>
9209 <envar>PGLOCALEDIR</envar> sets the directory containing the
9210 <literal>locale</literal> files for message localization.
9211 </para>
9212 </listitem>
9213 </itemizedlist>
9214 </para>
9216 </sect1>
9219 <sect1 id="libpq-pgpass">
9220 <title>The Password File</title>
9222 <indexterm zone="libpq-pgpass">
9223 <primary>password file</primary>
9224 </indexterm>
9225 <indexterm zone="libpq-pgpass">
9226 <primary>.pgpass</primary>
9227 </indexterm>
9229 <para>
9230 The file <filename>.pgpass</filename> in a user's home directory can
9231 contain passwords to
9232 be used if the connection requires a password (and no password has been
9233 specified otherwise). On Microsoft Windows the file is named
9234 <filename>%APPDATA%\postgresql\pgpass.conf</filename> (where
9235 <filename>%APPDATA%</filename> refers to the Application Data subdirectory in
9236 the user's profile).
9237 Alternatively, the password file to use can be specified
9238 using the connection parameter <xref linkend="libpq-connect-passfile"/>
9239 or the environment variable <envar>PGPASSFILE</envar>.
9240 </para>
9242 <para>
9243 This file should contain lines of the following format:
9244 <synopsis>
9245 <replaceable>hostname</replaceable>:<replaceable>port</replaceable>:<replaceable>database</replaceable>:<replaceable>username</replaceable>:<replaceable>password</replaceable>
9246 </synopsis>
9247 (You can add a reminder comment to the file by copying the line above and
9248 preceding it with <literal>#</literal>.)
9249 Each of the first four fields can be a literal value, or
9250 <literal>*</literal>, which matches anything. The password field from
9251 the first line that matches the current connection parameters will be
9252 used. (Therefore, put more-specific entries first when you are using
9253 wildcards.) If an entry needs to contain <literal>:</literal> or
9254 <literal>\</literal>, escape this character with <literal>\</literal>.
9255 The host name field is matched to the <literal>host</literal> connection
9256 parameter if that is specified, otherwise to
9257 the <literal>hostaddr</literal> parameter if that is specified; if neither
9258 are given then the host name <literal>localhost</literal> is searched for.
9259 The host name <literal>localhost</literal> is also searched for when
9260 the connection is a Unix-domain socket connection and
9261 the <literal>host</literal> parameter
9262 matches <application>libpq</application>'s default socket directory path.
9263 In a standby server, a database field of <literal>replication</literal>
9264 matches streaming replication connections made to the primary server.
9265 The database field is of limited usefulness otherwise, because users have
9266 the same password for all databases in the same cluster.
9267 </para>
9269 <para>
9270 On Unix systems, the permissions on a password file must
9271 disallow any access to world or group; achieve this by a command such as
9272 <command>chmod 0600 ~/.pgpass</command>. If the permissions are less
9273 strict than this, the file will be ignored. On Microsoft Windows, it
9274 is assumed that the file is stored in a directory that is secure, so
9275 no special permissions check is made.
9276 </para>
9277 </sect1>
9280 <sect1 id="libpq-pgservice">
9281 <title>The Connection Service File</title>
9283 <indexterm zone="libpq-pgservice">
9284 <primary>connection service file</primary>
9285 </indexterm>
9286 <indexterm zone="libpq-pgservice">
9287 <primary>pg_service.conf</primary>
9288 </indexterm>
9289 <indexterm zone="libpq-pgservice">
9290 <primary>.pg_service.conf</primary>
9291 </indexterm>
9293 <para>
9294 The connection service file allows libpq connection parameters to be
9295 associated with a single service name. That service name can then be
9296 specified in a libpq connection string, and the associated settings will be
9297 used. This allows connection parameters to be modified without requiring
9298 a recompile of the libpq-using application. The service name can also be
9299 specified using the <envar>PGSERVICE</envar> environment variable.
9300 </para>
9302 <para>
9303 Service names can be defined in either a per-user service file or a
9304 system-wide file. If the same service name exists in both the user
9305 and the system file, the user file takes precedence.
9306 By default, the per-user service file is named
9307 <filename>~/.pg_service.conf</filename>.
9308 On Microsoft Windows, it is named
9309 <filename>%APPDATA%\postgresql\.pg_service.conf</filename> (where
9310 <filename>%APPDATA%</filename> refers to the Application Data subdirectory
9311 in the user's profile). A different file name can be specified by
9312 setting the environment variable <envar>PGSERVICEFILE</envar>.
9313 The system-wide file is named <filename>pg_service.conf</filename>.
9314 By default it is sought in the <filename>etc</filename> directory
9315 of the <productname>PostgreSQL</productname> installation
9316 (use <literal>pg_config --sysconfdir</literal> to identify this
9317 directory precisely). Another directory, but not a different file
9318 name, can be specified by setting the environment variable
9319 <envar>PGSYSCONFDIR</envar>.
9320 </para>
9322 <para>
9323 Either service file uses an <quote>INI file</quote> format where the section
9324 name is the service name and the parameters are connection
9325 parameters; see <xref linkend="libpq-paramkeywords"/> for a list. For
9326 example:
9327 <programlisting>
9328 # comment
9329 [mydb]
9330 host=somehost
9331 port=5433
9332 user=admin
9333 </programlisting>
9334 An example file is provided in
9335 the <productname>PostgreSQL</productname> installation at
9336 <filename>share/pg_service.conf.sample</filename>.
9337 </para>
9339 <para>
9340 Connection parameters obtained from a service file are combined with
9341 parameters obtained from other sources. A service file setting
9342 overrides the corresponding environment variable, and in turn can be
9343 overridden by a value given directly in the connection string.
9344 For example, using the above service file, a connection string
9345 <literal>service=mydb port=5434</literal> will use
9346 host <literal>somehost</literal>, port <literal>5434</literal>,
9347 user <literal>admin</literal>, and other parameters as set by
9348 environment variables or built-in defaults.
9349 </para>
9350 </sect1>
9353 <sect1 id="libpq-ldap">
9354 <title>LDAP Lookup of Connection Parameters</title>
9356 <indexterm zone="libpq-ldap">
9357 <primary>LDAP connection parameter lookup</primary>
9358 </indexterm>
9360 <para>
9361 If <application>libpq</application> has been compiled with LDAP support (option
9362 <literal><option>--with-ldap</option></literal> for <command>configure</command>)
9363 it is possible to retrieve connection options like <literal>host</literal>
9364 or <literal>dbname</literal> via LDAP from a central server.
9365 The advantage is that if the connection parameters for a database change,
9366 the connection information doesn't have to be updated on all client machines.
9367 </para>
9369 <para>
9370 LDAP connection parameter lookup uses the connection service file
9371 <filename>pg_service.conf</filename> (see <xref
9372 linkend="libpq-pgservice"/>). A line in a
9373 <filename>pg_service.conf</filename> stanza that starts with
9374 <literal>ldap://</literal> will be recognized as an LDAP URL and an
9375 LDAP query will be performed. The result must be a list of
9376 <literal>keyword = value</literal> pairs which will be used to set
9377 connection options. The URL must conform to
9378 <ulink url="https://datatracker.ietf.org/doc/html/rfc1959">RFC 1959</ulink>
9379 and be of the form
9380 <synopsis>
9381 ldap://[<replaceable>hostname</replaceable>[:<replaceable>port</replaceable>]]/<replaceable>search_base</replaceable>?<replaceable>attribute</replaceable>?<replaceable>search_scope</replaceable>?<replaceable>filter</replaceable>
9382 </synopsis>
9383 where <replaceable>hostname</replaceable> defaults to
9384 <literal>localhost</literal> and <replaceable>port</replaceable>
9385 defaults to 389.
9386 </para>
9388 <para>
9389 Processing of <filename>pg_service.conf</filename> is terminated after
9390 a successful LDAP lookup, but is continued if the LDAP server cannot
9391 be contacted. This is to provide a fallback with further LDAP URL
9392 lines that point to different LDAP servers, classical <literal>keyword
9393 = value</literal> pairs, or default connection options. If you would
9394 rather get an error message in this case, add a syntactically incorrect
9395 line after the LDAP URL.
9396 </para>
9398 <para>
9399 A sample LDAP entry that has been created with the LDIF file
9400 <programlisting>
9401 version:1
9402 dn:cn=mydatabase,dc=mycompany,dc=com
9403 changetype:add
9404 objectclass:top
9405 objectclass:device
9406 cn:mydatabase
9407 description:host=dbserver.mycompany.com
9408 description:port=5439
9409 description:dbname=mydb
9410 description:user=mydb_user
9411 description:sslmode=require
9412 </programlisting>
9413 might be queried with the following LDAP URL:
9414 <programlisting>
9415 ldap://ldap.mycompany.com/dc=mycompany,dc=com?description?one?(cn=mydatabase)
9416 </programlisting>
9417 </para>
9419 <para>
9420 You can also mix regular service file entries with LDAP lookups.
9421 A complete example for a stanza in <filename>pg_service.conf</filename>
9422 would be:
9423 <programlisting>
9424 # only host and port are stored in LDAP, specify dbname and user explicitly
9425 [customerdb]
9426 dbname=customer
9427 user=appuser
9428 ldap://ldap.acme.com/cn=dbserver,cn=hosts?pgconnectinfo?base?(objectclass=*)
9429 </programlisting>
9430 </para>
9432 </sect1>
9435 <sect1 id="libpq-ssl">
9436 <title>SSL Support</title>
9438 <indexterm zone="libpq-ssl">
9439 <primary>SSL</primary>
9440 <secondary>TLS</secondary>
9441 </indexterm>
9443 <para>
9444 <productname>PostgreSQL</productname> has native support for using <acronym>SSL</acronym>
9445 connections to encrypt client/server communications using
9446 <acronym>TLS</acronym> protocols for increased security.
9447 See <xref linkend="ssl-tcp"/> for details about the server-side
9448 <acronym>SSL</acronym> functionality.
9449 </para>
9451 <para>
9452 <application>libpq</application> reads the system-wide
9453 <productname>OpenSSL</productname> configuration file. By default, this
9454 file is named <filename>openssl.cnf</filename> and is located in the
9455 directory reported by <literal>openssl version -d</literal>. This default
9456 can be overridden by setting environment variable
9457 <envar>OPENSSL_CONF</envar> to the name of the desired configuration
9458 file.
9459 </para>
9461 <sect2 id="libq-ssl-certificates">
9462 <title>Client Verification of Server Certificates</title>
9464 <para>
9465 By default, <productname>PostgreSQL</productname> will not perform any verification of
9466 the server certificate. This means that it is possible to spoof the server
9467 identity (for example by modifying a DNS record or by taking over the server
9468 IP address) without the client knowing. In order to prevent spoofing,
9469 the client must be able to verify the server's identity via a chain of
9470 trust. A chain of trust is established by placing a root (self-signed)
9471 certificate authority (<acronym>CA</acronym>) certificate on one
9472 computer and a leaf certificate <emphasis>signed</emphasis> by the
9473 root certificate on another computer. It is also possible to use an
9474 <quote>intermediate</quote> certificate which is signed by the root
9475 certificate and signs leaf certificates.
9476 </para>
9478 <para>
9479 To allow the client to verify the identity of the server, place a root
9480 certificate on the client and a leaf certificate signed by the root
9481 certificate on the server. To allow the server to verify the identity
9482 of the client, place a root certificate on the server and a leaf
9483 certificate signed by the root certificate on the client. One or more
9484 intermediate certificates (usually stored with the leaf certificate)
9485 can also be used to link the leaf certificate to the root certificate.
9486 </para>
9488 <para>
9489 Once a chain of trust has been established, there are two ways for
9490 the client to validate the leaf certificate sent by the server.
9491 If the parameter <literal>sslmode</literal> is set to <literal>verify-ca</literal>,
9492 libpq will verify that the server is trustworthy by checking the
9493 certificate chain up to the root certificate stored on the client.
9494 If <literal>sslmode</literal> is set to <literal>verify-full</literal>,
9495 libpq will <emphasis>also</emphasis> verify that the server host
9496 name matches the name stored in the server certificate. The
9497 SSL connection will fail if the server certificate cannot be
9498 verified. <literal>verify-full</literal> is recommended in most
9499 security-sensitive environments.
9500 </para>
9502 <para>
9503 In <literal>verify-full</literal> mode, the host name is matched against the
9504 certificate's Subject Alternative Name attribute(s) (SAN), or against the
9505 Common Name attribute if no SAN of type <literal>dNSName</literal> is
9506 present. If the certificate's name attribute starts with an asterisk
9507 (<literal>*</literal>), the asterisk will be treated as
9508 a wildcard, which will match all characters <emphasis>except</emphasis> a dot
9509 (<literal>.</literal>). This means the certificate will not match subdomains.
9510 If the connection is made using an IP address instead of a host name, the
9511 IP address will be matched (without doing any DNS lookups) against SANs of
9512 type <literal>iPAddress</literal> or <literal>dNSName</literal>. If no
9513 <literal>iPAddress</literal> SAN is present and no
9514 matching <literal>dNSName</literal> SAN is present, the host IP address is
9515 matched against the Common Name attribute.
9516 </para>
9518 <note>
9519 <para>
9520 For backward compatibility with earlier versions of PostgreSQL, the host
9521 IP address is verified in a manner different
9522 from <ulink url="https://datatracker.ietf.org/doc/html/rfc6125">RFC 6125</ulink>.
9523 The host IP address is always matched against <literal>dNSName</literal>
9524 SANs as well as <literal>iPAddress</literal> SANs, and can be matched
9525 against the Common Name attribute if no relevant SANs exist.
9526 </para>
9527 </note>
9529 <para>
9530 To allow server certificate verification, one or more root certificates
9531 must be placed in the file <filename>~/.postgresql/root.crt</filename>
9532 in the user's home directory. (On Microsoft Windows the file is named
9533 <filename>%APPDATA%\postgresql\root.crt</filename>.) Intermediate
9534 certificates should also be added to the file if they are needed to link
9535 the certificate chain sent by the server to the root certificates
9536 stored on the client.
9537 </para>
9539 <para>
9540 Certificate Revocation List (CRL) entries are also checked
9541 if the file <filename>~/.postgresql/root.crl</filename> exists
9542 (<filename>%APPDATA%\postgresql\root.crl</filename> on Microsoft
9543 Windows).
9544 </para>
9546 <para>
9547 The location of the root certificate file and the CRL can be changed by
9548 setting
9549 the connection parameters <literal>sslrootcert</literal> and <literal>sslcrl</literal>
9550 or the environment variables <envar>PGSSLROOTCERT</envar> and <envar>PGSSLCRL</envar>.
9551 <literal>sslcrldir</literal> or the environment variable <envar>PGSSLCRLDIR</envar>
9552 can also be used to specify a directory containing CRL files.
9553 </para>
9555 <note>
9556 <para>
9557 For backwards compatibility with earlier versions of PostgreSQL, if a
9558 root CA file exists, the behavior of
9559 <literal>sslmode</literal>=<literal>require</literal> will be the same
9560 as that of <literal>verify-ca</literal>, meaning the server certificate
9561 is validated against the CA. Relying on this behavior is discouraged,
9562 and applications that need certificate validation should always use
9563 <literal>verify-ca</literal> or <literal>verify-full</literal>.
9564 </para>
9565 </note>
9566 </sect2>
9568 <sect2 id="libpq-ssl-clientcert">
9569 <title>Client Certificates</title>
9571 <para>
9572 If the server attempts to verify the identity of the
9573 client by requesting the client's leaf certificate,
9574 <application>libpq</application> will send the certificate(s) stored in
9575 file <filename>~/.postgresql/postgresql.crt</filename> in the user's home
9576 directory. The certificates must chain to the root certificate trusted
9577 by the server. A matching
9578 private key file <filename>~/.postgresql/postgresql.key</filename> must also
9579 be present.
9580 On Microsoft Windows these files are named
9581 <filename>%APPDATA%\postgresql\postgresql.crt</filename> and
9582 <filename>%APPDATA%\postgresql\postgresql.key</filename>.
9583 The location of the certificate and key files can be overridden by the
9584 connection parameters <literal>sslcert</literal>
9585 and <literal>sslkey</literal>, or by the
9586 environment variables <envar>PGSSLCERT</envar> and <envar>PGSSLKEY</envar>.
9587 </para>
9589 <para>
9590 On Unix systems, the permissions on the private key file must disallow
9591 any access to world or group; achieve this by a command such as
9592 <command>chmod 0600 ~/.postgresql/postgresql.key</command>.
9593 Alternatively, the file can be owned by root and have group read access
9594 (that is, <literal>0640</literal> permissions). That setup is intended
9595 for installations where certificate and key files are managed by the
9596 operating system. The user of <application>libpq</application> should
9597 then be made a member of the group that has access to those certificate
9598 and key files. (On Microsoft Windows, there is no file permissions
9599 check, since the <filename>%APPDATA%\postgresql</filename> directory is
9600 presumed secure.)
9601 </para>
9603 <para>
9604 The first certificate in <filename>postgresql.crt</filename> must be the
9605 client's certificate because it must match the client's private key.
9606 <quote>Intermediate</quote> certificates can be optionally appended
9607 to the file &mdash; doing so avoids requiring storage of intermediate
9608 certificates on the server (<xref linkend="guc-ssl-ca-file"/>).
9609 </para>
9611 <para>
9612 The certificate and key may be in PEM or ASN.1 DER format.
9613 </para>
9615 <para>
9616 The key may be
9617 stored in cleartext or encrypted with a passphrase using any algorithm
9618 supported by <productname>OpenSSL</productname>, like AES-128. If the key
9619 is stored encrypted, then the passphrase may be provided in the
9620 <xref linkend="libpq-connect-sslpassword"/> connection option. If an
9621 encrypted key is supplied and the <literal>sslpassword</literal> option
9622 is absent or blank, a password will be prompted for interactively by
9623 <productname>OpenSSL</productname> with a
9624 <literal>Enter PEM pass phrase:</literal> prompt if a TTY is available.
9625 Applications can override the client certificate prompt and the handling
9626 of the <literal>sslpassword</literal> parameter by supplying their own
9627 key password callback; see
9628 <xref linkend="libpq-pqsetsslkeypasshook-openssl"/>.
9629 </para>
9631 <para>
9632 For instructions on creating certificates, see <xref
9633 linkend="ssl-certificate-creation"/>.
9634 </para>
9635 </sect2>
9637 <sect2 id="libpq-ssl-protection">
9638 <title>Protection Provided in Different Modes</title>
9640 <para>
9641 The different values for the <literal>sslmode</literal> parameter provide different
9642 levels of protection. SSL can provide
9643 protection against three types of attacks:
9645 <variablelist>
9646 <varlistentry>
9647 <term>Eavesdropping</term>
9648 <listitem>
9649 <para>If a third party can examine the network traffic between the
9650 client and the server, it can read both connection information (including
9651 the user name and password) and the data that is passed. <acronym>SSL</acronym>
9652 uses encryption to prevent this.
9653 </para>
9654 </listitem>
9655 </varlistentry>
9657 <varlistentry>
9658 <term>Man-in-the-middle (<acronym>MITM</acronym>)</term>
9659 <listitem>
9660 <para>If a third party can modify the data while passing between the
9661 client and server, it can pretend to be the server and therefore see and
9662 modify data <emphasis>even if it is encrypted</emphasis>. The third party can then
9663 forward the connection information and data to the original server,
9664 making it impossible to detect this attack. Common vectors to do this
9665 include DNS poisoning and address hijacking, whereby the client is directed
9666 to a different server than intended. There are also several other
9667 attack methods that can accomplish this. <acronym>SSL</acronym> uses certificate
9668 verification to prevent this, by authenticating the server to the client.
9669 </para>
9670 </listitem>
9671 </varlistentry>
9673 <varlistentry>
9674 <term>Impersonation</term>
9675 <listitem>
9676 <para>If a third party can pretend to be an authorized client, it can
9677 simply access data it should not have access to. Typically this can
9678 happen through insecure password management. <acronym>SSL</acronym> uses
9679 client certificates to prevent this, by making sure that only holders
9680 of valid certificates can access the server.
9681 </para>
9682 </listitem>
9683 </varlistentry>
9684 </variablelist>
9685 </para>
9687 <para>
9688 For a connection to be known SSL-secured, SSL usage must be configured
9689 on <emphasis>both the client and the server</emphasis> before the connection
9690 is made. If it is only configured on the server, the client may end up
9691 sending sensitive information (e.g., passwords) before
9692 it knows that the server requires high security. In libpq, secure
9693 connections can be ensured
9694 by setting the <literal>sslmode</literal> parameter to <literal>verify-full</literal> or
9695 <literal>verify-ca</literal>, and providing the system with a root certificate to
9696 verify against. This is analogous to using an <literal>https</literal>
9697 <acronym>URL</acronym> for encrypted web browsing.
9698 </para>
9700 <para>
9701 Once the server has been authenticated, the client can pass sensitive data.
9702 This means that up until this point, the client does not need to know if
9703 certificates will be used for authentication, making it safe to specify that
9704 only in the server configuration.
9705 </para>
9707 <para>
9708 All <acronym>SSL</acronym> options carry overhead in the form of encryption and
9709 key-exchange, so there is a trade-off that has to be made between performance
9710 and security. <xref linkend="libpq-ssl-sslmode-statements"/>
9711 illustrates the risks the different <literal>sslmode</literal> values
9712 protect against, and what statement they make about security and overhead.
9713 </para>
9715 <table id="libpq-ssl-sslmode-statements">
9716 <title>SSL Mode Descriptions</title>
9717 <tgroup cols="4">
9718 <colspec colname="col1" colwidth="1*"/>
9719 <colspec colname="col2" colwidth="1*"/>
9720 <colspec colname="col3" colwidth="1*"/>
9721 <colspec colname="col4" colwidth="2*"/>
9722 <thead>
9723 <row>
9724 <entry><literal>sslmode</literal></entry>
9725 <entry>Eavesdropping protection</entry>
9726 <entry><acronym>MITM</acronym> protection</entry>
9727 <entry>Statement</entry>
9728 </row>
9729 </thead>
9731 <tbody>
9732 <row>
9733 <entry><literal>disable</literal></entry>
9734 <entry>No</entry>
9735 <entry>No</entry>
9736 <entry>I don't care about security, and I don't want to pay the overhead
9737 of encryption.
9738 </entry>
9739 </row>
9741 <row>
9742 <entry><literal>allow</literal></entry>
9743 <entry>Maybe</entry>
9744 <entry>No</entry>
9745 <entry>I don't care about security, but I will pay the overhead of
9746 encryption if the server insists on it.
9747 </entry>
9748 </row>
9750 <row>
9751 <entry><literal>prefer</literal></entry>
9752 <entry>Maybe</entry>
9753 <entry>No</entry>
9754 <entry>I don't care about encryption, but I wish to pay the overhead of
9755 encryption if the server supports it.
9756 </entry>
9757 </row>
9759 <row>
9760 <entry><literal>require</literal></entry>
9761 <entry>Yes</entry>
9762 <entry>No</entry>
9763 <entry>I want my data to be encrypted, and I accept the overhead. I trust
9764 that the network will make sure I always connect to the server I want.
9765 </entry>
9766 </row>
9768 <row>
9769 <entry><literal>verify-ca</literal></entry>
9770 <entry>Yes</entry>
9771 <entry>Depends on CA policy</entry>
9772 <entry>I want my data encrypted, and I accept the overhead. I want to be
9773 sure that I connect to a server that I trust.
9774 </entry>
9775 </row>
9777 <row>
9778 <entry><literal>verify-full</literal></entry>
9779 <entry>Yes</entry>
9780 <entry>Yes</entry>
9781 <entry>I want my data encrypted, and I accept the overhead. I want to be
9782 sure that I connect to a server I trust, and that it's the one I
9783 specify.
9784 </entry>
9785 </row>
9787 </tbody>
9788 </tgroup>
9789 </table>
9791 <para>
9792 The difference between <literal>verify-ca</literal> and <literal>verify-full</literal>
9793 depends on the policy of the root <acronym>CA</acronym>. If a public
9794 <acronym>CA</acronym> is used, <literal>verify-ca</literal> allows connections to a server
9795 that <emphasis>somebody else</emphasis> may have registered with the <acronym>CA</acronym>.
9796 In this case, <literal>verify-full</literal> should always be used. If
9797 a local <acronym>CA</acronym> is used, or even a self-signed certificate, using
9798 <literal>verify-ca</literal> often provides enough protection.
9799 </para>
9801 <para>
9802 The default value for <literal>sslmode</literal> is <literal>prefer</literal>. As is shown
9803 in the table, this makes no sense from a security point of view, and it only
9804 promises performance overhead if possible. It is only provided as the default
9805 for backward compatibility, and is not recommended in secure deployments.
9806 </para>
9808 </sect2>
9810 <sect2 id="libpq-ssl-fileusage">
9811 <title>SSL Client File Usage</title>
9813 <para>
9814 <xref linkend="libpq-ssl-file-usage"/> summarizes the files that are
9815 relevant to the SSL setup on the client.
9816 </para>
9818 <table id="libpq-ssl-file-usage">
9819 <title>Libpq/Client SSL File Usage</title>
9820 <tgroup cols="3">
9821 <thead>
9822 <row>
9823 <entry>File</entry>
9824 <entry>Contents</entry>
9825 <entry>Effect</entry>
9826 </row>
9827 </thead>
9829 <tbody>
9831 <row>
9832 <entry><filename>~/.postgresql/postgresql.crt</filename></entry>
9833 <entry>client certificate</entry>
9834 <entry>sent to server</entry>
9835 </row>
9837 <row>
9838 <entry><filename>~/.postgresql/postgresql.key</filename></entry>
9839 <entry>client private key</entry>
9840 <entry>proves client certificate sent by owner; does not indicate
9841 certificate owner is trustworthy</entry>
9842 </row>
9844 <row>
9845 <entry><filename>~/.postgresql/root.crt</filename></entry>
9846 <entry>trusted certificate authorities</entry>
9847 <entry>checks that server certificate is signed by a trusted certificate
9848 authority</entry>
9849 </row>
9851 <row>
9852 <entry><filename>~/.postgresql/root.crl</filename></entry>
9853 <entry>certificates revoked by certificate authorities</entry>
9854 <entry>server certificate must not be on this list</entry>
9855 </row>
9857 </tbody>
9858 </tgroup>
9859 </table>
9860 </sect2>
9862 <sect2 id="libpq-ssl-initialize">
9863 <title>SSL Library Initialization</title>
9865 <para>
9866 If your application initializes <literal>libssl</literal> and/or
9867 <literal>libcrypto</literal> libraries and <application>libpq</application>
9868 is built with <acronym>SSL</acronym> support, you should call
9869 <xref linkend="libpq-PQinitOpenSSL"/> to tell <application>libpq</application>
9870 that the <literal>libssl</literal> and/or <literal>libcrypto</literal> libraries
9871 have been initialized by your application, so that
9872 <application>libpq</application> will not also initialize those libraries.
9873 However, this is unnecessary when using <productname>OpenSSL</productname>
9874 version 1.1.0 or later, as duplicate initializations are no longer problematic.
9875 </para>
9877 <para>
9878 <variablelist>
9879 <varlistentry id="libpq-PQinitOpenSSL">
9880 <term><function>PQinitOpenSSL</function><indexterm><primary>PQinitOpenSSL</primary></indexterm></term>
9882 <listitem>
9883 <para>
9884 Allows applications to select which security libraries to initialize.
9885 <synopsis>
9886 void PQinitOpenSSL(int do_ssl, int do_crypto);
9887 </synopsis>
9888 </para>
9890 <para>
9891 When <parameter>do_ssl</parameter> is non-zero, <application>libpq</application>
9892 will initialize the <productname>OpenSSL</productname> library before first
9893 opening a database connection. When <parameter>do_crypto</parameter> is
9894 non-zero, the <literal>libcrypto</literal> library will be initialized. By
9895 default (if <xref linkend="libpq-PQinitOpenSSL"/> is not called), both libraries
9896 are initialized. When SSL support is not compiled in, this function is
9897 present but does nothing.
9898 </para>
9900 <para>
9901 If your application uses and initializes either <productname>OpenSSL</productname>
9902 or its underlying <literal>libcrypto</literal> library, you <emphasis>must</emphasis>
9903 call this function with zeroes for the appropriate parameter(s)
9904 before first opening a database connection. Also be sure that you
9905 have done that initialization before opening a database connection.
9906 </para>
9907 </listitem>
9908 </varlistentry>
9910 <varlistentry id="libpq-PQinitSSL">
9911 <term><function>PQinitSSL</function><indexterm><primary>PQinitSSL</primary></indexterm></term><listitem>
9912 <para>
9913 Allows applications to select which security libraries to initialize.
9914 <synopsis>
9915 void PQinitSSL(int do_ssl);
9916 </synopsis>
9917 </para>
9919 <para>
9920 This function is equivalent to
9921 <literal>PQinitOpenSSL(do_ssl, do_ssl)</literal>.
9922 It is sufficient for applications that initialize both or neither
9923 of <productname>OpenSSL</productname> and <literal>libcrypto</literal>.
9924 </para>
9926 <para>
9927 <xref linkend="libpq-PQinitSSL"/> has been present since
9928 <productname>PostgreSQL</productname> 8.0, while <xref linkend="libpq-PQinitOpenSSL"/>
9929 was added in <productname>PostgreSQL</productname> 8.4, so <xref linkend="libpq-PQinitSSL"/>
9930 might be preferable for applications that need to work with older
9931 versions of <application>libpq</application>.
9932 </para>
9933 </listitem>
9934 </varlistentry>
9935 </variablelist>
9936 </para>
9937 </sect2>
9939 </sect1>
9942 <sect1 id="libpq-threading">
9943 <title>Behavior in Threaded Programs</title>
9945 <indexterm zone="libpq-threading">
9946 <primary>threads</primary>
9947 <secondary>with libpq</secondary>
9948 </indexterm>
9950 <para>
9951 As of version 17, <application>libpq</application> is always reentrant and thread-safe.
9952 However, one restriction is that no two threads attempt to manipulate
9953 the same <structname>PGconn</structname> object at the same time. In particular,
9954 you cannot issue concurrent commands from different threads through
9955 the same connection object. (If you need to run concurrent commands,
9956 use multiple connections.)
9957 </para>
9959 <para>
9960 <structname>PGresult</structname> objects are normally read-only after creation,
9961 and so can be passed around freely between threads. However, if you use
9962 any of the <structname>PGresult</structname>-modifying functions described in
9963 <xref linkend="libpq-misc"/> or <xref linkend="libpq-events"/>, it's up
9964 to you to avoid concurrent operations on the same <structname>PGresult</structname>,
9965 too.
9966 </para>
9968 <para>
9969 In earlier versions, <application>libpq</application> could be compiled
9970 with or without thread support, depending on compiler options. This
9971 function allows the querying of <application>libpq</application>'s
9972 thread-safe status:
9973 </para>
9975 <variablelist>
9976 <varlistentry id="libpq-PQisthreadsafe">
9977 <term><function>PQisthreadsafe</function><indexterm><primary>PQisthreadsafe</primary></indexterm></term>
9979 <listitem>
9980 <para>
9981 Returns the thread safety status of the
9982 <application>libpq</application> library.
9983 <synopsis>
9984 int PQisthreadsafe();
9985 </synopsis>
9986 </para>
9988 <para>
9989 Returns 1 if the <application>libpq</application> is thread-safe
9990 and 0 if it is not. Always returns 1 on version 17 and above.
9991 </para>
9992 </listitem>
9993 </varlistentry>
9994 </variablelist>
9996 <para>
9997 The deprecated functions <xref linkend="libpq-PQrequestCancel"/> and
9998 <xref linkend="libpq-PQoidStatus"/> are not thread-safe and should not be
9999 used in multithread programs. <xref linkend="libpq-PQrequestCancel"/>
10000 can be replaced by <xref linkend="libpq-PQcancelBlocking"/>.
10001 <xref linkend="libpq-PQoidStatus"/> can be replaced by
10002 <xref linkend="libpq-PQoidValue"/>.
10003 </para>
10005 <para>
10006 If you are using Kerberos inside your application (in addition to inside
10007 <application>libpq</application>), you will need to do locking around
10008 Kerberos calls because Kerberos functions are not thread-safe. See
10009 function <function>PQregisterThreadLock</function> in the
10010 <application>libpq</application> source code for a way to do cooperative
10011 locking between <application>libpq</application> and your application.
10012 </para>
10013 </sect1>
10016 <sect1 id="libpq-build">
10017 <title>Building <application>libpq</application> Programs</title>
10019 <indexterm zone="libpq-build">
10020 <primary>compiling</primary>
10021 <secondary>libpq applications</secondary>
10022 </indexterm>
10024 <para>
10025 To build (i.e., compile and link) a program using
10026 <application>libpq</application> you need to do all of the following
10027 things:
10029 <itemizedlist>
10030 <listitem>
10031 <para>
10032 Include the <filename>libpq-fe.h</filename> header file:
10033 <programlisting>
10034 #include &lt;libpq-fe.h&gt;
10035 </programlisting>
10036 If you failed to do that then you will normally get error messages
10037 from your compiler similar to:
10038 <screen>
10039 foo.c: In function `main':
10040 foo.c:34: `PGconn' undeclared (first use in this function)
10041 foo.c:35: `PGresult' undeclared (first use in this function)
10042 foo.c:54: `CONNECTION_BAD' undeclared (first use in this function)
10043 foo.c:68: `PGRES_COMMAND_OK' undeclared (first use in this function)
10044 foo.c:95: `PGRES_TUPLES_OK' undeclared (first use in this function)
10045 </screen>
10046 </para>
10047 </listitem>
10049 <listitem>
10050 <para>
10051 Point your compiler to the directory where the <productname>PostgreSQL</productname> header
10052 files were installed, by supplying the
10053 <literal>-I<replaceable>directory</replaceable></literal> option
10054 to your compiler. (In some cases the compiler will look into
10055 the directory in question by default, so you can omit this
10056 option.) For instance, your compile command line could look
10057 like:
10058 <programlisting>
10059 cc -c -I/usr/local/pgsql/include testprog.c
10060 </programlisting>
10061 If you are using makefiles then add the option to the
10062 <varname>CPPFLAGS</varname> variable:
10063 <programlisting>
10064 CPPFLAGS += -I/usr/local/pgsql/include
10065 </programlisting>
10066 </para>
10068 <para>
10069 If there is any chance that your program might be compiled by
10070 other users then you should not hardcode the directory location
10071 like that. Instead, you can run the utility
10072 <command>pg_config</command><indexterm><primary>pg_config</primary><secondary
10073 sortas="libpq">with libpq</secondary></indexterm> to find out where the header
10074 files are on the local system:
10075 <screen>
10076 <prompt>$</prompt> pg_config --includedir
10077 <computeroutput>/usr/local/include</computeroutput>
10078 </screen>
10079 </para>
10081 <para>
10082 If you
10083 have <command>pkg-config</command><indexterm><primary>pkg-config</primary><secondary sortas="libpq">with
10084 libpq</secondary></indexterm> installed, you can run instead:
10085 <screen>
10086 <prompt>$</prompt> pkg-config --cflags libpq
10087 <computeroutput>-I/usr/local/include</computeroutput>
10088 </screen>
10089 Note that this will already include the <option>-I</option> in front of
10090 the path.
10091 </para>
10093 <para>
10094 Failure to specify the correct option to the compiler will
10095 result in an error message such as:
10096 <screen>
10097 testlibpq.c:8:22: libpq-fe.h: No such file or directory
10098 </screen>
10099 </para>
10100 </listitem>
10102 <listitem>
10103 <para>
10104 When linking the final program, specify the option
10105 <literal>-lpq</literal> so that the <application>libpq</application>
10106 library gets pulled in, as well as the option
10107 <literal>-L<replaceable>directory</replaceable></literal> to point
10108 the compiler to the directory where the
10109 <application>libpq</application> library resides. (Again, the
10110 compiler will search some directories by default.) For maximum
10111 portability, put the <option>-L</option> option before the
10112 <option>-lpq</option> option. For example:
10113 <programlisting>
10114 cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq
10115 </programlisting>
10116 </para>
10118 <para>
10119 You can find out the library directory using
10120 <command>pg_config</command> as well:
10121 <screen>
10122 <prompt>$</prompt> pg_config --libdir
10123 <computeroutput>/usr/local/pgsql/lib</computeroutput>
10124 </screen>
10125 </para>
10127 <para>
10128 Or again use <command>pkg-config</command>:
10129 <screen>
10130 <prompt>$</prompt> pkg-config --libs libpq
10131 <computeroutput>-L/usr/local/pgsql/lib -lpq</computeroutput>
10132 </screen>
10133 Note again that this prints the full options, not only the path.
10134 </para>
10136 <para>
10137 Error messages that point to problems in this area could look like
10138 the following:
10139 <screen>
10140 testlibpq.o: In function `main':
10141 testlibpq.o(.text+0x60): undefined reference to `PQsetdbLogin'
10142 testlibpq.o(.text+0x71): undefined reference to `PQstatus'
10143 testlibpq.o(.text+0xa4): undefined reference to `PQerrorMessage'
10144 </screen>
10145 This means you forgot <option>-lpq</option>.
10146 <screen>
10147 /usr/bin/ld: cannot find -lpq
10148 </screen>
10149 This means you forgot the <option>-L</option> option or did not
10150 specify the right directory.
10151 </para>
10152 </listitem>
10153 </itemizedlist>
10154 </para>
10156 </sect1>
10159 <sect1 id="libpq-example">
10160 <title>Example Programs</title>
10162 <para>
10163 These examples and others can be found in the
10164 directory <filename>src/test/examples</filename> in the source code
10165 distribution.
10166 </para>
10168 <example id="libpq-example-1">
10169 <title><application>libpq</application> Example Program 1</title>
10171 <programlisting>
10172 <![CDATA[
10174 * src/test/examples/testlibpq.c
10177 * testlibpq.c
10179 * Test the C version of libpq, the PostgreSQL frontend library.
10181 #include <stdio.h>
10182 #include <stdlib.h>
10183 #include "libpq-fe.h"
10185 static void
10186 exit_nicely(PGconn *conn)
10188 PQfinish(conn);
10189 exit(1);
10193 main(int argc, char **argv)
10195 const char *conninfo;
10196 PGconn *conn;
10197 PGresult *res;
10198 int nFields;
10199 int i,
10203 * If the user supplies a parameter on the command line, use it as the
10204 * conninfo string; otherwise default to setting dbname=postgres and using
10205 * environment variables or defaults for all other connection parameters.
10207 if (argc > 1)
10208 conninfo = argv[1];
10209 else
10210 conninfo = "dbname = postgres";
10212 /* Make a connection to the database */
10213 conn = PQconnectdb(conninfo);
10215 /* Check to see that the backend connection was successfully made */
10216 if (PQstatus(conn) != CONNECTION_OK)
10218 fprintf(stderr, "%s", PQerrorMessage(conn));
10219 exit_nicely(conn);
10222 /* Set always-secure search path, so malicious users can't take control. */
10223 res = PQexec(conn,
10224 "SELECT pg_catalog.set_config('search_path', '', false)");
10225 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10227 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
10228 PQclear(res);
10229 exit_nicely(conn);
10233 * Should PQclear PGresult whenever it is no longer needed to avoid memory
10234 * leaks
10236 PQclear(res);
10239 * Our test case here involves using a cursor, for which we must be inside
10240 * a transaction block. We could do the whole thing with a single
10241 * PQexec() of "select * from pg_database", but that's too trivial to make
10242 * a good example.
10245 /* Start a transaction block */
10246 res = PQexec(conn, "BEGIN");
10247 if (PQresultStatus(res) != PGRES_COMMAND_OK)
10249 fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn));
10250 PQclear(res);
10251 exit_nicely(conn);
10253 PQclear(res);
10256 * Fetch rows from pg_database, the system catalog of databases
10258 res = PQexec(conn, "DECLARE myportal CURSOR FOR select * from pg_database");
10259 if (PQresultStatus(res) != PGRES_COMMAND_OK)
10261 fprintf(stderr, "DECLARE CURSOR failed: %s", PQerrorMessage(conn));
10262 PQclear(res);
10263 exit_nicely(conn);
10265 PQclear(res);
10267 res = PQexec(conn, "FETCH ALL in myportal");
10268 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10270 fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(conn));
10271 PQclear(res);
10272 exit_nicely(conn);
10275 /* first, print out the attribute names */
10276 nFields = PQnfields(res);
10277 for (i = 0; i < nFields; i++)
10278 printf("%-15s", PQfname(res, i));
10279 printf("\n\n");
10281 /* next, print out the rows */
10282 for (i = 0; i < PQntuples(res); i++)
10284 for (j = 0; j < nFields; j++)
10285 printf("%-15s", PQgetvalue(res, i, j));
10286 printf("\n");
10289 PQclear(res);
10291 /* close the portal ... we don't bother to check for errors ... */
10292 res = PQexec(conn, "CLOSE myportal");
10293 PQclear(res);
10295 /* end the transaction */
10296 res = PQexec(conn, "END");
10297 PQclear(res);
10299 /* close the connection to the database and cleanup */
10300 PQfinish(conn);
10302 return 0;
10305 </programlisting>
10306 </example>
10308 <example id="libpq-example-2">
10309 <title><application>libpq</application> Example Program 2</title>
10311 <programlisting>
10312 <![CDATA[
10314 * src/test/examples/testlibpq2.c
10317 * testlibpq2.c
10318 * Test of the asynchronous notification interface
10320 * Start this program, then from psql in another window do
10321 * NOTIFY TBL2;
10322 * Repeat four times to get this program to exit.
10324 * Or, if you want to get fancy, try this:
10325 * populate a database with the following commands
10326 * (provided in src/test/examples/testlibpq2.sql):
10328 * CREATE SCHEMA TESTLIBPQ2;
10329 * SET search_path = TESTLIBPQ2;
10330 * CREATE TABLE TBL1 (i int4);
10331 * CREATE TABLE TBL2 (i int4);
10332 * CREATE RULE r1 AS ON INSERT TO TBL1 DO
10333 * (INSERT INTO TBL2 VALUES (new.i); NOTIFY TBL2);
10335 * Start this program, then from psql do this four times:
10337 * INSERT INTO TESTLIBPQ2.TBL1 VALUES (10);
10340 #ifdef WIN32
10341 #include <windows.h>
10342 #endif
10343 #include <stdio.h>
10344 #include <stdlib.h>
10345 #include <string.h>
10346 #include <errno.h>
10347 #include <sys/select.h>
10348 #include <sys/time.h>
10349 #include <sys/types.h>
10351 #include "libpq-fe.h"
10353 static void
10354 exit_nicely(PGconn *conn)
10356 PQfinish(conn);
10357 exit(1);
10361 main(int argc, char **argv)
10363 const char *conninfo;
10364 PGconn *conn;
10365 PGresult *res;
10366 PGnotify *notify;
10367 int nnotifies;
10370 * If the user supplies a parameter on the command line, use it as the
10371 * conninfo string; otherwise default to setting dbname=postgres and using
10372 * environment variables or defaults for all other connection parameters.
10374 if (argc > 1)
10375 conninfo = argv[1];
10376 else
10377 conninfo = "dbname = postgres";
10379 /* Make a connection to the database */
10380 conn = PQconnectdb(conninfo);
10382 /* Check to see that the backend connection was successfully made */
10383 if (PQstatus(conn) != CONNECTION_OK)
10385 fprintf(stderr, "%s", PQerrorMessage(conn));
10386 exit_nicely(conn);
10389 /* Set always-secure search path, so malicious users can't take control. */
10390 res = PQexec(conn,
10391 "SELECT pg_catalog.set_config('search_path', '', false)");
10392 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10394 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
10395 PQclear(res);
10396 exit_nicely(conn);
10400 * Should PQclear PGresult whenever it is no longer needed to avoid memory
10401 * leaks
10403 PQclear(res);
10406 * Issue LISTEN command to enable notifications from the rule's NOTIFY.
10408 res = PQexec(conn, "LISTEN TBL2");
10409 if (PQresultStatus(res) != PGRES_COMMAND_OK)
10411 fprintf(stderr, "LISTEN command failed: %s", PQerrorMessage(conn));
10412 PQclear(res);
10413 exit_nicely(conn);
10415 PQclear(res);
10417 /* Quit after four notifies are received. */
10418 nnotifies = 0;
10419 while (nnotifies < 4)
10422 * Sleep until something happens on the connection. We use select(2)
10423 * to wait for input, but you could also use poll() or similar
10424 * facilities.
10426 int sock;
10427 fd_set input_mask;
10429 sock = PQsocket(conn);
10431 if (sock < 0)
10432 break; /* shouldn't happen */
10434 FD_ZERO(&input_mask);
10435 FD_SET(sock, &input_mask);
10437 if (select(sock + 1, &input_mask, NULL, NULL, NULL) < 0)
10439 fprintf(stderr, "select() failed: %s\n", strerror(errno));
10440 exit_nicely(conn);
10443 /* Now check for input */
10444 PQconsumeInput(conn);
10445 while ((notify = PQnotifies(conn)) != NULL)
10447 fprintf(stderr,
10448 "ASYNC NOTIFY of '%s' received from backend PID %d\n",
10449 notify->relname, notify->be_pid);
10450 PQfreemem(notify);
10451 nnotifies++;
10452 PQconsumeInput(conn);
10456 fprintf(stderr, "Done.\n");
10458 /* close the connection to the database and cleanup */
10459 PQfinish(conn);
10461 return 0;
10464 </programlisting>
10465 </example>
10467 <example id="libpq-example-3">
10468 <title><application>libpq</application> Example Program 3</title>
10470 <programlisting>
10471 <![CDATA[
10473 * src/test/examples/testlibpq3.c
10476 * testlibpq3.c
10477 * Test out-of-line parameters and binary I/O.
10479 * Before running this, populate a database with the following commands
10480 * (provided in src/test/examples/testlibpq3.sql):
10482 * CREATE SCHEMA testlibpq3;
10483 * SET search_path = testlibpq3;
10484 * SET standard_conforming_strings = ON;
10485 * CREATE TABLE test1 (i int4, t text, b bytea);
10486 * INSERT INTO test1 values (1, 'joe''s place', '\000\001\002\003\004');
10487 * INSERT INTO test1 values (2, 'ho there', '\004\003\002\001\000');
10489 * The expected output is:
10491 * tuple 0: got
10492 * i = (4 bytes) 1
10493 * t = (11 bytes) 'joe's place'
10494 * b = (5 bytes) \000\001\002\003\004
10496 * tuple 0: got
10497 * i = (4 bytes) 2
10498 * t = (8 bytes) 'ho there'
10499 * b = (5 bytes) \004\003\002\001\000
10502 #ifdef WIN32
10503 #include <windows.h>
10504 #endif
10506 #include <stdio.h>
10507 #include <stdlib.h>
10508 #include <stdint.h>
10509 #include <string.h>
10510 #include <sys/types.h>
10511 #include "libpq-fe.h"
10513 /* for ntohl/htonl */
10514 #include <netinet/in.h>
10515 #include <arpa/inet.h>
10518 static void
10519 exit_nicely(PGconn *conn)
10521 PQfinish(conn);
10522 exit(1);
10526 * This function prints a query result that is a binary-format fetch from
10527 * a table defined as in the comment above. We split it out because the
10528 * main() function uses it twice.
10530 static void
10531 show_binary_results(PGresult *res)
10533 int i,
10535 int i_fnum,
10536 t_fnum,
10537 b_fnum;
10539 /* Use PQfnumber to avoid assumptions about field order in result */
10540 i_fnum = PQfnumber(res, "i");
10541 t_fnum = PQfnumber(res, "t");
10542 b_fnum = PQfnumber(res, "b");
10544 for (i = 0; i < PQntuples(res); i++)
10546 char *iptr;
10547 char *tptr;
10548 char *bptr;
10549 int blen;
10550 int ival;
10552 /* Get the field values (we ignore possibility they are null!) */
10553 iptr = PQgetvalue(res, i, i_fnum);
10554 tptr = PQgetvalue(res, i, t_fnum);
10555 bptr = PQgetvalue(res, i, b_fnum);
10558 * The binary representation of INT4 is in network byte order, which
10559 * we'd better coerce to the local byte order.
10561 ival = ntohl(*((uint32_t *) iptr));
10564 * The binary representation of TEXT is, well, text, and since libpq
10565 * was nice enough to append a zero byte to it, it'll work just fine
10566 * as a C string.
10568 * The binary representation of BYTEA is a bunch of bytes, which could
10569 * include embedded nulls so we have to pay attention to field length.
10571 blen = PQgetlength(res, i, b_fnum);
10573 printf("tuple %d: got\n", i);
10574 printf(" i = (%d bytes) %d\n",
10575 PQgetlength(res, i, i_fnum), ival);
10576 printf(" t = (%d bytes) '%s'\n",
10577 PQgetlength(res, i, t_fnum), tptr);
10578 printf(" b = (%d bytes) ", blen);
10579 for (j = 0; j < blen; j++)
10580 printf("\\%03o", bptr[j]);
10581 printf("\n\n");
10586 main(int argc, char **argv)
10588 const char *conninfo;
10589 PGconn *conn;
10590 PGresult *res;
10591 const char *paramValues[1];
10592 int paramLengths[1];
10593 int paramFormats[1];
10594 uint32_t binaryIntVal;
10597 * If the user supplies a parameter on the command line, use it as the
10598 * conninfo string; otherwise default to setting dbname=postgres and using
10599 * environment variables or defaults for all other connection parameters.
10601 if (argc > 1)
10602 conninfo = argv[1];
10603 else
10604 conninfo = "dbname = postgres";
10606 /* Make a connection to the database */
10607 conn = PQconnectdb(conninfo);
10609 /* Check to see that the backend connection was successfully made */
10610 if (PQstatus(conn) != CONNECTION_OK)
10612 fprintf(stderr, "%s", PQerrorMessage(conn));
10613 exit_nicely(conn);
10616 /* Set always-secure search path, so malicious users can't take control. */
10617 res = PQexec(conn, "SET search_path = testlibpq3");
10618 if (PQresultStatus(res) != PGRES_COMMAND_OK)
10620 fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
10621 PQclear(res);
10622 exit_nicely(conn);
10624 PQclear(res);
10627 * The point of this program is to illustrate use of PQexecParams() with
10628 * out-of-line parameters, as well as binary transmission of data.
10630 * This first example transmits the parameters as text, but receives the
10631 * results in binary format. By using out-of-line parameters we can avoid
10632 * a lot of tedious mucking about with quoting and escaping, even though
10633 * the data is text. Notice how we don't have to do anything special with
10634 * the quote mark in the parameter value.
10637 /* Here is our out-of-line parameter value */
10638 paramValues[0] = "joe's place";
10640 res = PQexecParams(conn,
10641 "SELECT * FROM test1 WHERE t = $1",
10642 1, /* one param */
10643 NULL, /* let the backend deduce param type */
10644 paramValues,
10645 NULL, /* don't need param lengths since text */
10646 NULL, /* default to all text params */
10647 1); /* ask for binary results */
10649 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10651 fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
10652 PQclear(res);
10653 exit_nicely(conn);
10656 show_binary_results(res);
10658 PQclear(res);
10661 * In this second example we transmit an integer parameter in binary form,
10662 * and again retrieve the results in binary form.
10664 * Although we tell PQexecParams we are letting the backend deduce
10665 * parameter type, we really force the decision by casting the parameter
10666 * symbol in the query text. This is a good safety measure when sending
10667 * binary parameters.
10670 /* Convert integer value "2" to network byte order */
10671 binaryIntVal = htonl((uint32_t) 2);
10673 /* Set up parameter arrays for PQexecParams */
10674 paramValues[0] = (char *) &binaryIntVal;
10675 paramLengths[0] = sizeof(binaryIntVal);
10676 paramFormats[0] = 1; /* binary */
10678 res = PQexecParams(conn,
10679 "SELECT * FROM test1 WHERE i = $1::int4",
10680 1, /* one param */
10681 NULL, /* let the backend deduce param type */
10682 paramValues,
10683 paramLengths,
10684 paramFormats,
10685 1); /* ask for binary results */
10687 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10689 fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
10690 PQclear(res);
10691 exit_nicely(conn);
10694 show_binary_results(res);
10696 PQclear(res);
10698 /* close the connection to the database and cleanup */
10699 PQfinish(conn);
10701 return 0;
10704 </programlisting>
10705 </example>
10707 </sect1>
10708 </chapter>