1 <!-- doc/src/sgml/libpq.sgml -->
4 <title><application>libpq
</application> — C Library
</title>
6 <indexterm zone=
"libpq">
7 <primary>libpq
</primary>
10 <indexterm zone=
"libpq">
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.
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>.
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.
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.
49 <sect1 id=
"libpq-connect">
50 <title>Database Connection Control Functions
</title>
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.
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.
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.
95 <varlistentry id=
"libpq-PQconnectdbParams">
96 <term><function>PQconnectdbParams
</function><indexterm><primary>PQconnectdbParams
</primary></indexterm></term>
99 Makes a new connection to the database server.
102 PGconn *PQconnectdbParams(const char * const *keywords,
103 const char * const *values,
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
121 The currently recognized parameter key words are listed in
122 <xref linkend=
"libpq-paramkeywords"/>.
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.
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.
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).
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.
178 <varlistentry id=
"libpq-PQconnectdb">
179 <term><function>PQconnectdb
</function><indexterm><primary>PQconnectdb
</primary></indexterm></term>
182 Makes a new connection to the database server.
185 PGconn *PQconnectdb(const char *conninfo);
190 This function opens a new database connection using the parameters taken
191 from the string
<literal>conninfo
</literal>.
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.
205 <varlistentry id=
"libpq-PQsetdbLogin">
206 <term><function>PQsetdbLogin
</function><indexterm><primary>PQsetdbLogin
</primary></indexterm></term>
209 Makes a new connection to the database server.
211 PGconn *PQsetdbLogin(const char *pghost,
213 const char *pgoptions,
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.
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"/>.
237 <literal>pgtty
</literal> is no longer used and any value passed will
243 <varlistentry id=
"libpq-PQsetdb">
244 <term><function>PQsetdb
</function><indexterm><primary>PQsetdb
</primary></indexterm></term>
247 Makes a new connection to the database server.
249 PGconn *PQsetdb(char *pghost,
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.
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>
271 <indexterm><primary>nonblocking connection
</primary></indexterm>
272 Make a connection to the database server in a nonblocking manner.
275 PGconn *PQconnectStartParams(const char * const *keywords,
276 const char * const *values,
279 PGconn *PQconnectStart(const char *conninfo);
281 PostgresPollingStatusType PQconnectPoll(PGconn *conn);
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.
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"/>.
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"/>.
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:
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.
322 If you call
<xref linkend=
"libpq-PQtrace"/>, ensure that the stream object
323 into which you trace will not block.
329 You must ensure that the socket is in the appropriate state
330 before calling
<function>PQconnectPoll
</function>, as described below.
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.
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.
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:
389 <varlistentry id=
"libpq-connection-started">
390 <term><symbol>CONNECTION_STARTED
</symbol></term>
393 Waiting for connection to be made.
398 <varlistentry id=
"libpq-connection-made">
399 <term><symbol>CONNECTION_MADE
</symbol></term>
402 Connection OK; waiting to send.
407 <varlistentry id=
"libpq-connection-awaiting-response">
408 <term><symbol>CONNECTION_AWAITING_RESPONSE
</symbol></term>
411 Waiting for a response from the server.
416 <varlistentry id=
"libpq-connection-auth-ok">
417 <term><symbol>CONNECTION_AUTH_OK
</symbol></term>
420 Received authentication; waiting for backend start-up to finish.
425 <varlistentry id=
"libpq-connection-ssl-startup">
426 <term><symbol>CONNECTION_SSL_STARTUP
</symbol></term>
429 Negotiating SSL encryption.
434 <varlistentry id=
"libpq-connection-gss-startup">
435 <term><symbol>CONNECTION_GSS_STARTUP
</symbol></term>
438 Negotiating GSS encryption.
443 <varlistentry id=
"libpq-connection-check-writable">
444 <term><symbol>CONNECTION_CHECK_WRITABLE
</symbol></term>
447 Checking if connection is able to handle write transactions.
452 <varlistentry id=
"libpq-connection-check-standby">
453 <term><symbol>CONNECTION_CHECK_STANDBY
</symbol></term>
456 Checking if connection is to a server in standby mode.
461 <varlistentry id=
"libpq-connection-consume">
462 <term><symbol>CONNECTION_CONSUME
</symbol></term>
465 Consuming any remaining response messages on connection.
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:
476 switch(PQstatus(conn))
478 case CONNECTION_STARTED:
479 feedback =
"Connecting...";
482 case CONNECTION_MADE:
483 feedback =
"Connected to server...";
489 feedback =
"Connecting...";
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"/>.
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.
514 <varlistentry id=
"libpq-PQsocketPoll">
515 <term><function>PQsocketPoll
</function><indexterm><primary>PQsocketPoll
</primary></indexterm></term>
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"/>.
525 typedef pg_int64 pg_usec_time_t;
527 int PQsocketPoll(int sock, int forRead, int forWrite,
528 pg_usec_time_t end_time);
533 This function performs polling of a file descriptor, optionally with
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.
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.
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.
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.
578 <varlistentry id=
"libpq-PQconndefaults">
579 <term><function>PQconndefaults
</function><indexterm><primary>PQconndefaults
</primary></indexterm></term>
582 Returns the default connection options.
584 PQconninfoOption *PQconndefaults(void);
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 */
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.
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"/>.
625 <varlistentry id=
"libpq-PQconninfo">
626 <term><function>PQconninfo
</function><indexterm><primary>PQconninfo
</primary></indexterm></term>
629 Returns the connection options used by a live connection.
631 PQconninfoOption *PQconninfo(PGconn *conn);
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"/>.
649 <varlistentry id=
"libpq-PQconninfoParse">
650 <term><function>PQconninfoParse
</function><indexterm><primary>PQconninfoParse
</primary></indexterm></term>
653 Returns parsed connection options from the provided connection string.
656 PQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg);
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.
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.
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.)
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"/>.
696 <varlistentry id=
"libpq-PQfinish">
697 <term><function>PQfinish
</function><indexterm><primary>PQfinish
</primary></indexterm></term>
700 Closes the connection to the server. Also frees
701 memory used by the
<structname>PGconn
</structname> object.
703 void PQfinish(PGconn *conn);
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.
717 <varlistentry id=
"libpq-PQreset">
718 <term><function>PQreset
</function><indexterm><primary>PQreset
</primary></indexterm></term>
721 Resets the communication channel to the server.
723 void PQreset(PGconn *conn);
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.
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>
742 Reset the communication channel to the server, in a nonblocking manner.
745 int PQresetStart(PGconn *conn);
747 PostgresPollingStatusType PQresetPoll(PGconn *conn);
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>.
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>.
771 <varlistentry id=
"libpq-PQpingParams">
772 <term><function>PQpingParams
</function><indexterm><primary>PQpingParams
</primary></indexterm></term>
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.
783 PGPing PQpingParams(const char * const *keywords,
784 const char * const *values,
788 The function returns one of the following values:
791 <varlistentry id=
"libpq-PQpingParams-PQPING_OK">
792 <term><literal>PQPING_OK
</literal></term>
795 The server is running and appears to be accepting connections.
800 <varlistentry id=
"libpq-PQpingParams-PQPING_REJECT">
801 <term><literal>PQPING_REJECT
</literal></term>
804 The server is running but is in a state that disallows connections
805 (startup, shutdown, or crash recovery).
810 <varlistentry id=
"libpq-PQpingParams-PQPING_NO_RESPONSE">
811 <term><literal>PQPING_NO_RESPONSE
</literal></term>
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).
823 <varlistentry id=
"libpq-PQpingParams-PQPING_NO_ATTEMPT">
824 <term><literal>PQPING_NO_ATTEMPT
</literal></term>
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).
840 <varlistentry id=
"libpq-PQping">
841 <term><function>PQping
</function><indexterm><primary>PQping
</primary></indexterm></term>
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.
852 PGPing PQping(const char *conninfo);
857 The return values are the same as for
<xref linkend=
"libpq-PQpingParams"/>.
863 <varlistentry id=
"libpq-pqsetsslkeypasshook-openssl">
864 <term><function>PQsetSSLKeyPassHook_OpenSSL
</function><indexterm><primary>PQsetSSLKeyPassHook_OpenSSL
</primary></indexterm></term>
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.
873 void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook);
876 The application passes a pointer to a callback function with signature:
878 int callback_fn(char *buf, int size, PGconn *conn);
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.
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.
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.
910 The callback
<emphasis>must not
</emphasis> escape normal flow control with exceptions,
911 <function>longjmp(...)
</function>, etc. It must return normally.
917 <varlistentry id=
"libpq-pqgetsslkeypasshook-openssl">
918 <term><function>PQgetSSLKeyPassHook_OpenSSL
</function><indexterm><primary>PQgetSSLKeyPassHook_OpenSSL
</primary></indexterm></term>
921 <function>PQgetSSLKeyPassHook_OpenSSL
</function> returns the current
922 client certificate key password hook, or
<literal>NULL
</literal>
923 if none has been set.
926 PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void);
936 <sect2 id=
"libpq-connstring">
937 <title>Connection Strings
</title>
939 <indexterm zone=
"libpq-connstring">
940 <primary><literal>conninfo
</literal></primary>
943 <indexterm zone=
"libpq-connstring">
944 <primary><literal>URI
</literal></primary>
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.
957 <sect3 id=
"libpq-connstring-keyword-value">
958 <title>Keyword/Value Connection Strings
</title>
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>.
975 host=localhost port=
5432 dbname=mydb connect_timeout=
10
980 The recognized parameter key words are listed in
<xref
981 linkend=
"libpq-paramkeywords"/>.
985 <sect3 id=
"libpq-connstring-uris">
986 <title>Connection URIs
</title>
989 The general form for a connection
<acronym>URI
</acronym> is:
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>&...
</optional>
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:
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&application_name=myapp
1020 postgresql://host1:
123,host2:
456/somedb?target_session_attrs=any
&application_name=myapp
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:
1026 postgresql:///mydb?host=localhost
&port=
5433
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>.
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>:
1043 postgresql://user@localhost:
5433/mydb?options=-c%
20synchronous_commit%
3Doff
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:
1051 postgresql://[
2001:db8::
1234]/database
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
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:
1066 postgresql:///dbname?host=/var/lib/postgresql
1067 postgresql://%
2Fvar%
2Flib%
2Fpostgresql/dbname
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.
1082 <sect3 id=
"libpq-multiple-hosts">
1083 <title>Specifying Multiple Hosts
</title>
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.
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.
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
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.
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.
1125 <sect2 id=
"libpq-paramkeywords">
1126 <title>Parameter Key Words
</title>
1129 The currently recognized parameter key words are:
1132 <varlistentry id=
"libpq-connect-host" xreflabel=
"host">
1133 <term><literal>host
</literal></term>
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>.
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.
1161 <varlistentry id=
"libpq-connect-hostaddr" xreflabel=
"hostaddr">
1162 <term><literal>hostaddr
</literal></term>
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
— or, if
1172 <literal>host
</literal> specifies an IP address, that value will be
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:
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.)
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.
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.
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"/>).
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.
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>.
1236 <varlistentry id=
"libpq-connect-port" xreflabel=
"port">
1237 <term><literal>port
</literal></term>
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.
1254 <varlistentry id=
"libpq-connect-dbname" xreflabel=
"dbname">
1255 <term><literal>dbname
</literal></term>
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
1266 <varlistentry id=
"libpq-connect-user" xreflabel=
"user">
1267 <term><literal>user
</literal></term>
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.
1277 <varlistentry id=
"libpq-connect-password" xreflabel=
"password">
1278 <term><literal>password
</literal></term>
1281 Password to be used if the server demands password authentication.
1286 <varlistentry id=
"libpq-connect-passfile" xreflabel=
"passfile">
1287 <term><literal>passfile
</literal></term>
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.)
1299 <varlistentry id=
"libpq-connect-require-auth" xreflabel=
"require_auth">
1300 <term><literal>require_auth
</literal></term>
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.
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.
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.)
1326 The following methods may be specified:
1330 <term><literal>password
</literal></term>
1333 The server must request plaintext password authentication.
1339 <term><literal>md5
</literal></term>
1342 The server must request MD5 hashed password authentication.
1348 <term><literal>gss
</literal></term>
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" />).
1360 <term><literal>sspi
</literal></term>
1363 The server must request Windows
<acronym>SSPI
</acronym>
1370 <term><literal>scram-sha-
256</literal></term>
1373 The server must successfully complete a SCRAM-SHA-
256 authentication
1374 exchange with the client.
1380 <term><literal>none
</literal></term>
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.)
1394 <varlistentry id=
"libpq-connect-channel-binding" xreflabel=
"channel_binding">
1395 <term><literal>channel_binding
</literal></term>
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>.
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.
1416 <varlistentry id=
"libpq-connect-connect-timeout" xreflabel=
"connect_timeout">
1417 <term><literal>connect_timeout
</literal></term>
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
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
1432 <varlistentry id=
"libpq-connect-client-encoding" xreflabel=
"client_encoding">
1433 <term><literal>client_encoding
</literal></term>
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
1447 <varlistentry id=
"libpq-connect-options" xreflabel=
"options">
1448 <term><literal>options
</literal></term>
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"/>.
1464 <varlistentry id=
"libpq-connect-application-name" xreflabel=
"application_name">
1465 <term><literal>application_name
</literal></term>
1468 Specifies a value for the
<xref linkend=
"guc-application-name"/>
1469 configuration parameter.
1474 <varlistentry id=
"libpq-connect-fallback-application-name" xreflabel=
"fallback_application_name">
1475 <term><literal>fallback_application_name
</literal></term>
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.
1490 <varlistentry id=
"libpq-keepalives" xreflabel=
"keepalives">
1491 <term><literal>keepalives
</literal></term>
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.
1502 <varlistentry id=
"libpq-keepalives-idle" xreflabel=
"keepalives_idle">
1503 <term><literal>keepalives_idle
</literal></term>
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.
1517 <varlistentry id=
"libpq-keepalives-interval" xreflabel=
"keepalives_interval">
1518 <term><literal>keepalives_interval
</literal></term>
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.
1532 <varlistentry id=
"libpq-keepalives-count" xreflabel=
"keepalives_count">
1533 <term><literal>keepalives_count
</literal></term>
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
1547 <varlistentry id=
"libpq-tcp-user-timeout" xreflabel=
"tcp_user_timeout">
1548 <term><literal>tcp_user_timeout
</literal></term>
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.
1561 <varlistentry id=
"libpq-connect-replication" xreflabel=
"replication">
1562 <term><literal>replication
</literal></term>
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"/>.
1574 The following values, which are case-insensitive, are supported:
1578 <literal>true
</literal>,
<literal>on
</literal>,
1579 <literal>yes
</literal>,
<literal>1</literal>
1583 The connection goes into physical replication mode.
1589 <term><literal>database
</literal></term>
1592 The connection goes into logical replication mode, connecting to
1593 the database specified in the
<literal>dbname
</literal> parameter.
1600 <literal>false
</literal>,
<literal>off
</literal>,
1601 <literal>no
</literal>,
<literal>0</literal>
1605 The connection is a regular one, which is the default behavior.
1613 In physical or logical replication mode, only the simple query protocol
1619 <varlistentry id=
"libpq-connect-gssencmode" xreflabel=
"gssencmode">
1620 <term><literal>gssencmode
</literal></term>
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:
1629 <term><literal>disable
</literal></term>
1632 only try a non-
<acronym>GSSAPI
</acronym>-encrypted connection
1638 <term><literal>prefer
</literal> (default)
</term>
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.
1653 <term><literal>require
</literal></term>
1656 only try a
<acronym>GSSAPI
</acronym>-encrypted connection
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>
1676 <varlistentry id=
"libpq-connect-sslmode" xreflabel=
"sslmode">
1677 <term><literal>sslmode
</literal></term>
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:
1686 <term><literal>disable
</literal></term>
1689 only try a non-
<acronym>SSL
</acronym> connection
1695 <term><literal>allow
</literal></term>
1698 first try a non-
<acronym>SSL
</acronym> connection; if that
1699 fails, try an
<acronym>SSL
</acronym> connection
1705 <term><literal>prefer
</literal> (default)
</term>
1708 first try an
<acronym>SSL
</acronym> connection; if that fails,
1709 try a non-
<acronym>SSL
</acronym> connection
1715 <term><literal>require
</literal></term>
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
1726 <term><literal>verify-ca
</literal></term>
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>)
1737 <term><literal>verify-full
</literal></term>
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
1749 See
<xref linkend=
"libpq-ssl"/> for a detailed description of how
1754 <literal>sslmode
</literal> is ignored for Unix domain socket
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>
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>.
1778 <varlistentry id=
"libpq-connect-requiressl" xreflabel=
"requiressl">
1779 <term><literal>requiressl
</literal></term>
1782 This option is deprecated in favor of the
<literal>sslmode
</literal>
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.
1800 <varlistentry id=
"libpq-connect-sslnegotiation" xreflabel=
"sslnegotiation">
1801 <term><literal>sslnegotiation
</literal></term>
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
1820 <term><literal>postgres
</literal></term>
1823 perform
<productname>PostgreSQL
</productname> protocol
1824 negotiation. This is the default if the option is not provided.
1830 <term><literal>direct
</literal></term>
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
1845 <varlistentry id=
"libpq-connect-sslcompression" xreflabel=
"sslcompression">
1846 <term><literal>sslcompression
</literal></term>
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.
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.
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
1873 <varlistentry id=
"libpq-connect-sslcert" xreflabel=
"sslcert">
1874 <term><literal>sslcert
</literal></term>
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.
1885 <varlistentry id=
"libpq-connect-sslkey" xreflabel=
"sslkey">
1886 <term><literal>sslkey
</literal></term>
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.
1902 <varlistentry id=
"libpq-connect-sslpassword" xreflabel=
"sslpassword">
1903 <term><literal>sslpassword
</literal></term>
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.
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>.
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.
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.
1934 <varlistentry id=
"libpq-connect-sslcertmode" xreflabel=
"sslcertmode">
1935 <term><literal>sslcertmode
</literal></term>
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
1944 <term><literal>disable
</literal></term>
1947 A client certificate is never sent, even if one is available
1948 (default location or provided via
1949 <xref linkend=
"libpq-connect-sslcert" />).
1955 <term><literal>allow
</literal> (default)
</term>
1958 A certificate may be sent, if the server requests one and the
1959 client has one to send.
1965 <term><literal>require
</literal></term>
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.
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
1990 <varlistentry id=
"libpq-connect-sslrootcert" xreflabel=
"sslrootcert">
1991 <term><literal>sslrootcert
</literal></term>
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>.
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.
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.
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.
2027 <varlistentry id=
"libpq-connect-sslcrl" xreflabel=
"sslcrl">
2028 <term><literal>sslcrl
</literal></term>
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
2038 <filename>~/.postgresql/root.crl
</filename>.
2043 <varlistentry id=
"libpq-connect-sslcrldir" xreflabel=
"sslcrldir">
2044 <term><literal>sslcrldir
</literal></term>
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.
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.
2061 Both
<literal>sslcrl
</literal> and
<literal>sslcrldir
</literal> can be
2067 <varlistentry id=
"libpq-connect-sslsni" xreflabel=
"sslsni">
2068 <term><literal>sslsni
</literal><indexterm><primary>Server Name Indication
</primary></indexterm></term>
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.
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
2089 <varlistentry id=
"libpq-connect-requirepeer" xreflabel=
"requirepeer">
2090 <term><literal>requirepeer
</literal></term>
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"/>.
2112 <varlistentry id=
"libpq-connect-ssl-min-protocol-version" xreflabel=
"ssl_min_protocol_version">
2113 <term><literal>ssl_min_protocol_version
</literal></term>
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.
2128 <varlistentry id=
"libpq-connect-ssl-max-protocol-version" xreflabel=
"ssl_max_protocol_version">
2129 <term><literal>ssl_max_protocol_version
</literal></term>
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.
2146 <varlistentry id=
"libpq-connect-krbsrvname" xreflabel=
"krbsrvname">
2147 <term><literal>krbsrvname
</literal></term>
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>).
2167 <varlistentry id=
"libpq-connect-gsslib" xreflabel=
"gsslib">
2168 <term><literal>gsslib
</literal></term>
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.
2180 <varlistentry id=
"libpq-connect-gssdelegation" xreflabel=
"gssdelegation">
2181 <term><literal>gssdelegation
</literal></term>
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.
2192 <varlistentry id=
"libpq-connect-service" xreflabel=
"service">
2193 <term><literal>service
</literal></term>
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"/>.
2204 <varlistentry id=
"libpq-connect-target-session-attrs" xreflabel=
"target_session_attrs">
2205 <term><literal>target_session_attrs
</literal></term>
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:
2215 <term><literal>any
</literal> (default)
</term>
2218 any successful connection is acceptable
2224 <term><literal>read-write
</literal></term>
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>)
2236 <term><literal>read-only
</literal></term>
2239 session must not accept read-write transactions by default (the
2246 <term><literal>primary
</literal></term>
2249 server must not be in hot standby mode
2255 <term><literal>standby
</literal></term>
2258 server must be in hot standby mode
2264 <term><literal>prefer-standby
</literal></term>
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>
2278 <varlistentry id=
"libpq-connect-load-balance-hosts" xreflabel=
"load_balance_hosts">
2279 <term><literal>load_balance_hosts
</literal></term>
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:
2293 <term><literal>disable
</literal> (default)
</term>
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.
2304 <term><literal>random
</literal></term>
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.
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.
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.
2343 <sect1 id=
"libpq-status">
2344 <title>Connection Status Functions
</title>
2347 These functions can be used to interrogate the status
2348 of an existing database connection object.
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
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.
2373 <varlistentry id=
"libpq-PQdb">
2374 <term><function>PQdb
</function><indexterm><primary>PQdb
</primary></indexterm></term>
2378 Returns the database name of the connection.
2380 char *PQdb(const PGconn *conn);
2386 <varlistentry id=
"libpq-PQuser">
2387 <term><function>PQuser
</function><indexterm><primary>PQuser
</primary></indexterm></term>
2391 Returns the user name of the connection.
2393 char *PQuser(const PGconn *conn);
2399 <varlistentry id=
"libpq-PQpass">
2400 <term><function>PQpass
</function><indexterm><primary>PQpass
</primary></indexterm></term>
2404 Returns the password of the connection.
2406 char *PQpass(const PGconn *conn);
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"/>.
2423 <varlistentry id=
"libpq-PQhost">
2424 <term><function>PQhost
</function><indexterm><primary>PQhost
</primary></indexterm></term>
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>.)
2434 char *PQhost(const PGconn *conn);
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.
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.
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"/>.
2465 <varlistentry id=
"libpq-PQhostaddr">
2466 <term><function>PQhostaddr
</function><indexterm><primary>PQhostaddr
</primary></indexterm></term>
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>
2475 char *PQhostaddr(const PGconn *conn);
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.
2489 <varlistentry id=
"libpq-PQport">
2490 <term><function>PQport
</function><indexterm><primary>PQport
</primary></indexterm></term>
2494 Returns the port of the active connection.
2497 char *PQport(const PGconn *conn);
2502 If multiple ports were specified in the connection parameters,
2503 <xref linkend=
"libpq-PQport"/> returns the port actually connected to.
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.
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"/>.
2523 <varlistentry id=
"libpq-PQtty">
2524 <term><function>PQtty
</function><indexterm><primary>PQtty
</primary></indexterm></term>
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>.
2534 char *PQtty(const PGconn *conn);
2540 <varlistentry id=
"libpq-PQoptions">
2541 <term><function>PQoptions
</function><indexterm><primary>PQoptions
</primary></indexterm></term>
2545 Returns the command-line options passed in the connection request.
2547 char *PQoptions(const PGconn *conn);
2556 The following functions return status data that can change as operations
2557 are executed on the
<structname>PGconn
</structname> object.
2560 <varlistentry id=
"libpq-PQstatus">
2561 <term><function>PQstatus
</function><indexterm><primary>PQstatus
</primary></indexterm></term>
2565 Returns the status of the connection.
2567 ConnStatusType PQstatus(const PGconn *conn);
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"/>.
2587 See the entry for
<xref linkend=
"libpq-PQconnectStartParams"/>,
<function>PQconnectStart
</function>
2588 and
<function>PQconnectPoll
</function> with regards to other status codes that
2594 <varlistentry id=
"libpq-PQtransactionStatus">
2595 <term><function>PQtransactionStatus
</function><indexterm><primary>PQtransactionStatus
</primary></indexterm></term>
2599 Returns the current in-transaction status of the server.
2602 PGTransactionStatusType PQtransactionStatus(const PGconn *conn);
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.
2616 <varlistentry id=
"libpq-PQparameterStatus">
2617 <term><function>PQparameterStatus
</function><indexterm><primary>PQparameterStatus
</primary></indexterm></term>
2621 Looks up a current parameter setting of the server.
2624 const char *PQparameterStatus(const PGconn *conn, const char *paramName);
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.
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>search_path
</varname></member>
2647 <member><varname>server_encoding
</varname></member>
2648 <member><varname>server_version
</varname></member>
2649 <member><varname>session_authorization
</varname></member>
2650 <member><varname>standard_conforming_strings
</varname></member>
2651 <member><varname>TimeZone
</varname></member>
2653 (
<varname>default_transaction_read_only
</varname> and
2654 <varname>in_hot_standby
</varname> were not reported by releases before
2655 14;
<varname>scram_iterations
</varname> was not reported by releases
2656 before
16;
<varname>search_path
</varname> was not reported by releases
2659 <varname>server_version
</varname>,
2660 <varname>server_encoding
</varname> and
2661 <varname>integer_datetimes
</varname>
2662 cannot change after startup.
2666 If no value for
<varname>standard_conforming_strings
</varname> is reported,
2667 applications can assume it is
<literal>off
</literal>, that is, backslashes
2668 are treated as escapes in string literals. Also, the presence of
2669 this parameter can be taken as an indication that the escape string
2670 syntax (
<literal>E'...'
</literal>) is accepted.
2674 Although the returned pointer is declared
<literal>const
</literal>, it in fact
2675 points to mutable storage associated with the
<literal>PGconn
</literal> structure.
2676 It is unwise to assume the pointer will remain valid across queries.
2681 <varlistentry id=
"libpq-PQfullProtocolVersion">
2682 <term><function>PQfullProtocolVersion
</function><indexterm><primary>PQfullProtocolVersion
</primary></indexterm></term>
2686 Interrogates the frontend/backend protocol being used.
2688 int PQfullProtocolVersion(const PGconn *conn);
2690 Applications might wish to use this function to determine whether certain
2691 features are supported. The result is formed by multiplying the server's
2692 major version number by
10000 and adding the minor version number. For
2693 example, version
3.2 would be returned as
30002, and version
4.0 would
2694 be returned as
40000. Zero is returned if the connection is bad. The
3.0
2695 protocol is supported by
<productname>PostgreSQL
</productname> server
2696 versions
7.4 and above.
2699 The protocol version will not change after connection startup is
2700 complete, but it could theoretically change during a connection reset.
2705 <varlistentry id=
"libpq-PQprotocolVersion">
2706 <term><function>PQprotocolVersion
</function><indexterm><primary>PQprotocolVersion
</primary></indexterm></term>
2710 Interrogates the frontend/backend protocol major version.
2712 int PQprotocolVersion(const PGconn *conn);
2714 Unlike
<xref linkend=
"libpq-PQfullProtocolVersion"/>, this returns only
2715 the major protocol version in use, but it is supported by a wider range
2716 of libpq releases back to version
7.4. Currently, the possible values are
2717 3 (
3.0 protocol), or zero (connection bad). Prior to release version
2718 14.0, libpq could additionally return
2 (
2.0 protocol).
2723 <varlistentry id=
"libpq-PQserverVersion">
2724 <term><function>PQserverVersion
</function><indexterm><primary>PQserverVersion
</primary></indexterm></term>
2728 Returns an integer representing the server version.
2730 int PQserverVersion(const PGconn *conn);
2735 Applications might use this function to determine the version of the
2736 database server they are connected to. The result is formed by
2737 multiplying the server's major version number by
10000 and adding
2738 the minor version number. For example, version
10.1 will be
2739 returned as
100001, and version
11.0 will be returned as
110000.
2740 Zero is returned if the connection is bad.
2744 Prior to major version
10,
<productname>PostgreSQL
</productname> used
2745 three-part version numbers in which the first two parts together
2746 represented the major version. For those
2747 versions,
<xref linkend=
"libpq-PQserverVersion"/> uses two digits for each
2748 part; for example version
9.1.5 will be returned as
90105, and
2749 version
9.2.0 will be returned as
90200.
2753 Therefore, for purposes of determining feature compatibility,
2754 applications should divide the result of
<xref linkend=
"libpq-PQserverVersion"/>
2755 by
100 not
10000 to determine a logical major version number.
2756 In all release series, only the last two digits differ between
2757 minor releases (bug-fix releases).
2762 <varlistentry id=
"libpq-PQerrorMessage">
2764 <function>PQerrorMessage
</function><indexterm><primary>PQerrorMessage
</primary></indexterm>
2765 <indexterm><primary>error message
</primary><secondary>in
<structname>PGconn
</structname></secondary></indexterm>
2770 Returns the error message most recently generated by
2771 an operation on the connection.
2774 char *PQerrorMessage(const PGconn *conn);
2779 Nearly all
<application>libpq
</application> functions will set a message for
2780 <xref linkend=
"libpq-PQerrorMessage"/> if they fail. Note that by
2781 <application>libpq
</application> convention, a nonempty
2782 <xref linkend=
"libpq-PQerrorMessage"/> result can consist of multiple lines,
2783 and will include a trailing newline. The caller should not free
2784 the result directly. It will be freed when the associated
2785 <structname>PGconn
</structname> handle is passed to
2786 <xref linkend=
"libpq-PQfinish"/>. The result string should not be
2787 expected to remain the same across operations on the
2788 <literal>PGconn
</literal> structure.
2793 <varlistentry id=
"libpq-PQsocket">
2794 <term><function>PQsocket
</function><indexterm><primary>PQsocket
</primary></indexterm></term>
2797 Obtains the file descriptor number of the connection socket to
2798 the server. A valid descriptor will be greater than or equal
2799 to
0; a result of -
1 indicates that no server connection is
2800 currently open. (This will not change during normal operation,
2801 but could change during connection setup or reset.)
2804 int PQsocket(const PGconn *conn);
2811 <varlistentry id=
"libpq-PQbackendPID">
2812 <term><function>PQbackendPID
</function><indexterm><primary>PQbackendPID
</primary></indexterm></term>
2815 Returns the process
<acronym>ID
</acronym> (PID)
<indexterm>
2816 <primary>PID
</primary>
2817 <secondary>determining PID of server process
</secondary>
2818 <tertiary>in libpq
</tertiary>
2820 of the backend process handling this connection.
2823 int PQbackendPID(const PGconn *conn);
2828 The backend
<acronym>PID
</acronym> is useful for debugging
2829 purposes and for comparison to
<command>NOTIFY
</command>
2830 messages (which include the
<acronym>PID
</acronym> of the
2831 notifying backend process). Note that the
2832 <acronym>PID
</acronym> belongs to a process executing on the
2833 database server host, not the local host!
2838 <varlistentry id=
"libpq-PQconnectionNeedsPassword">
2839 <term><function>PQconnectionNeedsPassword
</function><indexterm><primary>PQconnectionNeedsPassword
</primary></indexterm></term>
2842 Returns true (
1) if the connection authentication method
2843 required a password, but none was available.
2844 Returns false (
0) if not.
2847 int PQconnectionNeedsPassword(const PGconn *conn);
2852 This function can be applied after a failed connection attempt
2853 to decide whether to prompt the user for a password.
2858 <varlistentry id=
"libpq-PQconnectionUsedPassword">
2859 <term><function>PQconnectionUsedPassword
</function><indexterm><primary>PQconnectionUsedPassword
</primary></indexterm></term>
2862 Returns true (
1) if the connection authentication method
2863 used a password. Returns false (
0) if not.
2866 int PQconnectionUsedPassword(const PGconn *conn);
2871 This function can be applied after either a failed or successful
2872 connection attempt to detect whether the server demanded a password.
2877 <varlistentry id=
"libpq-PQconnectionUsedGSSAPI">
2878 <term><function>PQconnectionUsedGSSAPI
</function><indexterm><primary>PQconnectionUsedGSSAPI
</primary></indexterm></term>
2881 Returns true (
1) if the connection authentication method
2882 used GSSAPI. Returns false (
0) if not.
2885 int PQconnectionUsedGSSAPI(const PGconn *conn);
2890 This function can be applied to detect whether the connection was
2891 authenticated with GSSAPI.
2899 The following functions return information related to SSL. This information
2900 usually doesn't change after a connection is established.
2903 <varlistentry id=
"libpq-PQsslInUse">
2904 <term><function>PQsslInUse
</function><indexterm><primary>PQsslInUse
</primary></indexterm></term>
2907 Returns true (
1) if the connection uses SSL, false (
0) if not.
2910 int PQsslInUse(const PGconn *conn);
2917 <varlistentry id=
"libpq-PQsslAttribute">
2918 <term><function>PQsslAttribute
</function><indexterm><primary>PQsslAttribute
</primary></indexterm></term>
2921 Returns SSL-related information about the connection.
2924 const char *PQsslAttribute(const PGconn *conn, const char *attribute_name);
2929 The list of available attributes varies depending on the SSL library
2930 being used and the type of connection. Returns NULL if the connection
2931 does not use SSL or the specified attribute name is not defined for the
2936 The following attributes are commonly available:
2939 <term><literal>library
</literal></term>
2942 Name of the SSL implementation in use. (Currently, only
2943 <literal>"OpenSSL"</literal> is implemented)
2948 <term><literal>protocol
</literal></term>
2951 SSL/TLS version in use. Common values
2952 are
<literal>"TLSv1"</literal>,
<literal>"TLSv1.1"</literal>
2953 and
<literal>"TLSv1.2"</literal>, but an implementation may
2954 return other strings if some other protocol is used.
2959 <term><literal>key_bits
</literal></term>
2962 Number of key bits used by the encryption algorithm.
2967 <term><literal>cipher
</literal></term>
2970 A short name of the ciphersuite used, e.g.,
2971 <literal>"DHE-RSA-DES-CBC3-SHA"</literal>. The names are specific
2972 to each SSL implementation.
2977 <term><literal>compression
</literal></term>
2980 Returns
"on" if SSL compression is in use, else it returns
"off".
2985 <term><literal>alpn
</literal></term>
2988 Application protocol selected by the TLS Application-Layer
2989 Protocol Negotiation (ALPN) extension. The only protocol
2990 supported by libpq is
<literal>postgresql
</literal>, so this is
2991 mainly useful for checking whether the server supported ALPN or
2992 not. Empty string if ALPN was not used.
3000 As a special case, the
<literal>library
</literal> attribute may be
3001 queried without a connection by passing NULL as
3002 the
<literal>conn
</literal> argument. The result will be the default
3003 SSL library name, or NULL if
<application>libpq
</application> was
3004 compiled without any SSL support. (Prior
3005 to
<productname>PostgreSQL
</productname> version
15, passing NULL as
3006 the
<literal>conn
</literal> argument always resulted in NULL.
3007 Client programs needing to differentiate between the newer and older
3008 implementations of this case may check the
3009 <literal>LIBPQ_HAS_SSL_LIBRARY_DETECTION
</literal> feature macro.)
3014 <varlistentry id=
"libpq-PQsslAttributeNames">
3015 <term><function>PQsslAttributeNames
</function><indexterm><primary>PQsslAttributeNames
</primary></indexterm></term>
3018 Returns an array of SSL attribute names that can be used
3019 in
<function>PQsslAttribute()
</function>.
3020 The array is terminated by a NULL pointer.
3022 const char * const * PQsslAttributeNames(const PGconn *conn);
3027 If
<literal>conn
</literal> is NULL, the attributes available for the
3028 default SSL library are returned, or an empty list
3029 if
<application>libpq
</application> was compiled without any SSL
3030 support. If
<literal>conn
</literal> is not NULL, the attributes
3031 available for the SSL library in use for the connection are returned,
3032 or an empty list if the connection is not encrypted.
3037 <varlistentry id=
"libpq-PQsslStruct">
3038 <term><function>PQsslStruct
</function><indexterm><primary>PQsslStruct
</primary></indexterm></term>
3041 Returns a pointer to an SSL-implementation-specific object describing
3042 the connection. Returns NULL if the connection is not encrypted
3043 or the requested type of object is not available from the connection's
3046 void *PQsslStruct(const PGconn *conn, const char *struct_name);
3050 The struct(s) available depend on the SSL implementation in use.
3051 For
<productname>OpenSSL
</productname>, there is one struct,
3052 available under the name
<literal>OpenSSL
</literal>,
3053 and it returns a pointer to
3054 <productname>OpenSSL
</productname>'s
<literal>SSL
</literal> struct.
3055 To use this function, code along the following lines could be used:
3056 <programlisting><![CDATA[
3057 #include
<libpq-fe.h
>
3058 #include
<openssl/ssl.h
>
3064 dbconn = PQconnectdb(...);
3067 ssl = PQsslStruct(dbconn,
"OpenSSL");
3070 /* use OpenSSL functions to access ssl */
3072 ]]
></programlisting>
3075 This structure can be used to verify encryption levels, check server
3076 certificates, and more. Refer to the
<productname>OpenSSL
</productname>
3077 documentation for information about this structure.
3082 <varlistentry id=
"libpq-PQgetssl">
3083 <term><function>PQgetssl
</function><indexterm><primary>PQgetssl
</primary></indexterm></term>
3086 <indexterm><primary>SSL
</primary><secondary sortas=
"libpq">in libpq
</secondary></indexterm>
3087 Returns the SSL structure used in the connection, or NULL
3088 if SSL is not in use.
3091 void *PQgetssl(const PGconn *conn);
3096 This function is equivalent to
<literal>PQsslStruct(conn,
"OpenSSL")
</literal>. It should
3097 not be used in new applications, because the returned struct is
3098 specific to
<productname>OpenSSL
</productname> and will not be
3099 available if another
<acronym>SSL
</acronym> implementation is used.
3100 To check if a connection uses SSL, call
3101 <xref linkend=
"libpq-PQsslInUse"/> instead, and for more details about the
3102 connection, use
<xref linkend=
"libpq-PQsslAttribute"/>.
3112 <sect1 id=
"libpq-exec">
3113 <title>Command Execution Functions
</title>
3116 Once a connection to a database server has been successfully
3117 established, the functions described here are used to perform
3118 SQL queries and commands.
3121 <sect2 id=
"libpq-exec-main">
3122 <title>Main Functions
</title>
3126 <varlistentry id=
"libpq-PQexec">
3127 <term><function>PQexec
</function><indexterm><primary>PQexec
</primary></indexterm></term>
3131 Submits a command to the server and waits for the result.
3134 PGresult *PQexec(PGconn *conn, const char *command);
3139 Returns a
<structname>PGresult
</structname> pointer or possibly a null
3140 pointer. A non-null pointer will generally be returned except in
3141 out-of-memory conditions or serious errors such as inability to send
3142 the command to the server. The
<xref linkend=
"libpq-PQresultStatus"/> function
3143 should be called to check the return value for any errors (including
3144 the value of a null pointer, in which case it will return
3145 <symbol>PGRES_FATAL_ERROR
</symbol>). Use
3146 <xref linkend=
"libpq-PQerrorMessage"/> to get more information about such
3153 The command string can include multiple SQL commands
3154 (separated by semicolons). Multiple queries sent in a single
3155 <xref linkend=
"libpq-PQexec"/> call are processed in a single transaction, unless
3156 there are explicit
<command>BEGIN
</command>/
<command>COMMIT
</command>
3157 commands included in the query string to divide it into multiple
3158 transactions. (See
<xref linkend=
"protocol-flow-multi-statement"/>
3159 for more details about how the server handles multi-query strings.)
3160 Note however that the returned
3161 <structname>PGresult
</structname> structure describes only the result
3162 of the last command executed from the string. Should one of the
3163 commands fail, processing of the string stops with it and the returned
3164 <structname>PGresult
</structname> describes the error condition.
3169 <varlistentry id=
"libpq-PQexecParams">
3170 <term><function>PQexecParams
</function><indexterm><primary>PQexecParams
</primary></indexterm></term>
3174 Submits a command to the server and waits for the result,
3175 with the ability to pass parameters separately from the SQL
3179 PGresult *PQexecParams(PGconn *conn,
3180 const char *command,
3182 const Oid *paramTypes,
3183 const char * const *paramValues,
3184 const int *paramLengths,
3185 const int *paramFormats,
3191 <xref linkend=
"libpq-PQexecParams"/> is like
<xref linkend=
"libpq-PQexec"/>, but offers additional
3192 functionality: parameter values can be specified separately from the command
3193 string proper, and query results can be requested in either text or binary
3198 The function arguments are:
3202 <term><parameter>conn
</parameter></term>
3206 The connection object to send the command through.
3212 <term><parameter>command
</parameter></term>
3215 The SQL command string to be executed. If parameters are used,
3216 they are referred to in the command string as
<literal>$
1</literal>,
3217 <literal>$
2</literal>, etc.
3223 <term><parameter>nParams
</parameter></term>
3226 The number of parameters supplied; it is the length of the arrays
3227 <parameter>paramTypes[]
</parameter>,
<parameter>paramValues[]
</parameter>,
3228 <parameter>paramLengths[]
</parameter>, and
<parameter>paramFormats[]
</parameter>. (The
3229 array pointers can be
<symbol>NULL
</symbol> when
<parameter>nParams
</parameter>
3236 <term><parameter>paramTypes[]
</parameter></term>
3239 Specifies, by OID, the data types to be assigned to the
3240 parameter symbols. If
<parameter>paramTypes
</parameter> is
3241 <symbol>NULL
</symbol>, or any particular element in the array
3242 is zero, the server infers a data type for the parameter symbol
3243 in the same way it would do for an untyped literal string.
3249 <term><parameter>paramValues[]
</parameter></term>
3252 Specifies the actual values of the parameters. A null pointer
3253 in this array means the corresponding parameter is null;
3254 otherwise the pointer points to a zero-terminated text string
3255 (for text format) or binary data in the format expected by the
3256 server (for binary format).
3262 <term><parameter>paramLengths[]
</parameter></term>
3265 Specifies the actual data lengths of binary-format parameters.
3266 It is ignored for null parameters and text-format parameters.
3267 The array pointer can be null when there are no binary parameters.
3273 <term><parameter>paramFormats[]
</parameter></term>
3276 Specifies whether parameters are text (put a zero in the
3277 array entry for the corresponding parameter) or binary (put
3278 a one in the array entry for the corresponding parameter).
3279 If the array pointer is null then all parameters are presumed
3283 Values passed in binary format require knowledge of
3284 the internal representation expected by the backend.
3285 For example, integers must be passed in network byte
3286 order. Passing
<type>numeric
</type> values requires
3287 knowledge of the server storage format, as implemented
3289 <filename>src/backend/utils/adt/numeric.c::numeric_send()
</filename> and
3290 <filename>src/backend/utils/adt/numeric.c::numeric_recv()
</filename>.
3296 <term><parameter>resultFormat
</parameter></term>
3299 Specify zero to obtain results in text format, or one to obtain
3300 results in binary format. (There is not currently a provision
3301 to obtain different result columns in different formats,
3302 although that is possible in the underlying protocol.)
3314 The primary advantage of
<xref linkend=
"libpq-PQexecParams"/> over
3315 <xref linkend=
"libpq-PQexec"/> is that parameter values can be separated from the
3316 command string, thus avoiding the need for tedious and error-prone
3317 quoting and escaping.
3321 Unlike
<xref linkend=
"libpq-PQexec"/>,
<xref linkend=
"libpq-PQexecParams"/> allows at most
3322 one SQL command in the given string. (There can be semicolons in it,
3323 but not more than one nonempty command.) This is a limitation of the
3324 underlying protocol, but has some usefulness as an extra defense against
3325 SQL-injection attacks.
3330 Specifying parameter types via OIDs is tedious, particularly if you prefer
3331 not to hard-wire particular OID values into your program. However, you can
3332 avoid doing so even in cases where the server by itself cannot determine the
3333 type of the parameter, or chooses a different type than you want. In the
3334 SQL command text, attach an explicit cast to the parameter symbol to show what
3335 data type you will send. For example:
3337 SELECT * FROM mytable WHERE x = $
1::bigint;
3339 This forces parameter
<literal>$
1</literal> to be treated as
<type>bigint
</type>, whereas
3340 by default it would be assigned the same type as
<literal>x
</literal>. Forcing the
3341 parameter type decision, either this way or by specifying a numeric type OID,
3342 is strongly recommended when sending parameter values in binary format, because
3343 binary format has less redundancy than text format and so there is less chance
3344 that the server will detect a type mismatch mistake for you.
3350 <varlistentry id=
"libpq-PQprepare">
3351 <term><function>PQprepare
</function><indexterm><primary>PQprepare
</primary></indexterm></term>
3355 Submits a request to create a prepared statement with the
3356 given parameters, and waits for completion.
3358 PGresult *PQprepare(PGconn *conn,
3359 const char *stmtName,
3362 const Oid *paramTypes);
3367 <xref linkend=
"libpq-PQprepare"/> creates a prepared statement for later
3368 execution with
<xref linkend=
"libpq-PQexecPrepared"/>. This feature allows
3369 commands to be executed repeatedly without being parsed and
3370 planned each time; see
<xref linkend=
"sql-prepare"/> for details.
3374 The function creates a prepared statement named
3375 <parameter>stmtName
</parameter> from the
<parameter>query
</parameter> string, which
3376 must contain a single SQL command.
<parameter>stmtName
</parameter> can be
3377 <literal>""</literal> to create an unnamed statement, in which case any
3378 pre-existing unnamed statement is automatically replaced; otherwise
3379 it is an error if the statement name is already defined in the
3380 current session. If any parameters are used, they are referred
3381 to in the query as
<literal>$
1</literal>,
<literal>$
2</literal>, etc.
3382 <parameter>nParams
</parameter> is the number of parameters for which types
3383 are pre-specified in the array
<parameter>paramTypes[]
</parameter>. (The
3384 array pointer can be
<symbol>NULL
</symbol> when
3385 <parameter>nParams
</parameter> is zero.)
<parameter>paramTypes[]
</parameter>
3386 specifies, by OID, the data types to be assigned to the parameter
3387 symbols. If
<parameter>paramTypes
</parameter> is
<symbol>NULL
</symbol>,
3388 or any particular element in the array is zero, the server assigns
3389 a data type to the parameter symbol in the same way it would do
3390 for an untyped literal string. Also, the query can use parameter
3391 symbols with numbers higher than
<parameter>nParams
</parameter>; data types
3392 will be inferred for these symbols as well. (See
3393 <xref linkend=
"libpq-PQdescribePrepared"/> for a means to find out
3394 what data types were inferred.)
3398 As with
<xref linkend=
"libpq-PQexec"/>, the result is normally a
3399 <structname>PGresult
</structname> object whose contents indicate
3400 server-side success or failure. A null result indicates
3401 out-of-memory or inability to send the command at all. Use
3402 <xref linkend=
"libpq-PQerrorMessage"/> to get more information about
3409 Prepared statements for use with
<xref linkend=
"libpq-PQexecPrepared"/> can also
3410 be created by executing SQL
<xref linkend=
"sql-prepare"/>
3416 <varlistentry id=
"libpq-PQexecPrepared">
3417 <term><function>PQexecPrepared
</function><indexterm><primary>PQexecPrepared
</primary></indexterm></term>
3421 Sends a request to execute a prepared statement with given
3422 parameters, and waits for the result.
3424 PGresult *PQexecPrepared(PGconn *conn,
3425 const char *stmtName,
3427 const char * const *paramValues,
3428 const int *paramLengths,
3429 const int *paramFormats,
3435 <xref linkend=
"libpq-PQexecPrepared"/> is like
<xref linkend=
"libpq-PQexecParams"/>,
3436 but the command to be executed is specified by naming a
3437 previously-prepared statement, instead of giving a query string.
3438 This feature allows commands that will be used repeatedly to be
3439 parsed and planned just once, rather than each time they are
3440 executed. The statement must have been prepared previously in
3441 the current session.
3445 The parameters are identical to
<xref linkend=
"libpq-PQexecParams"/>, except that the
3446 name of a prepared statement is given instead of a query string, and the
3447 <parameter>paramTypes[]
</parameter> parameter is not present (it is not needed since
3448 the prepared statement's parameter types were determined when it was created).
3453 <varlistentry id=
"libpq-PQdescribePrepared">
3454 <term><function>PQdescribePrepared
</function><indexterm><primary>PQdescribePrepared
</primary></indexterm></term>
3458 Submits a request to obtain information about the specified
3459 prepared statement, and waits for completion.
3461 PGresult *PQdescribePrepared(PGconn *conn, const char *stmtName);
3466 <xref linkend=
"libpq-PQdescribePrepared"/> allows an application to obtain
3467 information about a previously prepared statement.
3471 <parameter>stmtName
</parameter> can be
<literal>""</literal> or
<symbol>NULL
</symbol> to reference
3472 the unnamed statement, otherwise it must be the name of an existing
3473 prepared statement. On success, a
<structname>PGresult
</structname> with
3474 status
<literal>PGRES_COMMAND_OK
</literal> is returned. The
3475 functions
<xref linkend=
"libpq-PQnparams"/> and
3476 <xref linkend=
"libpq-PQparamtype"/> can be applied to this
3477 <structname>PGresult
</structname> to obtain information about the parameters
3478 of the prepared statement, and the functions
3479 <xref linkend=
"libpq-PQnfields"/>,
<xref linkend=
"libpq-PQfname"/>,
3480 <xref linkend=
"libpq-PQftype"/>, etc. provide information about the
3481 result columns (if any) of the statement.
3486 <varlistentry id=
"libpq-PQdescribePortal">
3487 <term><function>PQdescribePortal
</function><indexterm><primary>PQdescribePortal
</primary></indexterm></term>
3491 Submits a request to obtain information about the specified
3492 portal, and waits for completion.
3494 PGresult *PQdescribePortal(PGconn *conn, const char *portalName);
3499 <xref linkend=
"libpq-PQdescribePortal"/> allows an application to obtain
3500 information about a previously created portal.
3501 (
<application>libpq
</application> does not provide any direct access to
3502 portals, but you can use this function to inspect the properties
3503 of a cursor created with a
<command>DECLARE CURSOR
</command> SQL command.)
3507 <parameter>portalName
</parameter> can be
<literal>""</literal> or
<symbol>NULL
</symbol> to reference
3508 the unnamed portal, otherwise it must be the name of an existing
3509 portal. On success, a
<structname>PGresult
</structname> with status
3510 <literal>PGRES_COMMAND_OK
</literal> is returned. The functions
3511 <xref linkend=
"libpq-PQnfields"/>,
<xref linkend=
"libpq-PQfname"/>,
3512 <xref linkend=
"libpq-PQftype"/>, etc. can be applied to the
3513 <structname>PGresult
</structname> to obtain information about the result
3514 columns (if any) of the portal.
3519 <varlistentry id=
"libpq-PQclosePrepared">
3520 <term><function>PQclosePrepared
</function><indexterm><primary>PQclosePrepared
</primary></indexterm></term>
3524 Submits a request to close the specified prepared statement, and waits
3527 PGresult *PQclosePrepared(PGconn *conn, const char *stmtName);
3532 <xref linkend=
"libpq-PQclosePrepared"/> allows an application to close
3533 a previously prepared statement. Closing a statement releases all
3534 of its associated resources on the server and allows its name to be
3539 <parameter>stmtName
</parameter> can be
<literal>""</literal> or
3540 <symbol>NULL
</symbol> to reference the unnamed statement. It is fine
3541 if no statement exists with this name, in that case the operation is a
3542 no-op. On success, a
<structname>PGresult
</structname> with
3543 status
<literal>PGRES_COMMAND_OK
</literal> is returned.
3548 <varlistentry id=
"libpq-PQclosePortal">
3549 <term><function>PQclosePortal
</function><indexterm><primary>PQclosePortal
</primary></indexterm></term>
3553 Submits a request to close the specified portal, and waits for
3556 PGresult *PQclosePortal(PGconn *conn, const char *portalName);
3561 <xref linkend=
"libpq-PQclosePortal"/> allows an application to trigger
3562 a close of a previously created portal. Closing a portal releases all
3563 of its associated resources on the server and allows its name to be
3564 reused. (
<application>libpq
</application> does not provide any
3565 direct access to portals, but you can use this function to close a
3566 cursor created with a
<command>DECLARE CURSOR
</command> SQL command.)
3570 <parameter>portalName
</parameter> can be
<literal>""</literal> or
3571 <symbol>NULL
</symbol> to reference the unnamed portal. It is fine
3572 if no portal exists with this name, in that case the operation is a
3573 no-op. On success, a
<structname>PGresult
</structname> with status
3574 <literal>PGRES_COMMAND_OK
</literal> is returned.
3582 The
<structname>PGresult
</structname><indexterm><primary>PGresult
</primary></indexterm>
3583 structure encapsulates the result returned by the server.
3584 <application>libpq
</application> application programmers should be
3585 careful to maintain the
<structname>PGresult
</structname> abstraction.
3586 Use the accessor functions below to get at the contents of
3587 <structname>PGresult
</structname>. Avoid directly referencing the
3588 fields of the
<structname>PGresult
</structname> structure because they
3589 are subject to change in the future.
3592 <varlistentry id=
"libpq-PQresultStatus">
3593 <term><function>PQresultStatus
</function><indexterm><primary>PQresultStatus
</primary></indexterm></term>
3597 Returns the result status of the command.
3599 ExecStatusType PQresultStatus(const PGresult *res);
3604 <xref linkend=
"libpq-PQresultStatus"/> can return one of the following values:
3607 <varlistentry id=
"libpq-pgres-empty-query">
3608 <term><literal>PGRES_EMPTY_QUERY
</literal></term>
3611 The string sent to the server was empty.
3616 <varlistentry id=
"libpq-pgres-command-ok">
3617 <term><literal>PGRES_COMMAND_OK
</literal></term>
3620 Successful completion of a command returning no data.
3625 <varlistentry id=
"libpq-pgres-tuples-ok">
3626 <term><literal>PGRES_TUPLES_OK
</literal></term>
3629 Successful completion of a command returning data (such as
3630 a
<command>SELECT
</command> or
<command>SHOW
</command>).
3635 <varlistentry id=
"libpq-pgres-copy-out">
3636 <term><literal>PGRES_COPY_OUT
</literal></term>
3639 Copy Out (from server) data transfer started.
3644 <varlistentry id=
"libpq-pgres-copy-in">
3645 <term><literal>PGRES_COPY_IN
</literal></term>
3648 Copy In (to server) data transfer started.
3653 <varlistentry id=
"libpq-pgres-bad-response">
3654 <term><literal>PGRES_BAD_RESPONSE
</literal></term>
3657 The server's response was not understood.
3662 <varlistentry id=
"libpq-pgres-nonfatal-error">
3663 <term><literal>PGRES_NONFATAL_ERROR
</literal></term>
3666 A nonfatal error (a notice or warning) occurred.
3671 <varlistentry id=
"libpq-pgres-fatal-error">
3672 <term><literal>PGRES_FATAL_ERROR
</literal></term>
3675 A fatal error occurred.
3680 <varlistentry id=
"libpq-pgres-copy-both">
3681 <term><literal>PGRES_COPY_BOTH
</literal></term>
3684 Copy In/Out (to and from server) data transfer started. This
3685 feature is currently used only for streaming replication,
3686 so this status should not occur in ordinary applications.
3691 <varlistentry id=
"libpq-pgres-single-tuple">
3692 <term><literal>PGRES_SINGLE_TUPLE
</literal></term>
3695 The
<structname>PGresult
</structname> contains a single result tuple
3696 from the current command. This status occurs only when
3697 single-row mode has been selected for the query
3698 (see
<xref linkend=
"libpq-single-row-mode"/>).
3703 <varlistentry id=
"libpq-pgres-tuples-chunk">
3704 <term><literal>PGRES_TUPLES_CHUNK
</literal></term>
3707 The
<structname>PGresult
</structname> contains several result tuples
3708 from the current command. This status occurs only when
3709 chunked mode has been selected for the query
3710 (see
<xref linkend=
"libpq-single-row-mode"/>).
3711 The number of tuples will not exceed the limit passed to
3712 <xref linkend=
"libpq-PQsetChunkedRowsMode"/>.
3717 <varlistentry id=
"libpq-pgres-pipeline-sync">
3718 <term><literal>PGRES_PIPELINE_SYNC
</literal></term>
3721 The
<structname>PGresult
</structname> represents a
3722 synchronization point in pipeline mode, requested by either
3723 <xref linkend=
"libpq-PQpipelineSync"/> or
3724 <xref linkend=
"libpq-PQsendPipelineSync"/>.
3725 This status occurs only when pipeline mode has been selected.
3730 <varlistentry id=
"libpq-pgres-pipeline-aborted">
3731 <term><literal>PGRES_PIPELINE_ABORTED
</literal></term>
3734 The
<structname>PGresult
</structname> represents a pipeline that has
3735 received an error from the server.
<function>PQgetResult
</function>
3736 must be called repeatedly, and each time it will return this status code
3737 until the end of the current pipeline, at which point it will return
3738 <literal>PGRES_PIPELINE_SYNC
</literal> and normal processing can
3746 If the result status is
<literal>PGRES_TUPLES_OK
</literal>,
3747 <literal>PGRES_SINGLE_TUPLE
</literal>, or
3748 <literal>PGRES_TUPLES_CHUNK
</literal>, then
3749 the functions described below can be used to retrieve the rows
3750 returned by the query. Note that a
<command>SELECT
</command>
3751 command that happens to retrieve zero rows still shows
3752 <literal>PGRES_TUPLES_OK
</literal>.
3753 <literal>PGRES_COMMAND_OK
</literal> is for commands that can never
3754 return rows (
<command>INSERT
</command> or
<command>UPDATE
</command>
3755 without a
<literal>RETURNING
</literal> clause,
3756 etc.). A response of
<literal>PGRES_EMPTY_QUERY
</literal> might
3757 indicate a bug in the client software.
3761 A result of status
<symbol>PGRES_NONFATAL_ERROR
</symbol> will
3762 never be returned directly by
<xref linkend=
"libpq-PQexec"/> or other
3763 query execution functions; results of this kind are instead passed
3764 to the notice processor (see
<xref
3765 linkend=
"libpq-notice-processing"/>).
3770 <varlistentry id=
"libpq-PQresStatus">
3771 <term><function>PQresStatus
</function><indexterm><primary>PQresStatus
</primary></indexterm></term>
3775 Converts the enumerated type returned by
3776 <xref linkend=
"libpq-PQresultStatus"/> into a string constant describing the
3777 status code. The caller should not free the result.
3780 char *PQresStatus(ExecStatusType status);
3786 <varlistentry id=
"libpq-PQresultErrorMessage">
3787 <term><function>PQresultErrorMessage
</function><indexterm><primary>PQresultErrorMessage
</primary></indexterm></term>
3791 Returns the error message associated with the command, or an empty string
3792 if there was no error.
3794 char *PQresultErrorMessage(const PGresult *res);
3796 If there was an error, the returned string will include a trailing
3797 newline. The caller should not free the result directly. It will
3798 be freed when the associated
<structname>PGresult
</structname> handle is
3799 passed to
<xref linkend=
"libpq-PQclear"/>.
3803 Immediately following a
<xref linkend=
"libpq-PQexec"/> or
3804 <xref linkend=
"libpq-PQgetResult"/> call,
3805 <xref linkend=
"libpq-PQerrorMessage"/> (on the connection) will return
3806 the same string as
<xref linkend=
"libpq-PQresultErrorMessage"/> (on
3807 the result). However, a
<structname>PGresult
</structname> will
3808 retain its error message until destroyed, whereas the connection's
3809 error message will change when subsequent operations are done.
3810 Use
<xref linkend=
"libpq-PQresultErrorMessage"/> when you want to
3811 know the status associated with a particular
3812 <structname>PGresult
</structname>; use
3813 <xref linkend=
"libpq-PQerrorMessage"/> when you want to know the
3814 status from the latest operation on the connection.
3819 <varlistentry id=
"libpq-PQresultVerboseErrorMessage">
3820 <term><function>PQresultVerboseErrorMessage
</function><indexterm><primary>PQresultVerboseErrorMessage
</primary></indexterm></term>
3824 Returns a reformatted version of the error message associated with
3825 a
<structname>PGresult
</structname> object.
3827 char *PQresultVerboseErrorMessage(const PGresult *res,
3828 PGVerbosity verbosity,
3829 PGContextVisibility show_context);
3831 In some situations a client might wish to obtain a more detailed
3832 version of a previously-reported error.
3833 <xref linkend=
"libpq-PQresultVerboseErrorMessage"/> addresses this need
3834 by computing the message that would have been produced
3835 by
<xref linkend=
"libpq-PQresultErrorMessage"/> if the specified
3836 verbosity settings had been in effect for the connection when the
3837 given
<structname>PGresult
</structname> was generated. If
3838 the
<structname>PGresult
</structname> is not an error result,
3839 <quote>PGresult is not an error result
</quote> is reported instead.
3840 The returned string includes a trailing newline.
3844 Unlike most other functions for extracting data from
3845 a
<structname>PGresult
</structname>, the result of this function is a freshly
3846 allocated string. The caller must free it
3847 using
<function>PQfreemem()
</function> when the string is no longer needed.
3851 A NULL return is possible if there is insufficient memory.
3856 <varlistentry id=
"libpq-PQresultErrorField">
3857 <term><function>PQresultErrorField
</function><indexterm><primary>PQresultErrorField
</primary></indexterm></term>
3860 Returns an individual field of an error report.
3862 char *PQresultErrorField(const PGresult *res, int fieldcode);
3864 <parameter>fieldcode
</parameter> is an error field identifier; see the symbols
3865 listed below.
<symbol>NULL
</symbol> is returned if the
3866 <structname>PGresult
</structname> is not an error or warning result,
3867 or does not include the specified field. Field values will normally
3868 not include a trailing newline. The caller should not free the
3869 result directly. It will be freed when the
3870 associated
<structname>PGresult
</structname> handle is passed to
3871 <xref linkend=
"libpq-PQclear"/>.
3875 The following field codes are available:
3877 <varlistentry id=
"libpq-pg-diag-severity">
3878 <term><symbol>PG_DIAG_SEVERITY
</symbol></term>
3881 The severity; the field contents are
<literal>ERROR
</literal>,
3882 <literal>FATAL
</literal>, or
<literal>PANIC
</literal> (in an error message),
3883 or
<literal>WARNING
</literal>,
<literal>NOTICE
</literal>,
<literal>DEBUG
</literal>,
3884 <literal>INFO
</literal>, or
<literal>LOG
</literal> (in a notice message), or
3885 a localized translation of one of these. Always present.
3890 <varlistentry id=
"libpq-PG-diag-severity-nonlocalized">
3891 <term><symbol>PG_DIAG_SEVERITY_NONLOCALIZED
</symbol></term>
3894 The severity; the field contents are
<literal>ERROR
</literal>,
3895 <literal>FATAL
</literal>, or
<literal>PANIC
</literal> (in an error message),
3896 or
<literal>WARNING
</literal>,
<literal>NOTICE
</literal>,
<literal>DEBUG
</literal>,
3897 <literal>INFO
</literal>, or
<literal>LOG
</literal> (in a notice message).
3898 This is identical to the
<symbol>PG_DIAG_SEVERITY
</symbol> field except
3899 that the contents are never localized. This is present only in
3900 reports generated by
<productname>PostgreSQL
</productname> versions
9.6
3906 <varlistentry id=
"libpq-pg-diag-sqlstate">
3907 <term><symbol>PG_DIAG_SQLSTATE
</symbol><indexterm
3908 ><primary>error codes
</primary><secondary>libpq
</secondary></indexterm></term>
3911 The SQLSTATE code for the error. The SQLSTATE code identifies
3912 the type of error that has occurred; it can be used by
3913 front-end applications to perform specific operations (such
3914 as error handling) in response to a particular database error.
3915 For a list of the possible SQLSTATE codes, see
<xref
3916 linkend=
"errcodes-appendix"/>. This field is not localizable,
3917 and is always present.
3922 <varlistentry id=
"libpq-pg-diag-message-primary">
3923 <term><symbol>PG_DIAG_MESSAGE_PRIMARY
</symbol></term>
3926 The primary human-readable error message (typically one line).
3932 <varlistentry id=
"libpq-pg-diag-message-detail">
3933 <term><symbol>PG_DIAG_MESSAGE_DETAIL
</symbol></term>
3936 Detail: an optional secondary error message carrying more
3937 detail about the problem. Might run to multiple lines.
3942 <varlistentry id=
"libpq-pg-diag-message-hint">
3943 <term><symbol>PG_DIAG_MESSAGE_HINT
</symbol></term>
3946 Hint: an optional suggestion what to do about the problem.
3947 This is intended to differ from detail in that it offers advice
3948 (potentially inappropriate) rather than hard facts. Might
3949 run to multiple lines.
3954 <varlistentry id=
"libpq-pg-diag-statement-position">
3955 <term><symbol>PG_DIAG_STATEMENT_POSITION
</symbol></term>
3958 A string containing a decimal integer indicating an error cursor
3959 position as an index into the original statement string. The
3960 first character has index
1, and positions are measured in
3961 characters not bytes.
3966 <varlistentry id=
"libpq-pg-diag-internal-position">
3967 <term><symbol>PG_DIAG_INTERNAL_POSITION
</symbol></term>
3970 This is defined the same as the
3971 <symbol>PG_DIAG_STATEMENT_POSITION
</symbol> field, but it is used
3972 when the cursor position refers to an internally generated
3973 command rather than the one submitted by the client. The
3974 <symbol>PG_DIAG_INTERNAL_QUERY
</symbol> field will always appear when
3980 <varlistentry id=
"libpq-pg-diag-internal-query">
3981 <term><symbol>PG_DIAG_INTERNAL_QUERY
</symbol></term>
3984 The text of a failed internally-generated command. This could
3985 be, for example, an SQL query issued by a PL/pgSQL function.
3990 <varlistentry id=
"libpq-pg-diag-context">
3991 <term><symbol>PG_DIAG_CONTEXT
</symbol></term>
3994 An indication of the context in which the error occurred.
3995 Presently this includes a call stack traceback of active
3996 procedural language functions and internally-generated queries.
3997 The trace is one entry per line, most recent first.
4002 <varlistentry id=
"libpq-pg-diag-schema-name">
4003 <term><symbol>PG_DIAG_SCHEMA_NAME
</symbol></term>
4006 If the error was associated with a specific database object,
4007 the name of the schema containing that object, if any.
4012 <varlistentry id=
"libpq-pg-diag-table-name">
4013 <term><symbol>PG_DIAG_TABLE_NAME
</symbol></term>
4016 If the error was associated with a specific table, the name of the
4017 table. (Refer to the schema name field for the name of the
4023 <varlistentry id=
"libpq-pg-diag-column-name">
4024 <term><symbol>PG_DIAG_COLUMN_NAME
</symbol></term>
4027 If the error was associated with a specific table column, the name
4028 of the column. (Refer to the schema and table name fields to
4029 identify the table.)
4034 <varlistentry id=
"libpq-pg-diag-datatype-name">
4035 <term><symbol>PG_DIAG_DATATYPE_NAME
</symbol></term>
4038 If the error was associated with a specific data type, the name of
4039 the data type. (Refer to the schema name field for the name of
4040 the data type's schema.)
4045 <varlistentry id=
"libpq-pg-diag-constraint-name">
4046 <term><symbol>PG_DIAG_CONSTRAINT_NAME
</symbol></term>
4049 If the error was associated with a specific constraint, the name
4050 of the constraint. Refer to fields listed above for the
4051 associated table or domain. (For this purpose, indexes are
4052 treated as constraints, even if they weren't created with
4058 <varlistentry id=
"libpq-pg-diag-source-file">
4059 <term><symbol>PG_DIAG_SOURCE_FILE
</symbol></term>
4062 The file name of the source-code location where the error was
4068 <varlistentry id=
"libpq-pg-diag-source-line">
4069 <term><symbol>PG_DIAG_SOURCE_LINE
</symbol></term>
4072 The line number of the source-code location where the error
4078 <varlistentry id=
"libpq-pg-diag-source-function">
4079 <term><symbol>PG_DIAG_SOURCE_FUNCTION
</symbol></term>
4082 The name of the source-code function reporting the error.
4091 The fields for schema name, table name, column name, data type name,
4092 and constraint name are supplied only for a limited number of error
4093 types; see
<xref linkend=
"errcodes-appendix"/>. Do not assume that
4094 the presence of any of these fields guarantees the presence of
4095 another field. Core error sources observe the interrelationships
4096 noted above, but user-defined functions may use these fields in other
4097 ways. In the same vein, do not assume that these fields denote
4098 contemporary objects in the current database.
4103 The client is responsible for formatting displayed information to meet
4104 its needs; in particular it should break long lines as needed.
4105 Newline characters appearing in the error message fields should be
4106 treated as paragraph breaks, not line breaks.
4110 Errors generated internally by
<application>libpq
</application> will
4111 have severity and primary message, but typically no other fields.
4115 Note that error fields are only available from
4116 <structname>PGresult
</structname> objects, not
4117 <structname>PGconn
</structname> objects; there is no
4118 <function>PQerrorField
</function> function.
4123 <varlistentry id=
"libpq-PQclear">
4124 <term><function>PQclear
</function><indexterm><primary>PQclear
</primary></indexterm></term>
4127 Frees the storage associated with a
4128 <structname>PGresult
</structname>. Every command result should be
4129 freed via
<xref linkend=
"libpq-PQclear"/> when it is no longer
4133 void PQclear(PGresult *res);
4136 If the argument is a
<symbol>NULL
</symbol> pointer, no operation is
4141 You can keep a
<structname>PGresult
</structname> object around for
4142 as long as you need it; it does not go away when you issue a new
4143 command, nor even if you close the connection. To get rid of it,
4144 you must call
<xref linkend=
"libpq-PQclear"/>. Failure to do this
4145 will result in memory leaks in your application.
4153 <sect2 id=
"libpq-exec-select-info">
4154 <title>Retrieving Query Result Information
</title>
4157 These functions are used to extract information from a
4158 <structname>PGresult
</structname> object that represents a successful
4159 query result (that is, one that has status
4160 <literal>PGRES_TUPLES_OK
</literal>,
4161 <literal>PGRES_SINGLE_TUPLE
</literal>, or
4162 <literal>PGRES_TUPLES_CHUNK
</literal>).
4163 They can also be used to extract
4164 information from a successful Describe operation: a Describe's result
4165 has all the same column information that actual execution of the query
4166 would provide, but it has zero rows. For objects with other status values,
4167 these functions will act as though the result has zero rows and zero columns.
4171 <varlistentry id=
"libpq-PQntuples">
4172 <term><function>PQntuples
</function><indexterm><primary>PQntuples
</primary></indexterm></term>
4176 Returns the number of rows (tuples) in the query result.
4177 (Note that
<structname>PGresult
</structname> objects are limited to no more
4178 than
<literal>INT_MAX
</literal> rows, so an
<type>int
</type> result is
4182 int PQntuples(const PGresult *res);
4189 <varlistentry id=
"libpq-PQnfields">
4190 <term><function>PQnfields
</function><indexterm><primary>PQnfields
</primary></indexterm></term>
4194 Returns the number of columns (fields) in each row of the query
4198 int PQnfields(const PGresult *res);
4204 <varlistentry id=
"libpq-PQfname">
4205 <term><function>PQfname
</function><indexterm><primary>PQfname
</primary></indexterm></term>
4209 Returns the column name associated with the given column number.
4210 Column numbers start at
0. The caller should not free the result
4211 directly. It will be freed when the associated
4212 <structname>PGresult
</structname> handle is passed to
4213 <xref linkend=
"libpq-PQclear"/>.
4215 char *PQfname(const PGresult *res,
4221 <symbol>NULL
</symbol> is returned if the column number is out of range.
4226 <varlistentry id=
"libpq-PQfnumber">
4227 <term><function>PQfnumber
</function><indexterm><primary>PQfnumber
</primary></indexterm></term>
4231 Returns the column number associated with the given column name.
4233 int PQfnumber(const PGresult *res,
4234 const char *column_name);
4239 -
1 is returned if the given name does not match any column.
4243 The given name is treated like an identifier in an SQL command,
4244 that is, it is downcased unless double-quoted. For example, given
4245 a query result generated from the SQL command:
4247 SELECT
1 AS FOO,
2 AS
"BAR";
4249 we would have the results:
4251 PQfname(res,
0)
<lineannotation>foo
</lineannotation>
4252 PQfname(res,
1)
<lineannotation>BAR
</lineannotation>
4253 PQfnumber(res,
"FOO")
<lineannotation>0</lineannotation>
4254 PQfnumber(res,
"foo")
<lineannotation>0</lineannotation>
4255 PQfnumber(res,
"BAR")
<lineannotation>-
1</lineannotation>
4256 PQfnumber(res,
"\"BAR\
"")
<lineannotation>1</lineannotation>
4262 <varlistentry id=
"libpq-PQftable">
4263 <term><function>PQftable
</function><indexterm><primary>PQftable
</primary></indexterm></term>
4267 Returns the OID of the table from which the given column was
4268 fetched. Column numbers start at
0.
4270 Oid PQftable(const PGresult *res,
4276 <literal>InvalidOid
</literal> is returned if the column number is out of range,
4277 or if the specified column is not a simple reference to a table column.
4278 You can query the system table
<literal>pg_class
</literal> to determine
4279 exactly which table is referenced.
4283 The type
<type>Oid
</type> and the constant
4284 <literal>InvalidOid
</literal> will be defined when you include
4285 the
<application>libpq
</application> header file. They will both
4286 be some integer type.
4291 <varlistentry id=
"libpq-PQftablecol">
4292 <term><function>PQftablecol
</function><indexterm><primary>PQftablecol
</primary></indexterm></term>
4296 Returns the column number (within its table) of the column making
4297 up the specified query result column. Query-result column numbers
4298 start at
0, but table columns have nonzero numbers.
4300 int PQftablecol(const PGresult *res,
4306 Zero is returned if the column number is out of range, or if the
4307 specified column is not a simple reference to a table column.
4312 <varlistentry id=
"libpq-PQfformat">
4313 <term><function>PQfformat
</function><indexterm><primary>PQfformat
</primary></indexterm></term>
4317 Returns the format code indicating the format of the given
4318 column. Column numbers start at
0.
4320 int PQfformat(const PGresult *res,
4326 Format code zero indicates textual data representation, while format
4327 code one indicates binary representation. (Other codes are reserved
4328 for future definition.)
4333 <varlistentry id=
"libpq-PQftype">
4334 <term><function>PQftype
</function><indexterm><primary>PQftype
</primary></indexterm></term>
4338 Returns the data type associated with the given column number.
4339 The integer returned is the internal OID number of the type.
4340 Column numbers start at
0.
4342 Oid PQftype(const PGresult *res,
4348 You can query the system table
<literal>pg_type
</literal> to
4349 obtain the names and properties of the various data types. The
4350 <acronym>OID
</acronym>s of the built-in data types are defined
4351 in the file
<filename>catalog/pg_type_d.h
</filename>
4352 in the
<productname>PostgreSQL
</productname>
4353 installation's
<filename>include
</filename> directory.
4358 <varlistentry id=
"libpq-PQfmod">
4359 <term><function>PQfmod
</function><indexterm><primary>PQfmod
</primary></indexterm></term>
4363 Returns the type modifier of the column associated with the
4364 given column number. Column numbers start at
0.
4366 int PQfmod(const PGresult *res,
4372 The interpretation of modifier values is type-specific; they
4373 typically indicate precision or size limits. The value -
1 is
4374 used to indicate
<quote>no information available
</quote>. Most data
4375 types do not use modifiers, in which case the value is always
4381 <varlistentry id=
"libpq-PQfsize">
4382 <term><function>PQfsize
</function><indexterm><primary>PQfsize
</primary></indexterm></term>
4386 Returns the size in bytes of the column associated with the
4387 given column number. Column numbers start at
0.
4389 int PQfsize(const PGresult *res,
4395 <xref linkend=
"libpq-PQfsize"/> returns the space allocated for this column
4396 in a database row, in other words the size of the server's
4397 internal representation of the data type. (Accordingly, it is
4398 not really very useful to clients.) A negative value indicates
4399 the data type is variable-length.
4404 <varlistentry id=
"libpq-PQbinaryTuples">
4405 <term><function>PQbinaryTuples
</function><indexterm><primary>PQbinaryTuples
</primary></indexterm></term>
4409 Returns
1 if the
<structname>PGresult
</structname> contains binary data
4410 and
0 if it contains text data.
4412 int PQbinaryTuples(const PGresult *res);
4417 This function is deprecated (except for its use in connection with
4418 <command>COPY
</command>), because it is possible for a single
4419 <structname>PGresult
</structname> to contain text data in some columns and
4420 binary data in others.
<xref linkend=
"libpq-PQfformat"/> is preferred.
4421 <xref linkend=
"libpq-PQbinaryTuples"/> returns
1 only if all columns of the
4422 result are binary (format
1).
4427 <varlistentry id=
"libpq-PQgetvalue">
4428 <term><function>PQgetvalue
</function><indexterm><primary>PQgetvalue
</primary></indexterm></term>
4432 Returns a single field value of one row of a
4433 <structname>PGresult
</structname>. Row and column numbers start
4434 at
0. The caller should not free the result directly. It will
4435 be freed when the associated
<structname>PGresult
</structname> handle is
4436 passed to
<xref linkend=
"libpq-PQclear"/>.
4438 char *PQgetvalue(const PGresult *res,
4445 For data in text format, the value returned by
4446 <xref linkend=
"libpq-PQgetvalue"/> is a null-terminated character
4447 string representation of the field value. For data in binary
4448 format, the value is in the binary representation determined by
4449 the data type's
<function>typsend
</function> and
<function>typreceive
</function>
4450 functions. (The value is actually followed by a zero byte in
4451 this case too, but that is not ordinarily useful, since the
4452 value is likely to contain embedded nulls.)
4456 An empty string is returned if the field value is null. See
4457 <xref linkend=
"libpq-PQgetisnull"/> to distinguish null values from
4458 empty-string values.
4462 The pointer returned by
<xref linkend=
"libpq-PQgetvalue"/> points
4463 to storage that is part of the
<structname>PGresult
</structname>
4464 structure. One should not modify the data it points to, and one
4465 must explicitly copy the data into other storage if it is to be
4466 used past the lifetime of the
<structname>PGresult
</structname>
4472 <varlistentry id=
"libpq-PQgetisnull">
4473 <term><function>PQgetisnull
</function><indexterm
4474 ><primary>PQgetisnull
</primary></indexterm><indexterm
4475 ><primary>null value
</primary><secondary sortas=
"libpq">in libpq
</secondary></indexterm></term>
4479 Tests a field for a null value. Row and column numbers start
4482 int PQgetisnull(const PGresult *res,
4489 This function returns
1 if the field is null and
0 if it
4490 contains a non-null value. (Note that
4491 <xref linkend=
"libpq-PQgetvalue"/> will return an empty string,
4492 not a null pointer, for a null field.)
4497 <varlistentry id=
"libpq-PQgetlength">
4498 <term><function>PQgetlength
</function><indexterm><primary>PQgetlength
</primary></indexterm></term>
4502 Returns the actual length of a field value in bytes. Row and
4503 column numbers start at
0.
4505 int PQgetlength(const PGresult *res,
4512 This is the actual data length for the particular data value,
4513 that is, the size of the object pointed to by
4514 <xref linkend=
"libpq-PQgetvalue"/>. For text data format this is
4515 the same as
<function>strlen()
</function>. For binary format this is
4516 essential information. Note that one should
<emphasis>not
</emphasis>
4517 rely on
<xref linkend=
"libpq-PQfsize"/> to obtain the actual data
4523 <varlistentry id=
"libpq-PQnparams">
4524 <term><function>PQnparams
</function><indexterm><primary>PQnparams
</primary></indexterm></term>
4528 Returns the number of parameters of a prepared statement.
4530 int PQnparams(const PGresult *res);
4535 This function is only useful when inspecting the result of
4536 <xref linkend=
"libpq-PQdescribePrepared"/>. For other types of results it
4542 <varlistentry id=
"libpq-PQparamtype">
4543 <term><function>PQparamtype
</function><indexterm><primary>PQparamtype
</primary></indexterm></term>
4547 Returns the data type of the indicated statement parameter.
4548 Parameter numbers start at
0.
4550 Oid PQparamtype(const PGresult *res, int param_number);
4555 This function is only useful when inspecting the result of
4556 <xref linkend=
"libpq-PQdescribePrepared"/>. For other types of results it
4562 <varlistentry id=
"libpq-PQprint">
4563 <term><function>PQprint
</function><indexterm><primary>PQprint
</primary></indexterm></term>
4567 Prints out all the rows and, optionally, the column names to
4568 the specified output stream.
4570 void PQprint(FILE *fout, /* output stream */
4571 const PGresult *res,
4572 const PQprintOpt *po);
4575 pqbool header; /* print output field headings and row count */
4576 pqbool align; /* fill align the fields */
4577 pqbool standard; /* old brain dead format */
4578 pqbool html3; /* output HTML tables */
4579 pqbool expanded; /* expand tables */
4580 pqbool pager; /* use pager for output if needed */
4581 char *fieldSep; /* field separator */
4582 char *tableOpt; /* attributes for HTML table element */
4583 char *caption; /* HTML table caption */
4584 char **fieldName; /* null-terminated array of replacement field names */
4590 This function was formerly used by
<application>psql
</application>
4591 to print query results, but this is no longer the case. Note
4592 that it assumes all the data is in text format.
4599 <sect2 id=
"libpq-exec-nonselect">
4600 <title>Retrieving Other Result Information
</title>
4603 These functions are used to extract other information from
4604 <structname>PGresult
</structname> objects.
4608 <varlistentry id=
"libpq-PQcmdStatus">
4609 <term><function>PQcmdStatus
</function><indexterm><primary>PQcmdStatus
</primary></indexterm></term>
4613 Returns the command status tag from the SQL command that generated
4614 the
<structname>PGresult
</structname>.
4616 char *PQcmdStatus(PGresult *res);
4621 Commonly this is just the name of the command, but it might include
4622 additional data such as the number of rows processed. The caller
4623 should not free the result directly. It will be freed when the
4624 associated
<structname>PGresult
</structname> handle is passed to
4625 <xref linkend=
"libpq-PQclear"/>.
4630 <varlistentry id=
"libpq-PQcmdTuples">
4631 <term><function>PQcmdTuples
</function><indexterm><primary>PQcmdTuples
</primary></indexterm></term>
4635 Returns the number of rows affected by the SQL command.
4637 char *PQcmdTuples(PGresult *res);
4642 This function returns a string containing the number of rows
4643 affected by the
<acronym>SQL
</acronym> statement that generated the
4644 <structname>PGresult
</structname>. This function can only be used following
4645 the execution of a
<command>SELECT
</command>,
<command>CREATE TABLE AS
</command>,
4646 <command>INSERT
</command>,
<command>UPDATE
</command>,
<command>DELETE
</command>,
4647 <command>MERGE
</command>,
<command>MOVE
</command>,
<command>FETCH
</command>,
4648 or
<command>COPY
</command> statement, or an
<command>EXECUTE
</command> of a
4649 prepared query that contains an
<command>INSERT
</command>,
4650 <command>UPDATE
</command>,
<command>DELETE
</command>,
4651 or
<command>MERGE
</command> statement.
4652 If the command that generated the
<structname>PGresult
</structname> was anything
4653 else,
<xref linkend=
"libpq-PQcmdTuples"/> returns an empty string. The caller
4654 should not free the return value directly. It will be freed when
4655 the associated
<structname>PGresult
</structname> handle is passed to
4656 <xref linkend=
"libpq-PQclear"/>.
4661 <varlistentry id=
"libpq-PQoidValue">
4662 <term><function>PQoidValue
</function><indexterm><primary>PQoidValue
</primary></indexterm></term>
4666 Returns the OID
<indexterm><primary>OID
</primary><secondary>in libpq
</secondary></indexterm>
4667 of the inserted row, if the
<acronym>SQL
</acronym> command was an
4668 <command>INSERT
</command> that inserted exactly one row into a table that
4669 has OIDs, or a
<command>EXECUTE
</command> of a prepared query containing
4670 a suitable
<command>INSERT
</command> statement. Otherwise, this function
4671 returns
<literal>InvalidOid
</literal>. This function will also
4672 return
<literal>InvalidOid
</literal> if the table affected by the
4673 <command>INSERT
</command> statement does not contain OIDs.
4675 Oid PQoidValue(const PGresult *res);
4681 <varlistentry id=
"libpq-PQoidStatus">
4682 <term><function>PQoidStatus
</function><indexterm><primary>PQoidStatus
</primary></indexterm></term>
4686 This function is deprecated in favor of
4687 <xref linkend=
"libpq-PQoidValue"/> and is not thread-safe.
4688 It returns a string with the OID of the inserted row, while
4689 <xref linkend=
"libpq-PQoidValue"/> returns the OID value.
4691 char *PQoidStatus(const PGresult *res);
4701 <sect2 id=
"libpq-exec-escape-string">
4702 <title>Escaping Strings for Inclusion in SQL Commands
</title>
4704 <indexterm zone=
"libpq-exec-escape-string">
4705 <primary>escaping strings
</primary>
4706 <secondary>in libpq
</secondary>
4710 <varlistentry id=
"libpq-PQescapeLiteral">
4711 <term><function>PQescapeLiteral
</function><indexterm><primary>PQescapeLiteral
</primary></indexterm></term>
4716 char *PQescapeLiteral(PGconn *conn, const char *str, size_t length);
4721 <xref linkend=
"libpq-PQescapeLiteral"/> escapes a string for
4722 use within an SQL command. This is useful when inserting data
4723 values as literal constants in SQL commands. Certain characters
4724 (such as quotes and backslashes) must be escaped to prevent them
4725 from being interpreted specially by the SQL parser.
4726 <xref linkend=
"libpq-PQescapeLiteral"/> performs this operation.
4730 <xref linkend=
"libpq-PQescapeLiteral"/> returns an escaped version of the
4731 <parameter>str
</parameter> parameter in memory allocated with
4732 <function>malloc()
</function>. This memory should be freed using
4733 <function>PQfreemem()
</function> when the result is no longer needed.
4734 A terminating zero byte is not required, and should not be
4735 counted in
<parameter>length
</parameter>. (If a terminating zero byte is found
4736 before
<parameter>length
</parameter> bytes are processed,
4737 <xref linkend=
"libpq-PQescapeLiteral"/> stops at the zero; the behavior is
4738 thus rather like
<function>strncpy
</function>.) The
4739 return string has all special characters replaced so that they can
4740 be properly processed by the
<productname>PostgreSQL
</productname>
4741 string literal parser. A terminating zero byte is also added. The
4742 single quotes that must surround
<productname>PostgreSQL
</productname>
4743 string literals are included in the result string.
4747 On error,
<xref linkend=
"libpq-PQescapeLiteral"/> returns
<symbol>NULL
</symbol> and a suitable
4748 message is stored in the
<parameter>conn
</parameter> object.
4753 It is especially important to do proper escaping when handling
4754 strings that were received from an untrustworthy source.
4755 Otherwise there is a security risk: you are vulnerable to
4756 <quote>SQL injection
</quote> attacks wherein unwanted SQL commands are
4757 fed to your database.
4762 Note that it is neither necessary nor correct to do escaping when a data
4763 value is passed as a separate parameter in
<xref linkend=
"libpq-PQexecParams"/> or
4764 its sibling routines.
4769 <varlistentry id=
"libpq-PQescapeIdentifier">
4770 <term><function>PQescapeIdentifier
</function><indexterm><primary>PQescapeIdentifier
</primary></indexterm></term>
4775 char *PQescapeIdentifier(PGconn *conn, const char *str, size_t length);
4780 <xref linkend=
"libpq-PQescapeIdentifier"/> escapes a string for
4781 use as an SQL identifier, such as a table, column, or function name.
4782 This is useful when a user-supplied identifier might contain
4783 special characters that would otherwise not be interpreted as part
4784 of the identifier by the SQL parser, or when the identifier might
4785 contain upper case characters whose case should be preserved.
4789 <xref linkend=
"libpq-PQescapeIdentifier"/> returns a version of the
4790 <parameter>str
</parameter> parameter escaped as an SQL identifier
4791 in memory allocated with
<function>malloc()
</function>. This memory must be
4792 freed using
<function>PQfreemem()
</function> when the result is no longer
4793 needed. A terminating zero byte is not required, and should not be
4794 counted in
<parameter>length
</parameter>. (If a terminating zero byte is found
4795 before
<parameter>length
</parameter> bytes are processed,
4796 <xref linkend=
"libpq-PQescapeIdentifier"/> stops at the zero; the behavior is
4797 thus rather like
<function>strncpy
</function>.) The
4798 return string has all special characters replaced so that it
4799 will be properly processed as an SQL identifier. A terminating zero byte
4800 is also added. The return string will also be surrounded by double
4805 On error,
<xref linkend=
"libpq-PQescapeIdentifier"/> returns
<symbol>NULL
</symbol> and a suitable
4806 message is stored in the
<parameter>conn
</parameter> object.
4811 As with string literals, to prevent SQL injection attacks,
4812 SQL identifiers must be escaped when they are received from an
4813 untrustworthy source.
4819 <varlistentry id=
"libpq-PQescapeStringConn">
4820 <term><function>PQescapeStringConn
</function><indexterm><primary>PQescapeStringConn
</primary></indexterm></term>
4825 size_t PQescapeStringConn(PGconn *conn,
4826 char *to, const char *from, size_t length,
4832 <xref linkend=
"libpq-PQescapeStringConn"/> escapes string literals, much like
4833 <xref linkend=
"libpq-PQescapeLiteral"/>. Unlike
<xref linkend=
"libpq-PQescapeLiteral"/>,
4834 the caller is responsible for providing an appropriately sized buffer.
4835 Furthermore,
<xref linkend=
"libpq-PQescapeStringConn"/> does not generate the
4836 single quotes that must surround
<productname>PostgreSQL
</productname> string
4837 literals; they should be provided in the SQL command that the
4838 result is inserted into. The parameter
<parameter>from
</parameter> points to
4839 the first character of the string that is to be escaped, and the
4840 <parameter>length
</parameter> parameter gives the number of bytes in this
4841 string. A terminating zero byte is not required, and should not be
4842 counted in
<parameter>length
</parameter>. (If a terminating zero byte is found
4843 before
<parameter>length
</parameter> bytes are processed,
4844 <xref linkend=
"libpq-PQescapeStringConn"/> stops at the zero; the behavior is
4845 thus rather like
<function>strncpy
</function>.)
<parameter>to
</parameter> shall point
4846 to a buffer that is able to hold at least one more byte than twice
4847 the value of
<parameter>length
</parameter>, otherwise the behavior is undefined.
4848 Behavior is likewise undefined if the
<parameter>to
</parameter> and
4849 <parameter>from
</parameter> strings overlap.
4853 If the
<parameter>error
</parameter> parameter is not
<symbol>NULL
</symbol>, then
4854 <literal>*error
</literal> is set to zero on success, nonzero on error.
4855 Presently the only possible error conditions involve invalid multibyte
4856 encoding in the source string. The output string is still generated
4857 on error, but it can be expected that the server will reject it as
4858 malformed. On error, a suitable message is stored in the
4859 <parameter>conn
</parameter> object, whether or not
<parameter>error
</parameter> is
<symbol>NULL
</symbol>.
4863 <xref linkend=
"libpq-PQescapeStringConn"/> returns the number of bytes written
4864 to
<parameter>to
</parameter>, not including the terminating zero byte.
4869 <varlistentry id=
"libpq-PQescapeString">
4870 <term><function>PQescapeString
</function><indexterm><primary>PQescapeString
</primary></indexterm></term>
4874 <xref linkend=
"libpq-PQescapeString"/> is an older, deprecated version of
4875 <xref linkend=
"libpq-PQescapeStringConn"/>.
4877 size_t PQescapeString (char *to, const char *from, size_t length);
4882 The only difference from
<xref linkend=
"libpq-PQescapeStringConn"/> is that
4883 <xref linkend=
"libpq-PQescapeString"/> does not take
<structname>PGconn
</structname>
4884 or
<parameter>error
</parameter> parameters.
4885 Because of this, it cannot adjust its behavior depending on the
4886 connection properties (such as character encoding) and therefore
4887 <emphasis>it might give the wrong results
</emphasis>. Also, it has no way
4888 to report error conditions.
4892 <xref linkend=
"libpq-PQescapeString"/> can be used safely in
4893 client programs that work with only one
<productname>PostgreSQL
</productname>
4894 connection at a time (in this case it can find out what it needs to
4895 know
<quote>behind the scenes
</quote>). In other contexts it is a security
4896 hazard and should be avoided in favor of
4897 <xref linkend=
"libpq-PQescapeStringConn"/>.
4902 <varlistentry id=
"libpq-PQescapeByteaConn">
4903 <term><function>PQescapeByteaConn
</function><indexterm><primary>PQescapeByteaConn
</primary></indexterm></term>
4907 Escapes binary data for use within an SQL command with the type
4908 <type>bytea
</type>. As with
<xref linkend=
"libpq-PQescapeStringConn"/>,
4909 this is only used when inserting data directly into an SQL command string.
4911 unsigned char *PQescapeByteaConn(PGconn *conn,
4912 const unsigned char *from,
4919 Certain byte values must be escaped when used as part of a
4920 <type>bytea
</type> literal in an
<acronym>SQL
</acronym> statement.
4921 <xref linkend=
"libpq-PQescapeByteaConn"/> escapes bytes using
4922 either hex encoding or backslash escaping. See
<xref
4923 linkend=
"datatype-binary"/> for more information.
4927 The
<parameter>from
</parameter> parameter points to the first
4928 byte of the string that is to be escaped, and the
4929 <parameter>from_length
</parameter> parameter gives the number of
4930 bytes in this binary string. (A terminating zero byte is
4931 neither necessary nor counted.) The
<parameter>to_length
</parameter>
4932 parameter points to a variable that will hold the resultant
4933 escaped string length. This result string length includes the terminating
4934 zero byte of the result.
4938 <xref linkend=
"libpq-PQescapeByteaConn"/> returns an escaped version of the
4939 <parameter>from
</parameter> parameter binary string in memory
4940 allocated with
<function>malloc()
</function>. This memory should be freed using
4941 <function>PQfreemem()
</function> when the result is no longer needed. The
4942 return string has all special characters replaced so that they can
4943 be properly processed by the
<productname>PostgreSQL
</productname>
4944 string literal parser, and the
<type>bytea
</type> input function. A
4945 terminating zero byte is also added. The single quotes that must
4946 surround
<productname>PostgreSQL
</productname> string literals are
4947 not part of the result string.
4951 On error, a null pointer is returned, and a suitable error message
4952 is stored in the
<parameter>conn
</parameter> object. Currently, the only
4953 possible error is insufficient memory for the result string.
4958 <varlistentry id=
"libpq-PQescapeBytea">
4959 <term><function>PQescapeBytea
</function><indexterm><primary>PQescapeBytea
</primary></indexterm></term>
4963 <xref linkend=
"libpq-PQescapeBytea"/> is an older, deprecated version of
4964 <xref linkend=
"libpq-PQescapeByteaConn"/>.
4966 unsigned char *PQescapeBytea(const unsigned char *from,
4973 The only difference from
<xref linkend=
"libpq-PQescapeByteaConn"/> is that
4974 <xref linkend=
"libpq-PQescapeBytea"/> does not take a
<structname>PGconn
</structname>
4975 parameter. Because of this,
<xref linkend=
"libpq-PQescapeBytea"/> can
4976 only be used safely in client programs that use a single
4977 <productname>PostgreSQL
</productname> connection at a time (in this case
4978 it can find out what it needs to know
<quote>behind the
4979 scenes
</quote>). It
<emphasis>might give the wrong results
</emphasis> if
4980 used in programs that use multiple database connections (use
4981 <xref linkend=
"libpq-PQescapeByteaConn"/> in such cases).
4986 <varlistentry id=
"libpq-PQunescapeBytea">
4987 <term><function>PQunescapeBytea
</function><indexterm><primary>PQunescapeBytea
</primary></indexterm></term>
4991 Converts a string representation of binary data into binary data
4992 — the reverse of
<xref linkend=
"libpq-PQescapeBytea"/>. This
4993 is needed when retrieving
<type>bytea
</type> data in text format,
4994 but not when retrieving it in binary format.
4997 unsigned char *PQunescapeBytea(const unsigned char *from, size_t *to_length);
5002 The
<parameter>from
</parameter> parameter points to a string
5003 such as might be returned by
<xref linkend=
"libpq-PQgetvalue"/> when applied
5004 to a
<type>bytea
</type> column.
<xref linkend=
"libpq-PQunescapeBytea"/>
5005 converts this string representation into its binary representation.
5006 It returns a pointer to a buffer allocated with
5007 <function>malloc()
</function>, or
<symbol>NULL
</symbol> on error, and puts the size of
5008 the buffer in
<parameter>to_length
</parameter>. The result must be
5009 freed using
<xref linkend=
"libpq-PQfreemem"/> when it is no longer needed.
5013 This conversion is not exactly the inverse of
5014 <xref linkend=
"libpq-PQescapeBytea"/>, because the string is not expected
5015 to be
<quote>escaped
</quote> when received from
<xref linkend=
"libpq-PQgetvalue"/>.
5016 In particular this means there is no need for string quoting considerations,
5017 and so no need for a
<structname>PGconn
</structname> parameter.
5027 <sect1 id=
"libpq-async">
5028 <title>Asynchronous Command Processing
</title>
5030 <indexterm zone=
"libpq-async">
5031 <primary>nonblocking connection
</primary>
5035 The
<xref linkend=
"libpq-PQexec"/> function is adequate for submitting
5036 commands in normal, synchronous applications. It has a few
5037 deficiencies, however, that can be of importance to some users:
5042 <xref linkend=
"libpq-PQexec"/> waits for the command to be completed.
5043 The application might have other work to do (such as maintaining a
5044 user interface), in which case it won't want to block waiting for
5051 Since the execution of the client application is suspended while it
5052 waits for the result, it is hard for the application to decide that
5053 it would like to try to cancel the ongoing command. (It can be done
5054 from a signal handler, but not otherwise.)
5060 <xref linkend=
"libpq-PQexec"/> can return only one
5061 <structname>PGresult
</structname> structure. If the submitted command
5062 string contains multiple
<acronym>SQL
</acronym> commands, all but
5063 the last
<structname>PGresult
</structname> are discarded by
5064 <xref linkend=
"libpq-PQexec"/>.
5070 <xref linkend=
"libpq-PQexec"/> always collects the command's entire result,
5071 buffering it in a single
<structname>PGresult
</structname>. While
5072 this simplifies error-handling logic for the application, it can be
5073 impractical for results containing many rows.
5080 Applications that do not like these limitations can instead use the
5081 underlying functions that
<xref linkend=
"libpq-PQexec"/> is built from:
5082 <xref linkend=
"libpq-PQsendQuery"/> and
<xref linkend=
"libpq-PQgetResult"/>.
5084 <xref linkend=
"libpq-PQsendQueryParams"/>,
5085 <xref linkend=
"libpq-PQsendPrepare"/>,
5086 <xref linkend=
"libpq-PQsendQueryPrepared"/>,
5087 <xref linkend=
"libpq-PQsendDescribePrepared"/>,
5088 <xref linkend=
"libpq-PQsendDescribePortal"/>,
5089 <xref linkend=
"libpq-PQsendClosePrepared"/>, and
5090 <xref linkend=
"libpq-PQsendClosePortal"/>,
5091 which can be used with
<xref linkend=
"libpq-PQgetResult"/> to duplicate
5092 the functionality of
5093 <xref linkend=
"libpq-PQexecParams"/>,
5094 <xref linkend=
"libpq-PQprepare"/>,
5095 <xref linkend=
"libpq-PQexecPrepared"/>,
5096 <xref linkend=
"libpq-PQdescribePrepared"/>,
5097 <xref linkend=
"libpq-PQdescribePortal"/>
5098 <xref linkend=
"libpq-PQclosePrepared"/>, and
5099 <xref linkend=
"libpq-PQclosePortal"/>
5103 <varlistentry id=
"libpq-PQsendQuery">
5104 <term><function>PQsendQuery
</function><indexterm><primary>PQsendQuery
</primary></indexterm></term>
5108 Submits a command to the server without waiting for the result(s).
5109 1 is returned if the command was successfully dispatched and
0 if
5110 not (in which case, use
<xref linkend=
"libpq-PQerrorMessage"/> to get more
5111 information about the failure).
5113 int PQsendQuery(PGconn *conn, const char *command);
5116 After successfully calling
<xref linkend=
"libpq-PQsendQuery"/>, call
5117 <xref linkend=
"libpq-PQgetResult"/> one or more times to obtain the
5118 results.
<xref linkend=
"libpq-PQsendQuery"/> cannot be called again
5119 (on the same connection) until
<xref linkend=
"libpq-PQgetResult"/>
5120 has returned a null pointer, indicating that the command is done.
5124 In pipeline mode, this function is disallowed.
5129 <varlistentry id=
"libpq-PQsendQueryParams">
5130 <term><function>PQsendQueryParams
</function><indexterm><primary>PQsendQueryParams
</primary></indexterm></term>
5134 Submits a command and separate parameters to the server without
5135 waiting for the result(s).
5137 int PQsendQueryParams(PGconn *conn,
5138 const char *command,
5140 const Oid *paramTypes,
5141 const char * const *paramValues,
5142 const int *paramLengths,
5143 const int *paramFormats,
5147 This is equivalent to
<xref linkend=
"libpq-PQsendQuery"/> except that
5148 query parameters can be specified separately from the query string.
5149 The function's parameters are handled identically to
5150 <xref linkend=
"libpq-PQexecParams"/>. Like
5151 <xref linkend=
"libpq-PQexecParams"/>, it allows only one command in the
5157 <varlistentry id=
"libpq-PQsendPrepare">
5158 <term><function>PQsendPrepare
</function><indexterm><primary>PQsendPrepare
</primary></indexterm></term>
5162 Sends a request to create a prepared statement with the given
5163 parameters, without waiting for completion.
5165 int PQsendPrepare(PGconn *conn,
5166 const char *stmtName,
5169 const Oid *paramTypes);
5172 This is an asynchronous version of
<xref linkend=
"libpq-PQprepare"/>: it
5173 returns
1 if it was able to dispatch the request, and
0 if not.
5174 After a successful call, call
<xref linkend=
"libpq-PQgetResult"/> to
5175 determine whether the server successfully created the prepared
5176 statement. The function's parameters are handled identically to
5177 <xref linkend=
"libpq-PQprepare"/>.
5182 <varlistentry id=
"libpq-PQsendQueryPrepared">
5183 <term><function>PQsendQueryPrepared
</function><indexterm><primary>PQsendQueryPrepared
</primary></indexterm></term>
5187 Sends a request to execute a prepared statement with given
5188 parameters, without waiting for the result(s).
5190 int PQsendQueryPrepared(PGconn *conn,
5191 const char *stmtName,
5193 const char * const *paramValues,
5194 const int *paramLengths,
5195 const int *paramFormats,
5199 This is similar to
<xref linkend=
"libpq-PQsendQueryParams"/>, but
5200 the command to be executed is specified by naming a
5201 previously-prepared statement, instead of giving a query string.
5202 The function's parameters are handled identically to
5203 <xref linkend=
"libpq-PQexecPrepared"/>.
5208 <varlistentry id=
"libpq-PQsendDescribePrepared">
5209 <term><function>PQsendDescribePrepared
</function><indexterm><primary>PQsendDescribePrepared
</primary></indexterm></term>
5213 Submits a request to obtain information about the specified
5214 prepared statement, without waiting for completion.
5216 int PQsendDescribePrepared(PGconn *conn, const char *stmtName);
5219 This is an asynchronous version of
<xref linkend=
"libpq-PQdescribePrepared"/>:
5220 it returns
1 if it was able to dispatch the request, and
0 if not.
5221 After a successful call, call
<xref linkend=
"libpq-PQgetResult"/> to
5222 obtain the results. The function's parameters are handled
5223 identically to
<xref linkend=
"libpq-PQdescribePrepared"/>.
5228 <varlistentry id=
"libpq-PQsendDescribePortal">
5229 <term><function>PQsendDescribePortal
</function><indexterm><primary>PQsendDescribePortal
</primary></indexterm></term>
5233 Submits a request to obtain information about the specified
5234 portal, without waiting for completion.
5236 int PQsendDescribePortal(PGconn *conn, const char *portalName);
5239 This is an asynchronous version of
<xref linkend=
"libpq-PQdescribePortal"/>:
5240 it returns
1 if it was able to dispatch the request, and
0 if not.
5241 After a successful call, call
<xref linkend=
"libpq-PQgetResult"/> to
5242 obtain the results. The function's parameters are handled
5243 identically to
<xref linkend=
"libpq-PQdescribePortal"/>.
5248 <varlistentry id=
"libpq-PQsendClosePrepared">
5249 <term><function>PQsendClosePrepared
</function><indexterm><primary>PQsendClosePrepared
</primary></indexterm></term>
5253 Submits a request to close the specified prepared statement, without
5254 waiting for completion.
5256 int PQsendClosePrepared(PGconn *conn, const char *stmtName);
5259 This is an asynchronous version of
<xref linkend=
"libpq-PQclosePrepared"/>:
5260 it returns
1 if it was able to dispatch the request, and
0 if not.
5261 After a successful call, call
<xref linkend=
"libpq-PQgetResult"/> to
5262 obtain the results. The function's parameters are handled
5263 identically to
<xref linkend=
"libpq-PQclosePrepared"/>.
5268 <varlistentry id=
"libpq-PQsendClosePortal">
5269 <term><function>PQsendClosePortal
</function><indexterm><primary>PQsendClosePortal
</primary></indexterm></term>
5273 Submits a request to close specified portal, without waiting for
5276 int PQsendClosePortal(PGconn *conn, const char *portalName);
5279 This is an asynchronous version of
<xref linkend=
"libpq-PQclosePortal"/>:
5280 it returns
1 if it was able to dispatch the request, and
0 if not.
5281 After a successful call, call
<xref linkend=
"libpq-PQgetResult"/> to
5282 obtain the results. The function's parameters are handled
5283 identically to
<xref linkend=
"libpq-PQclosePortal"/>.
5288 <varlistentry id=
"libpq-PQgetResult">
5289 <term><function>PQgetResult
</function><indexterm><primary>PQgetResult
</primary></indexterm></term>
5293 Waits for the next result from a prior
5294 <xref linkend=
"libpq-PQsendQuery"/>,
5295 <xref linkend=
"libpq-PQsendQueryParams"/>,
5296 <xref linkend=
"libpq-PQsendPrepare"/>,
5297 <xref linkend=
"libpq-PQsendQueryPrepared"/>,
5298 <xref linkend=
"libpq-PQsendDescribePrepared"/>,
5299 <xref linkend=
"libpq-PQsendDescribePortal"/>,
5300 <xref linkend=
"libpq-PQsendClosePrepared"/>,
5301 <xref linkend=
"libpq-PQsendClosePortal"/>,
5302 <xref linkend=
"libpq-PQsendPipelineSync"/>, or
5303 <xref linkend=
"libpq-PQpipelineSync"/>
5304 call, and returns it.
5305 A null pointer is returned when the command is complete and there
5306 will be no more results.
5308 PGresult *PQgetResult(PGconn *conn);
5313 <xref linkend=
"libpq-PQgetResult"/> must be called repeatedly until
5314 it returns a null pointer, indicating that the command is done.
5315 (If called when no command is active,
5316 <xref linkend=
"libpq-PQgetResult"/> will just return a null pointer
5317 at once.) Each non-null result from
5318 <xref linkend=
"libpq-PQgetResult"/> should be processed using the
5319 same
<structname>PGresult
</structname> accessor functions previously
5320 described. Don't forget to free each result object with
5321 <xref linkend=
"libpq-PQclear"/> when done with it. Note that
5322 <xref linkend=
"libpq-PQgetResult"/> will block only if a command is
5323 active and the necessary response data has not yet been read by
5324 <xref linkend=
"libpq-PQconsumeInput"/>.
5328 In pipeline mode,
<function>PQgetResult
</function> will return normally
5329 unless an error occurs; for any subsequent query sent after the one
5330 that caused the error until (and excluding) the next synchronization point,
5331 a special result of type
<literal>PGRES_PIPELINE_ABORTED
</literal> will
5332 be returned, and a null pointer will be returned after it.
5333 When the pipeline synchronization point is reached, a result of type
5334 <literal>PGRES_PIPELINE_SYNC
</literal> will be returned.
5335 The result of the next query after the synchronization point follows
5336 immediately (that is, no null pointer is returned after
5337 the synchronization point.)
5342 Even when
<xref linkend=
"libpq-PQresultStatus"/> indicates a fatal
5343 error,
<xref linkend=
"libpq-PQgetResult"/> should be called until it
5344 returns a null pointer, to allow
<application>libpq
</application> to
5345 process the error information completely.
5354 Using
<xref linkend=
"libpq-PQsendQuery"/> and
5355 <xref linkend=
"libpq-PQgetResult"/> solves one of
5356 <xref linkend=
"libpq-PQexec"/>'s problems: If a command string contains
5357 multiple
<acronym>SQL
</acronym> commands, the results of those commands
5358 can be obtained individually. (This allows a simple form of overlapped
5359 processing, by the way: the client can be handling the results of one
5360 command while the server is still working on later queries in the same
5365 Another frequently-desired feature that can be obtained with
5366 <xref linkend=
"libpq-PQsendQuery"/> and
<xref linkend=
"libpq-PQgetResult"/>
5367 is retrieving large query results a limited number of rows at a time.
5369 in
<xref linkend=
"libpq-single-row-mode"/>.
5373 By itself, calling
<xref linkend=
"libpq-PQgetResult"/>
5374 will still cause the client to block until the server completes the
5375 next
<acronym>SQL
</acronym> command. This can be avoided by proper
5376 use of two more functions:
5379 <varlistentry id=
"libpq-PQconsumeInput">
5380 <term><function>PQconsumeInput
</function><indexterm><primary>PQconsumeInput
</primary></indexterm>
5385 If input is available from the server, consume it.
5387 int PQconsumeInput(PGconn *conn);
5392 <xref linkend=
"libpq-PQconsumeInput"/> normally returns
1 indicating
5393 <quote>no error
</quote>, but returns
0 if there was some kind of
5394 trouble (in which case
<xref linkend=
"libpq-PQerrorMessage"/> can be
5395 consulted). Note that the result does not say whether any input
5396 data was actually collected. After calling
5397 <xref linkend=
"libpq-PQconsumeInput"/>, the application can check
5398 <xref linkend=
"libpq-PQisBusy"/> and/or
5399 <function>PQnotifies
</function> to see if their state has changed.
5403 <xref linkend=
"libpq-PQconsumeInput"/> can be called even if the
5404 application is not prepared to deal with a result or notification
5405 just yet. The function will read available data and save it in
5406 a buffer, thereby causing a
<function>select()
</function>
5407 read-ready indication to go away. The application can thus use
5408 <xref linkend=
"libpq-PQconsumeInput"/> to clear the
5409 <function>select()
</function> condition immediately, and then
5410 examine the results at leisure.
5415 <varlistentry id=
"libpq-PQisBusy">
5416 <term><function>PQisBusy
</function><indexterm><primary>PQisBusy
</primary></indexterm></term>
5420 Returns
1 if a command is busy, that is,
5421 <xref linkend=
"libpq-PQgetResult"/> would block waiting for input.
5422 A
0 return indicates that
<xref linkend=
"libpq-PQgetResult"/> can be
5423 called with assurance of not blocking.
5425 int PQisBusy(PGconn *conn);
5430 <xref linkend=
"libpq-PQisBusy"/> will not itself attempt to read data
5431 from the server; therefore
<xref linkend=
"libpq-PQconsumeInput"/>
5432 must be invoked first, or the busy state will never end.
5440 A typical application using these functions will have a main loop that
5441 uses
<function>select()
</function> or
<function>poll()
</function> to wait for
5442 all the conditions that it must respond to. One of the conditions
5443 will be input available from the server, which in terms of
5444 <function>select()
</function> means readable data on the file
5445 descriptor identified by
<xref linkend=
"libpq-PQsocket"/>. When the main
5446 loop detects input ready, it should call
5447 <xref linkend=
"libpq-PQconsumeInput"/> to read the input. It can then
5448 call
<xref linkend=
"libpq-PQisBusy"/>, followed by
5449 <xref linkend=
"libpq-PQgetResult"/> if
<xref linkend=
"libpq-PQisBusy"/>
5450 returns false (
0). It can also call
<function>PQnotifies
</function>
5451 to detect
<command>NOTIFY
</command> messages (see
<xref
5452 linkend=
"libpq-notify"/>).
5457 <xref linkend=
"libpq-PQsendQuery"/>/
<xref linkend=
"libpq-PQgetResult"/>
5458 can also attempt to cancel a command that is still being processed
5459 by the server; see
<xref linkend=
"libpq-cancel"/>. But regardless of
5460 the return value of
<xref linkend=
"libpq-PQcancelBlocking"/>, the application
5461 must continue with the normal result-reading sequence using
5462 <xref linkend=
"libpq-PQgetResult"/>. A successful cancellation will
5463 simply cause the command to terminate sooner than it would have
5468 By using the functions described above, it is possible to avoid
5469 blocking while waiting for input from the database server. However,
5470 it is still possible that the application will block waiting to send
5471 output to the server. This is relatively uncommon but can happen if
5472 very long SQL commands or data values are sent. (It is much more
5473 probable if the application sends data via
<command>COPY IN
</command>,
5474 however.) To prevent this possibility and achieve completely
5475 nonblocking database operation, the following additional functions
5479 <varlistentry id=
"libpq-PQsetnonblocking">
5480 <term><function>PQsetnonblocking
</function><indexterm><primary>PQsetnonblocking
</primary></indexterm></term>
5484 Sets the nonblocking status of the connection.
5486 int PQsetnonblocking(PGconn *conn, int arg);
5491 Sets the state of the connection to nonblocking if
5492 <parameter>arg
</parameter> is
1, or blocking if
5493 <parameter>arg
</parameter> is
0. Returns
0 if OK, -
1 if error.
5497 In the nonblocking state, successful calls to
5498 <xref linkend=
"libpq-PQsendQuery"/>,
<xref linkend=
"libpq-PQputline"/>,
5499 <xref linkend=
"libpq-PQputnbytes"/>,
<xref linkend=
"libpq-PQputCopyData"/>,
5500 and
<xref linkend=
"libpq-PQendcopy"/> will not block; their changes
5501 are stored in the local output buffer until they are flushed.
5502 Unsuccessful calls will return an error and must be retried.
5506 Note that
<xref linkend=
"libpq-PQexec"/> does not honor nonblocking
5507 mode; if it is called, it will act in blocking fashion anyway.
5512 <varlistentry id=
"libpq-PQisnonblocking">
5513 <term><function>PQisnonblocking
</function><indexterm><primary>PQisnonblocking
</primary></indexterm></term>
5517 Returns the blocking status of the database connection.
5519 int PQisnonblocking(const PGconn *conn);
5524 Returns
1 if the connection is set to nonblocking mode and
0 if
5530 <varlistentry id=
"libpq-PQflush">
5531 <term><function>PQflush
</function><indexterm><primary>PQflush
</primary></indexterm></term>
5535 Attempts to flush any queued output data to the server. Returns
5536 0 if successful (or if the send queue is empty), -
1 if it failed
5537 for some reason, or
1 if it was unable to send all the data in
5538 the send queue yet (this case can only occur if the connection
5541 int PQflush(PGconn *conn);
5550 After sending any command or data on a nonblocking connection, call
5551 <xref linkend=
"libpq-PQflush"/>. If it returns
1, wait for the socket
5552 to become read- or write-ready. If it becomes write-ready, call
5553 <xref linkend=
"libpq-PQflush"/> again. If it becomes read-ready, call
5554 <xref linkend=
"libpq-PQconsumeInput"/>, then call
5555 <xref linkend=
"libpq-PQflush"/> again. Repeat until
5556 <xref linkend=
"libpq-PQflush"/> returns
0. (It is necessary to check for
5557 read-ready and drain the input with
<xref linkend=
"libpq-PQconsumeInput"/>,
5558 because the server can block trying to send us data, e.g., NOTICE
5559 messages, and won't read our data until we read its.) Once
5560 <xref linkend=
"libpq-PQflush"/> returns
0, wait for the socket to be
5561 read-ready and then read the response as described above.
5566 <sect1 id=
"libpq-pipeline-mode">
5567 <title>Pipeline Mode
</title>
5569 <indexterm zone=
"libpq-pipeline-mode">
5570 <primary>libpq
</primary>
5571 <secondary>pipeline mode
</secondary>
5574 <indexterm zone=
"libpq-pipeline-mode">
5575 <primary>pipelining
</primary>
5576 <secondary>in libpq
</secondary>
5579 <indexterm zone=
"libpq-pipeline-mode">
5580 <primary>batch mode
</primary>
5581 <secondary>in libpq
</secondary>
5585 <application>libpq
</application> pipeline mode allows applications to
5586 send a query without having to read the result of the previously
5587 sent query. Taking advantage of the pipeline mode, a client will wait
5588 less for the server, since multiple queries/results can be
5589 sent/received in a single network transaction.
5593 While pipeline mode provides a significant performance boost, writing
5594 clients using the pipeline mode is more complex because it involves
5595 managing a queue of pending queries and finding which result
5596 corresponds to which query in the queue.
5600 Pipeline mode also generally consumes more memory on both the client and server,
5601 though careful and aggressive management of the send/receive queue can mitigate
5602 this. This applies whether or not the connection is in blocking or non-blocking
5607 While
<application>libpq
</application>'s pipeline API was introduced in
5608 <productname>PostgreSQL
</productname> 14, it is a client-side feature
5609 which doesn't require special server support and works on any server
5610 that supports the v3 extended query protocol. For more information see
5611 <xref linkend=
"protocol-flow-pipelining"/>.
5614 <sect2 id=
"libpq-pipeline-using">
5615 <title>Using Pipeline Mode
</title>
5618 To issue pipelines, the application must switch the connection
5620 which is done with
<xref linkend=
"libpq-PQenterPipelineMode"/>.
5621 <xref linkend=
"libpq-PQpipelineStatus"/> can be used
5622 to test whether pipeline mode is active.
5623 In pipeline mode, only
<link linkend=
"libpq-async">asynchronous operations
</link>
5624 that utilize the extended query protocol
5625 are permitted, command strings containing multiple SQL commands are
5626 disallowed, and so is
<literal>COPY
</literal>.
5627 Using synchronous command execution functions
5628 such as
<function>PQfn
</function>,
5629 <function>PQexec
</function>,
5630 <function>PQexecParams
</function>,
5631 <function>PQprepare
</function>,
5632 <function>PQexecPrepared
</function>,
5633 <function>PQdescribePrepared
</function>,
5634 <function>PQdescribePortal
</function>,
5635 <function>PQclosePrepared
</function>,
5636 <function>PQclosePortal
</function>,
5637 is an error condition.
5638 <function>PQsendQuery
</function> is
5639 also disallowed, because it uses the simple query protocol.
5640 Once all dispatched commands have had their results processed, and
5641 the end pipeline result has been consumed, the application may return
5642 to non-pipelined mode with
<xref linkend=
"libpq-PQexitPipelineMode"/>.
5647 It is best to use pipeline mode with
<application>libpq
</application> in
5648 <link linkend=
"libpq-PQsetnonblocking">non-blocking mode
</link>. If used
5649 in blocking mode it is possible for a client/server deadlock to occur.
5652 The client will block trying to send queries to the server, but the
5653 server will block trying to send results to the client from queries
5654 it has already processed. This only occurs when the client sends
5655 enough queries to fill both its output buffer and the server's receive
5656 buffer before it switches to processing input from the server,
5657 but it's hard to predict exactly when that will happen.
5663 <sect3 id=
"libpq-pipeline-sending">
5664 <title>Issuing Queries
</title>
5667 After entering pipeline mode, the application dispatches requests using
5668 <xref linkend=
"libpq-PQsendQueryParams"/>
5669 or its prepared-query sibling
5670 <xref linkend=
"libpq-PQsendQueryPrepared"/>.
5671 These requests are queued on the client-side until flushed to the server;
5672 this occurs when
<xref linkend=
"libpq-PQpipelineSync"/> is used to
5673 establish a synchronization point in the pipeline,
5674 or when
<xref linkend=
"libpq-PQflush"/> is called.
5675 The functions
<xref linkend=
"libpq-PQsendPrepare"/>,
5676 <xref linkend=
"libpq-PQsendDescribePrepared"/>,
5677 <xref linkend=
"libpq-PQsendDescribePortal"/>,
5678 <xref linkend=
"libpq-PQsendClosePrepared"/>, and
5679 <xref linkend=
"libpq-PQsendClosePortal"/> also work in pipeline mode.
5680 Result processing is described below.
5684 The server executes statements, and returns results, in the order the
5685 client sends them. The server will begin executing the commands in the
5686 pipeline immediately, not waiting for the end of the pipeline.
5687 Note that results are buffered on the server side; the server flushes
5688 that buffer when a synchronization point is established with either
5689 <function>PQpipelineSync
</function> or
5690 <function>PQsendPipelineSync
</function>, or when
5691 <function>PQsendFlushRequest
</function> is called.
5692 If any statement encounters an error, the server aborts the current
5693 transaction and does not execute any subsequent command in the queue
5694 until the next synchronization point;
5695 a
<literal>PGRES_PIPELINE_ABORTED
</literal> result is produced for
5697 (This remains true even if the commands in the pipeline would rollback
5699 Query processing resumes after the synchronization point.
5703 It's fine for one operation to depend on the results of a
5704 prior one; for example, one query may define a table that the next
5705 query in the same pipeline uses. Similarly, an application may
5706 create a named prepared statement and execute it with later
5707 statements in the same pipeline.
5711 <sect3 id=
"libpq-pipeline-results">
5712 <title>Processing Results
</title>
5715 To process the result of one query in a pipeline, the application calls
5716 <function>PQgetResult
</function> repeatedly and handles each result
5717 until
<function>PQgetResult
</function> returns null.
5718 The result from the next query in the pipeline may then be retrieved using
5719 <function>PQgetResult
</function> again and the cycle repeated.
5720 The application handles individual statement results as normal.
5721 When the results of all the queries in the pipeline have been
5722 returned,
<function>PQgetResult
</function> returns a result
5723 containing the status value
<literal>PGRES_PIPELINE_SYNC
</literal>
5727 The client may choose to defer result processing until the complete
5728 pipeline has been sent, or interleave that with sending further
5729 queries in the pipeline; see
<xref linkend=
"libpq-pipeline-interleave"/>.
5733 <function>PQgetResult
</function> behaves the same as for normal
5734 asynchronous processing except that it may contain the new
5735 <type>PGresult
</type> types
<literal>PGRES_PIPELINE_SYNC
</literal>
5736 and
<literal>PGRES_PIPELINE_ABORTED
</literal>.
5737 <literal>PGRES_PIPELINE_SYNC
</literal> is reported exactly once for each
5738 <function>PQpipelineSync
</function> or
5739 <function>PQsendPipelineSync
</function> at the corresponding point
5741 <literal>PGRES_PIPELINE_ABORTED
</literal> is emitted in place of a normal
5742 query result for the first error and all subsequent results
5743 until the next
<literal>PGRES_PIPELINE_SYNC
</literal>;
5744 see
<xref linkend=
"libpq-pipeline-errors"/>.
5748 <function>PQisBusy
</function>,
<function>PQconsumeInput
</function>, etc
5749 operate as normal when processing pipeline results. In particular,
5750 a call to
<function>PQisBusy
</function> in the middle of a pipeline
5751 returns
0 if the results for all the queries issued so far have been
5756 <application>libpq
</application> does not provide any information to the
5757 application about the query currently being processed (except that
5758 <function>PQgetResult
</function> returns null to indicate that we start
5759 returning the results of next query). The application must keep track
5760 of the order in which it sent queries, to associate them with their
5761 corresponding results.
5762 Applications will typically use a state machine or a FIFO queue for this.
5767 <sect3 id=
"libpq-pipeline-errors">
5768 <title>Error Handling
</title>
5771 From the client's perspective, after
<function>PQresultStatus
</function>
5772 returns
<literal>PGRES_FATAL_ERROR
</literal>,
5773 the pipeline is flagged as aborted.
5774 <function>PQresultStatus
</function> will report a
5775 <literal>PGRES_PIPELINE_ABORTED
</literal> result for each remaining queued
5776 operation in an aborted pipeline. The result for
5777 <function>PQpipelineSync
</function> or
5778 <function>PQsendPipelineSync
</function> is reported as
5779 <literal>PGRES_PIPELINE_SYNC
</literal> to signal the end of the aborted pipeline
5780 and resumption of normal result processing.
5784 The client
<emphasis>must
</emphasis> process results with
5785 <function>PQgetResult
</function> during error recovery.
5789 If the pipeline used an implicit transaction, then operations that have
5790 already executed are rolled back and operations that were queued to follow
5791 the failed operation are skipped entirely. The same behavior holds if the
5792 pipeline starts and commits a single explicit transaction (i.e. the first
5793 statement is
<literal>BEGIN
</literal> and the last is
5794 <literal>COMMIT
</literal>) except that the session remains in an aborted
5795 transaction state at the end of the pipeline. If a pipeline contains
5796 <emphasis>multiple explicit transactions
</emphasis>, all transactions that
5797 committed prior to the error remain committed, the currently in-progress
5798 transaction is aborted, and all subsequent operations are skipped completely,
5799 including subsequent transactions. If a pipeline synchronization point
5800 occurs with an explicit transaction block in aborted state, the next pipeline
5801 will become aborted immediately unless the next command puts the transaction
5802 in normal mode with
<command>ROLLBACK
</command>.
5807 The client must not assume that work is committed when it
5808 <emphasis>sends
</emphasis> a
<literal>COMMIT
</literal> — only when the
5809 corresponding result is received to confirm the commit is complete.
5810 Because errors arrive asynchronously, the application needs to be able to
5811 restart from the last
<emphasis>received
</emphasis> committed change and
5812 resend work done after that point if something goes wrong.
5817 <sect3 id=
"libpq-pipeline-interleave">
5818 <title>Interleaving Result Processing and Query Dispatch
</title>
5821 To avoid deadlocks on large pipelines the client should be structured
5822 around a non-blocking event loop using operating system facilities
5823 such as
<function>select
</function>,
<function>poll
</function>,
5824 <function>WaitForMultipleObjectEx
</function>, etc.
5828 The client application should generally maintain a queue of work
5829 remaining to be dispatched and a queue of work that has been dispatched
5830 but not yet had its results processed. When the socket is writable
5831 it should dispatch more work. When the socket is readable it should
5832 read results and process them, matching them up to the next entry in
5833 its corresponding results queue. Based on available memory, results from the
5834 socket should be read frequently: there's no need to wait until the
5835 pipeline end to read the results. Pipelines should be scoped to logical
5836 units of work, usually (but not necessarily) one transaction per pipeline.
5837 There's no need to exit pipeline mode and re-enter it between pipelines,
5838 or to wait for one pipeline to finish before sending the next.
5842 An example using
<function>select()
</function> and a simple state
5843 machine to track sent and received work is in
5844 <filename>src/test/modules/libpq_pipeline/libpq_pipeline.c
</filename>
5845 in the PostgreSQL source distribution.
5850 <sect2 id=
"libpq-pipeline-functions">
5851 <title>Functions Associated with Pipeline Mode
</title>
5855 <varlistentry id=
"libpq-PQpipelineStatus">
5856 <term><function>PQpipelineStatus
</function><indexterm><primary>PQpipelineStatus
</primary></indexterm></term>
5860 Returns the current pipeline mode status of the
5861 <application>libpq
</application> connection.
5863 PGpipelineStatus PQpipelineStatus(const PGconn *conn);
5868 <function>PQpipelineStatus
</function> can return one of the following values:
5873 <literal>PQ_PIPELINE_ON
</literal>
5877 The
<application>libpq
</application> connection is in
5885 <literal>PQ_PIPELINE_OFF
</literal>
5889 The
<application>libpq
</application> connection is
5890 <emphasis>not
</emphasis> in pipeline mode.
5897 <literal>PQ_PIPELINE_ABORTED
</literal>
5901 The
<application>libpq
</application> connection is in pipeline
5902 mode and an error occurred while processing the current pipeline.
5903 The aborted flag is cleared when
<function>PQgetResult
</function>
5904 returns a result of type
<literal>PGRES_PIPELINE_SYNC
</literal>.
5914 <varlistentry id=
"libpq-PQenterPipelineMode">
5915 <term><function>PQenterPipelineMode
</function><indexterm><primary>PQenterPipelineMode
</primary></indexterm></term>
5919 Causes a connection to enter pipeline mode if it is currently idle or
5920 already in pipeline mode.
5923 int PQenterPipelineMode(PGconn *conn);
5928 Returns
1 for success.
5929 Returns
0 and has no effect if the connection is not currently
5930 idle, i.e., it has a result ready, or it is waiting for more
5931 input from the server, etc.
5932 This function does not actually send anything to the server,
5933 it just changes the
<application>libpq
</application> connection
5939 <varlistentry id=
"libpq-PQexitPipelineMode">
5940 <term><function>PQexitPipelineMode
</function><indexterm><primary>PQexitPipelineMode
</primary></indexterm></term>
5944 Causes a connection to exit pipeline mode if it is currently in pipeline mode
5945 with an empty queue and no pending results.
5947 int PQexitPipelineMode(PGconn *conn);
5951 Returns
1 for success. Returns
1 and takes no action if not in
5952 pipeline mode. If the current statement isn't finished processing,
5953 or
<function>PQgetResult
</function> has not been called to collect
5954 results from all previously sent query, returns
0 (in which case,
5955 use
<xref linkend=
"libpq-PQerrorMessage"/> to get more information
5961 <varlistentry id=
"libpq-PQpipelineSync">
5962 <term><function>PQpipelineSync
</function><indexterm><primary>PQpipelineSync
</primary></indexterm></term>
5966 Marks a synchronization point in a pipeline by sending a
5967 <link linkend=
"protocol-flow-ext-query">sync message
</link>
5968 and 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"/>.
5973 int PQpipelineSync(PGconn *conn);
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>
5985 <varlistentry id=
"libpq-PQsendPipelineSync">
5986 <term><function>PQsendPipelineSync
</function><indexterm><primary>PQsendPipelineSync
</primary></indexterm></term>
5990 Marks a synchronization point in a pipeline by sending a
5991 <link linkend=
"protocol-flow-ext-query">sync message
</link>
5992 without flushing the send buffer. This serves as
5993 the delimiter of an implicit transaction and an error recovery
5994 point; see
<xref linkend=
"libpq-pipeline-errors"/>.
5997 int PQsendPipelineSync(PGconn *conn);
6001 Returns
1 for success. Returns
0 if the connection is not in
6002 pipeline mode or sending a
6003 <link linkend=
"protocol-flow-ext-query">sync message
</link>
6005 Note that the message is not itself flushed to the server automatically;
6006 use
<function>PQflush
</function> if necessary.
6011 <varlistentry id=
"libpq-PQsendFlushRequest">
6012 <term><function>PQsendFlushRequest
</function><indexterm><primary>PQsendFlushRequest
</primary></indexterm></term>
6016 Sends a request for the server to flush its output buffer.
6018 int PQsendFlushRequest(PGconn *conn);
6023 Returns
1 for success. Returns
0 on any failure.
6026 The server flushes its output buffer automatically as a result of
6027 <function>PQpipelineSync
</function> being called, or
6028 on any request when not in pipeline mode; this function is useful
6029 to cause the server to flush its output buffer in pipeline mode
6030 without establishing a synchronization point.
6031 Note that the request is not itself flushed to the server automatically;
6032 use
<function>PQflush
</function> if necessary.
6039 <sect2 id=
"libpq-pipeline-tips">
6040 <title>When to Use Pipeline Mode
</title>
6043 Much like asynchronous query mode, there is no meaningful performance
6044 overhead when using pipeline mode. It increases client application complexity,
6045 and extra caution is required to prevent client/server deadlocks, but
6046 pipeline mode can offer considerable performance improvements, in exchange for
6047 increased memory usage from leaving state around longer.
6051 Pipeline mode is most useful when the server is distant, i.e., network latency
6052 (
<quote>ping time
</quote>) is high, and also when many small operations
6053 are being performed in rapid succession. There is usually less benefit
6054 in using pipelined commands when each query takes many multiples of the client/server
6055 round-trip time to execute. A
100-statement operation run on a server
6056 300 ms round-trip-time away would take
30 seconds in network latency alone
6057 without pipelining; with pipelining it may spend as little as
0.3 s waiting for
6058 results from the server.
6062 Use pipelined commands when your application does lots of small
6063 <literal>INSERT
</literal>,
<literal>UPDATE
</literal> and
6064 <literal>DELETE
</literal> operations that can't easily be transformed
6065 into operations on sets, or into a
<literal>COPY
</literal> operation.
6069 Pipeline mode is not useful when information from one operation is required by
6070 the client to produce the next operation. In such cases, the client
6071 would have to introduce a synchronization point and wait for a full client/server
6072 round-trip to get the results it needs. However, it's often possible to
6073 adjust the client design to exchange the required information server-side.
6074 Read-modify-write cycles are especially good candidates; for example:
6077 SELECT x FROM mytable WHERE id =
42 FOR UPDATE;
6079 -- client adds
1 to x:
6080 UPDATE mytable SET x =
3 WHERE id =
42;
6083 could be much more efficiently done with:
6085 UPDATE mytable SET x = x +
1 WHERE id =
42;
6090 Pipelining is less useful, and more complex, when a single pipeline contains
6091 multiple transactions (see
<xref linkend=
"libpq-pipeline-errors"/>).
6096 <!-- keep this not-too-apropos sect1 ID for stability of doc URLs -->
6097 <sect1 id=
"libpq-single-row-mode">
6098 <title>Retrieving Query Results in Chunks
</title>
6100 <indexterm zone=
"libpq-single-row-mode">
6101 <primary>libpq
</primary>
6102 <secondary>single-row mode
</secondary>
6105 <indexterm zone=
"libpq-single-row-mode">
6106 <primary>libpq
</primary>
6107 <secondary>chunked mode
</secondary>
6111 Ordinarily,
<application>libpq
</application> collects an SQL command's
6112 entire result and returns it to the application as a single
6113 <structname>PGresult
</structname>. This can be unworkable for commands
6114 that return a large number of rows. For such cases, applications can use
6115 <xref linkend=
"libpq-PQsendQuery"/> and
<xref linkend=
"libpq-PQgetResult"/> in
6116 <firstterm>single-row mode
</firstterm> or
<firstterm>chunked
6117 mode
</firstterm>. In these modes, result row(s) are returned to the
6118 application as they are received from the server, one at a time for
6119 single-row mode or in groups for chunked mode.
6123 To enter one of these modes, call
<xref linkend=
"libpq-PQsetSingleRowMode"/>
6124 or
<xref linkend=
"libpq-PQsetChunkedRowsMode"/>
6125 immediately after a successful call of
<xref linkend=
"libpq-PQsendQuery"/>
6126 (or a sibling function). This mode selection is effective only for the
6127 currently executing query. Then call
<xref linkend=
"libpq-PQgetResult"/>
6128 repeatedly, until it returns null, as documented in
<xref
6129 linkend=
"libpq-async"/>. If the query returns any rows, they are returned
6130 as one or more
<structname>PGresult
</structname> objects, which look like
6131 normal query results except for having status code
6132 <literal>PGRES_SINGLE_TUPLE
</literal> for single-row mode or
6133 <literal>PGRES_TUPLES_CHUNK
</literal> for chunked mode, instead of
6134 <literal>PGRES_TUPLES_OK
</literal>. There is exactly one result row in
6135 each
<literal>PGRES_SINGLE_TUPLE
</literal> object, while
6136 a
<literal>PGRES_TUPLES_CHUNK
</literal> object contains at least one
6137 row but not more than the specified number of rows per chunk.
6138 After the last row, or immediately if
6139 the query returns zero rows, a zero-row object with status
6140 <literal>PGRES_TUPLES_OK
</literal> is returned; this is the signal that no
6141 more rows will arrive. (But note that it is still necessary to continue
6142 calling
<xref linkend=
"libpq-PQgetResult"/> until it returns null.) All of
6143 these
<structname>PGresult
</structname> objects will contain the same row
6144 description data (column names, types, etc.) that an ordinary
6145 <structname>PGresult
</structname> object for the query would have.
6146 Each object should be freed with
<xref linkend=
"libpq-PQclear"/> as usual.
6150 When using pipeline mode, single-row or chunked mode needs to be
6151 activated for each query in the pipeline before retrieving results for
6152 that query with
<function>PQgetResult
</function>.
6153 See
<xref linkend=
"libpq-pipeline-mode"/> for more information.
6158 <varlistentry id=
"libpq-PQsetSingleRowMode">
6159 <term><function>PQsetSingleRowMode
</function><indexterm><primary>PQsetSingleRowMode
</primary></indexterm></term>
6163 Select single-row mode for the currently-executing query.
6166 int PQsetSingleRowMode(PGconn *conn);
6171 This function can only be called immediately after
6172 <xref linkend=
"libpq-PQsendQuery"/> or one of its sibling functions,
6173 before any other operation on the connection such as
6174 <xref linkend=
"libpq-PQconsumeInput"/> or
6175 <xref linkend=
"libpq-PQgetResult"/>. If called at the correct time,
6176 the function activates single-row mode for the current query and
6177 returns
1. Otherwise the mode stays unchanged and the function
6178 returns
0. In any case, the mode reverts to normal after
6179 completion of the current query.
6184 <varlistentry id=
"libpq-PQsetChunkedRowsMode">
6185 <term><function>PQsetChunkedRowsMode
</function><indexterm><primary>PQsetChunkedRowsMode
</primary></indexterm></term>
6189 Select chunked mode for the currently-executing query.
6192 int PQsetChunkedRowsMode(PGconn *conn, int chunkSize);
6197 This function is similar to
6198 <xref linkend=
"libpq-PQsetSingleRowMode"/>, except that it
6199 specifies retrieval of up to
<replaceable>chunkSize
</replaceable> rows
6200 per
<structname>PGresult
</structname>, not necessarily just one row.
6201 This function can only be called immediately after
6202 <xref linkend=
"libpq-PQsendQuery"/> or one of its sibling functions,
6203 before any other operation on the connection such as
6204 <xref linkend=
"libpq-PQconsumeInput"/> or
6205 <xref linkend=
"libpq-PQgetResult"/>. If called at the correct time,
6206 the function activates chunked mode for the current query and
6207 returns
1. Otherwise the mode stays unchanged and the function
6208 returns
0. In any case, the mode reverts to normal after
6209 completion of the current query.
6218 While processing a query, the server may return some rows and then
6219 encounter an error, causing the query to be aborted. Ordinarily,
6220 <application>libpq
</application> discards any such rows and reports only the
6221 error. But in single-row or chunked mode, some rows may have already
6222 been returned to the application. Hence, the application will see some
6223 <literal>PGRES_SINGLE_TUPLE
</literal> or
<literal>PGRES_TUPLES_CHUNK
</literal>
6224 <structname>PGresult
</structname>
6225 objects followed by a
<literal>PGRES_FATAL_ERROR
</literal> object. For
6226 proper transactional behavior, the application must be designed to
6227 discard or undo whatever has been done with the previously-processed
6228 rows, if the query ultimately fails.
6234 <sect1 id=
"libpq-cancel">
6235 <title>Canceling Queries in Progress
</title>
6237 <indexterm zone=
"libpq-cancel">
6238 <primary>canceling SQL queries
</primary>
6240 <indexterm zone=
"libpq-cancel">
6241 <primary>query cancellation
</primary>
6244 <sect2 id=
"libpq-cancel-functions">
6245 <title>Functions for Sending Cancel Requests
</title>
6247 <varlistentry id=
"libpq-PQcancelCreate">
6248 <term><function>PQcancelCreate
</function><indexterm><primary>PQcancelCreate
</primary></indexterm></term>
6252 Prepares a connection over which a cancel request can be sent.
6254 PGcancelConn *PQcancelCreate(PGconn *conn);
6259 <xref linkend=
"libpq-PQcancelCreate"/> creates a
6260 <structname>PGcancelConn
</structname><indexterm><primary>PGcancelConn
</primary></indexterm>
6261 object, but it won't instantly start sending a cancel request over this
6262 connection. A cancel request can be sent over this connection in a
6263 blocking manner using
<xref linkend=
"libpq-PQcancelBlocking"/> and in a
6264 non-blocking manner using
<xref linkend=
"libpq-PQcancelStart"/>.
6265 The return value can be passed to
<xref linkend=
"libpq-PQcancelStatus"/>
6266 to check if the
<structname>PGcancelConn
</structname> object was
6267 created successfully. The
<structname>PGcancelConn
</structname> object
6268 is an opaque structure that is not meant to be accessed directly by the
6269 application. This
<structname>PGcancelConn
</structname> object can be
6270 used to cancel the query that's running on the original connection in a
6275 Many connection parameters of the original client will be reused when
6276 setting up the connection for the cancel request. Importantly, if the
6277 original connection requires encryption of the connection and/or
6278 verification of the target host (using
<literal>sslmode
</literal> or
6279 <literal>gssencmode
</literal>), then the connection for the cancel
6280 request is made with these same requirements. Any connection options
6281 that are only used during authentication or after authentication of the
6282 client are ignored though, because cancellation requests do not require
6283 authentication and the connection is closed right after the cancellation
6284 request is submitted.
6288 Note that when
<function>PQcancelCreate
</function> returns a non-null
6289 pointer, you must call
<xref linkend=
"libpq-PQcancelFinish"/> when you
6290 are finished with it, in order to dispose of the structure and any
6291 associated memory blocks. This must be done even if the cancel request
6292 failed or was abandoned.
6297 <varlistentry id=
"libpq-PQcancelBlocking">
6298 <term><function>PQcancelBlocking
</function><indexterm><primary>PQcancelBlocking
</primary></indexterm></term>
6302 Requests that the server abandons processing of the current command
6303 in a blocking manner.
6305 int PQcancelBlocking(PGcancelConn *cancelConn);
6310 The request is made over the given
<structname>PGcancelConn
</structname>,
6311 which needs to be created with
<xref linkend=
"libpq-PQcancelCreate"/>.
6312 The return value of
<xref linkend=
"libpq-PQcancelBlocking"/>
6313 is
1 if the cancel request was successfully
6314 dispatched and
0 if not. If it was unsuccessful, the error message can be
6315 retrieved using
<xref linkend=
"libpq-PQcancelErrorMessage"/>.
6319 Successful dispatch of the cancellation is no guarantee that the request
6320 will have any effect, however. If the cancellation is effective, the
6321 command being canceled will terminate early and return an error result.
6322 If the cancellation fails (say, because the server was already done
6323 processing the command), then there will be no visible result at all.
6329 <varlistentry id=
"libpq-PQcancelStart">
6330 <term><function>PQcancelStart
</function><indexterm><primary>PQcancelStart
</primary></indexterm></term>
6331 <term><function>PQcancelPoll
</function><indexterm><primary>PQcancelPoll
</primary></indexterm></term>
6335 Requests that the server abandons processing of the current command
6336 in a non-blocking manner.
6338 int PQcancelStart(PGcancelConn *cancelConn);
6340 PostgresPollingStatusType PQcancelPoll(PGcancelConn *cancelConn);
6345 The request is made over the given
<structname>PGcancelConn
</structname>,
6346 which needs to be created with
<xref linkend=
"libpq-PQcancelCreate"/>.
6347 The return value of
<xref linkend=
"libpq-PQcancelStart"/>
6348 is
1 if the cancellation request could be started and
0 if not.
6349 If it was unsuccessful, the error message can be
6350 retrieved using
<xref linkend=
"libpq-PQcancelErrorMessage"/>.
6354 If
<function>PQcancelStart
</function> succeeds, the next stage
6355 is to poll
<application>libpq
</application> so that it can proceed with
6356 the cancel connection sequence.
6357 Use
<xref linkend=
"libpq-PQcancelSocket"/> to obtain the descriptor of the
6358 socket underlying the database connection.
6359 (Caution: do not assume that the socket remains the same
6360 across
<function>PQcancelPoll
</function> calls.)
6361 Loop thus: If
<function>PQcancelPoll(cancelConn)
</function> last returned
6362 <symbol>PGRES_POLLING_READING
</symbol>, wait until the socket is ready to
6363 read (as indicated by
<function>select()
</function>,
6364 <function>poll()
</function>, or similar system function).
6365 Then call
<function>PQcancelPoll(cancelConn)
</function> again.
6366 Conversely, if
<function>PQcancelPoll(cancelConn)
</function> last returned
6367 <symbol>PGRES_POLLING_WRITING
</symbol>, wait until the socket is ready
6368 to write, then call
<function>PQcancelPoll(cancelConn)
</function> again.
6369 On the first iteration, i.e., if you have yet to call
6370 <function>PQcancelPoll(cancelConn)
</function>, behave as if it last returned
6371 <symbol>PGRES_POLLING_WRITING
</symbol>. Continue this loop until
6372 <function>PQcancelPoll(cancelConn)
</function> returns
6373 <symbol>PGRES_POLLING_FAILED
</symbol>, indicating the connection procedure
6374 has failed, or
<symbol>PGRES_POLLING_OK
</symbol>, indicating cancel
6375 request was successfully dispatched.
6379 Successful dispatch of the cancellation is no guarantee that the request
6380 will have any effect, however. If the cancellation is effective, the
6381 command being canceled will terminate early and return an error result.
6382 If the cancellation fails (say, because the server was already done
6383 processing the command), then there will be no visible result at all.
6387 At any time during connection, the status of the connection can be
6388 checked by calling
<xref linkend=
"libpq-PQcancelStatus"/>.
6389 If this call returns
<symbol>CONNECTION_BAD
</symbol>, then
6390 the cancel procedure has failed; if the call returns
6391 <function>CONNECTION_OK
</function>, then cancel request was
6392 successfully dispatched.
6393 Both of these states are equally detectable from the return value of
6394 <function>PQcancelPoll
</function>, described above.
6395 Other states might also occur during (and only during) an asynchronous
6396 connection procedure.
6397 These indicate the current stage of the connection procedure and might
6398 be useful to provide feedback to the user for example.
6402 <varlistentry id=
"libpq-cancel-connection-allocated">
6403 <term><symbol>CONNECTION_ALLOCATED
</symbol></term>
6406 Waiting for a call to
<xref linkend=
"libpq-PQcancelStart"/> or
6407 <xref linkend=
"libpq-PQcancelBlocking"/>, to actually open the
6408 socket. This is the connection state right after
6409 calling
<xref linkend=
"libpq-PQcancelCreate"/>
6410 or
<xref linkend=
"libpq-PQcancelReset"/>. No connection to the
6411 server has been initiated yet at this point. To actually start
6412 sending the cancel request use
<xref linkend=
"libpq-PQcancelStart"/> or
6413 <xref linkend=
"libpq-PQcancelBlocking"/>.
6418 <varlistentry id=
"libpq-cancel-connection-started">
6419 <term><symbol>CONNECTION_STARTED
</symbol></term>
6422 Waiting for connection to be made.
6427 <varlistentry id=
"libpq-cancel-connection-made">
6428 <term><symbol>CONNECTION_MADE
</symbol></term>
6431 Connection OK; waiting to send.
6436 <varlistentry id=
"libpq-cancel-connection-awaiting-response">
6437 <term><symbol>CONNECTION_AWAITING_RESPONSE
</symbol></term>
6440 Waiting for a response from the server.
6445 <varlistentry id=
"libpq-cancel-connection-ssl-startup">
6446 <term><symbol>CONNECTION_SSL_STARTUP
</symbol></term>
6449 Negotiating SSL encryption.
6454 <varlistentry id=
"libpq-cancel-connection-gss-startup">
6455 <term><symbol>CONNECTION_GSS_STARTUP
</symbol></term>
6458 Negotiating GSS encryption.
6464 Note that, although these constants will remain (in order to maintain
6465 compatibility), an application should never rely upon these occurring in a
6466 particular order, or at all, or on the status always being one of these
6467 documented values. An application might do something like this:
6469 switch(PQcancelStatus(conn))
6471 case CONNECTION_STARTED:
6472 feedback =
"Connecting...";
6475 case CONNECTION_MADE:
6476 feedback =
"Connected to server...";
6482 feedback =
"Connecting...";
6488 The
<literal>connect_timeout
</literal> connection parameter is ignored
6489 when using
<function>PQcancelPoll
</function>; it is the application's
6490 responsibility to decide whether an excessive amount of time has elapsed.
6491 Otherwise,
<function>PQcancelStart
</function> followed by a
6492 <function>PQcancelPoll
</function> loop is equivalent to
6493 <xref linkend=
"libpq-PQcancelBlocking"/>.
6499 <varlistentry id=
"libpq-PQcancelStatus">
6500 <term><function>PQcancelStatus
</function><indexterm><primary>PQcancelStatus
</primary></indexterm></term>
6504 Returns the status of the cancel connection.
6506 ConnStatusType PQcancelStatus(const PGcancelConn *cancelConn);
6511 The status can be one of a number of values. However, only three of
6512 these are seen outside of an asynchronous cancel procedure:
6513 <literal>CONNECTION_ALLOCATED
</literal>,
6514 <literal>CONNECTION_OK
</literal> and
6515 <literal>CONNECTION_BAD
</literal>. The initial state of a
6516 <function>PGcancelConn
</function> that's successfully created using
6517 <xref linkend=
"libpq-PQcancelCreate"/> is
<literal>CONNECTION_ALLOCATED
</literal>.
6518 A cancel request that was successfully dispatched
6519 has the status
<literal>CONNECTION_OK
</literal>. A failed
6520 cancel attempt is signaled by status
6521 <literal>CONNECTION_BAD
</literal>. An OK status will
6522 remain so until
<xref linkend=
"libpq-PQcancelFinish"/> or
6523 <xref linkend=
"libpq-PQcancelReset"/> is called.
6527 See the entry for
<xref linkend=
"libpq-PQcancelStart"/> with regards
6528 to other status codes that might be returned.
6532 Successful dispatch of the cancellation is no guarantee that the request
6533 will have any effect, however. If the cancellation is effective, the
6534 command being canceled will terminate early and return an error result.
6535 If the cancellation fails (say, because the server was already done
6536 processing the command), then there will be no visible result at all.
6542 <varlistentry id=
"libpq-PQcancelSocket">
6543 <term><function>PQcancelSocket
</function><indexterm><primary>PQcancelSocket
</primary></indexterm></term>
6547 Obtains the file descriptor number of the cancel connection socket to
6550 int PQcancelSocket(const PGcancelConn *cancelConn);
6555 A valid descriptor will be greater than or equal to
0;
6556 a result of -
1 indicates that no server connection is currently open.
6557 This might change as a result of calling any of the functions
6558 in this section on the
<structname>PGcancelConn
</structname>
6559 (except for
<xref linkend=
"libpq-PQcancelErrorMessage"/> and
6560 <function>PQcancelSocket
</function> itself).
6565 <varlistentry id=
"libpq-PQcancelErrorMessage">
6567 <function>PQcancelErrorMessage
</function><indexterm><primary>PQcancelErrorMessage
</primary></indexterm>
6568 <indexterm><primary>error message
</primary><secondary>in
<structname>PGcancelConn
</structname></secondary></indexterm>
6573 Returns the error message most recently generated by an
6574 operation on the cancel connection.
6576 char *PQcancelErrorMessage(const PGcancelConn *cancelconn);
6581 Nearly all
<application>libpq
</application> functions that take a
6582 <structname>PGcancelConn
</structname> will set a message for
6583 <xref linkend=
"libpq-PQcancelErrorMessage"/> if they fail.
6584 Note that by
<application>libpq
</application> convention,
6585 a nonempty
<xref linkend=
"libpq-PQcancelErrorMessage"/> result
6586 can consist of multiple lines, and will include a trailing newline.
6587 The caller should not free the result directly.
6588 It will be freed when the associated
6589 <structname>PGcancelConn
</structname> handle is passed to
6590 <xref linkend=
"libpq-PQcancelFinish"/>. The result string should not be
6591 expected to remain the same across operations on the
6592 <literal>PGcancelConn
</literal> structure.
6597 <varlistentry id=
"libpq-PQcancelFinish">
6598 <term><function>PQcancelFinish
</function><indexterm><primary>PQcancelFinish
</primary></indexterm></term>
6601 Closes the cancel connection (if it did not finish sending the
6602 cancel request yet). Also frees memory used by the
6603 <structname>PGcancelConn
</structname> object.
6605 void PQcancelFinish(PGcancelConn *cancelConn);
6610 Note that even if the cancel attempt fails (as
6611 indicated by
<xref linkend=
"libpq-PQcancelStatus"/>), the
6612 application should call
<xref linkend=
"libpq-PQcancelFinish"/>
6613 to free the memory used by the
<structname>PGcancelConn
</structname>
6615 The
<structname>PGcancelConn
</structname> pointer must not be used
6616 again after
<xref linkend=
"libpq-PQcancelFinish"/> has been called.
6621 <varlistentry id=
"libpq-PQcancelReset">
6622 <term><function>PQcancelReset
</function><indexterm><primary>PQcancelReset
</primary></indexterm></term>
6625 Resets the
<symbol>PGcancelConn
</symbol> so it can be reused for a new
6628 void PQcancelReset(PGcancelConn *cancelConn);
6633 If the
<symbol>PGcancelConn
</symbol> is currently used to send a cancel
6634 request, then this connection is closed. It will then prepare the
6635 <symbol>PGcancelConn
</symbol> object such that it can be used to send a
6640 This can be used to create one
<structname>PGcancelConn
</structname>
6641 for a
<structname>PGconn
</structname> and reuse it multiple times
6642 throughout the lifetime of the original
<structname>PGconn
</structname>.
6649 <sect2 id=
"libpq-cancel-deprecated">
6650 <title>Obsolete Functions for Sending Cancel Requests
</title>
6653 These functions represent older methods of sending cancel requests.
6654 Although they still work, they are deprecated due to not sending the cancel
6655 requests in an encrypted manner, even when the original connection
6656 specified
<literal>sslmode
</literal> or
<literal>gssencmode
</literal> to
6657 require encryption. Thus these older methods are heavily discouraged from
6658 being used in new code, and it is recommended to change existing code to
6659 use the new functions instead.
6663 <varlistentry id=
"libpq-PQgetCancel">
6664 <term><function>PQgetCancel
</function><indexterm><primary>PQgetCancel
</primary></indexterm></term>
6668 Creates a data structure containing the information needed to cancel
6669 a command using
<xref linkend=
"libpq-PQcancel"/>.
6671 PGcancel *PQgetCancel(PGconn *conn);
6676 <xref linkend=
"libpq-PQgetCancel"/> creates a
6677 <structname>PGcancel
</structname><indexterm><primary>PGcancel
</primary></indexterm>
6678 object given a
<structname>PGconn
</structname> connection object.
6679 It will return
<symbol>NULL
</symbol> if the given
<parameter>conn
</parameter>
6680 is
<symbol>NULL
</symbol> or an invalid connection.
6681 The
<structname>PGcancel
</structname> object is an opaque
6682 structure that is not meant to be accessed directly by the
6683 application; it can only be passed to
<xref linkend=
"libpq-PQcancel"/>
6684 or
<xref linkend=
"libpq-PQfreeCancel"/>.
6689 <varlistentry id=
"libpq-PQfreeCancel">
6690 <term><function>PQfreeCancel
</function><indexterm><primary>PQfreeCancel
</primary></indexterm></term>
6694 Frees a data structure created by
<xref linkend=
"libpq-PQgetCancel"/>.
6696 void PQfreeCancel(PGcancel *cancel);
6701 <xref linkend=
"libpq-PQfreeCancel"/> frees a data object previously created
6702 by
<xref linkend=
"libpq-PQgetCancel"/>.
6707 <varlistentry id=
"libpq-PQcancel">
6708 <term><function>PQcancel
</function><indexterm><primary>PQcancel
</primary></indexterm></term>
6712 <xref linkend=
"libpq-PQcancel"/> is a deprecated and insecure
6713 variant of
<xref linkend=
"libpq-PQcancelBlocking"/>, but one that can be
6714 used safely from within a signal handler.
6716 int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize);
6721 <xref linkend=
"libpq-PQcancel"/> only exists because of backwards
6722 compatibility reasons.
<xref linkend=
"libpq-PQcancelBlocking"/> should be
6723 used instead. The only benefit that
<xref linkend=
"libpq-PQcancel"/> has
6724 is that it can be safely invoked from a signal handler, if the
6725 <parameter>errbuf
</parameter> is a local variable in the signal handler.
6726 However, this is generally not considered a big enough benefit to be
6727 worth the security issues that this function has.
6731 The
<structname>PGcancel
</structname> object is read-only as far as
6732 <xref linkend=
"libpq-PQcancel"/> is concerned, so it can also be invoked
6733 from a thread that is separate from the one manipulating the
6734 <structname>PGconn
</structname> object.
6738 The return value of
<xref linkend=
"libpq-PQcancel"/> is
1 if the
6739 cancel request was successfully dispatched and
0 if not.
6740 If not,
<parameter>errbuf
</parameter> is filled with an explanatory
6742 <parameter>errbuf
</parameter> must be a char array of size
6743 <parameter>errbufsize
</parameter> (the recommended size is
256 bytes).
6750 <varlistentry id=
"libpq-PQrequestCancel">
6751 <term><function>PQrequestCancel
</function><indexterm><primary>PQrequestCancel
</primary></indexterm></term>
6755 <xref linkend=
"libpq-PQrequestCancel"/> is a deprecated and insecure
6756 variant of
<xref linkend=
"libpq-PQcancelBlocking"/>.
6758 int PQrequestCancel(PGconn *conn);
6763 <xref linkend=
"libpq-PQrequestCancel"/> only exists because of backwards
6764 compatibility reasons.
<xref linkend=
"libpq-PQcancelBlocking"/> should be
6765 used instead. There is no benefit to using
6766 <xref linkend=
"libpq-PQrequestCancel"/> over
6767 <xref linkend=
"libpq-PQcancelBlocking"/>.
6771 Requests that the server abandon processing of the current
6772 command. It operates directly on the
6773 <structname>PGconn
</structname> object, and in case of failure stores the
6774 error message in the
<structname>PGconn
</structname> object (whence it can
6775 be retrieved by
<xref linkend=
"libpq-PQerrorMessage"/>). Although
6776 the functionality is the same, this approach is not safe within
6777 multiple-thread programs or signal handlers, since it is possible
6778 that overwriting the
<structname>PGconn
</structname>'s error message will
6779 mess up the operation currently in progress on the connection.
6787 <sect1 id=
"libpq-fastpath">
6788 <title>The Fast-Path Interface
</title>
6790 <indexterm zone=
"libpq-fastpath">
6791 <primary>fast path
</primary>
6795 <productname>PostgreSQL
</productname> provides a fast-path interface
6796 to send simple function calls to the server.
6801 This interface is somewhat obsolete, as one can achieve similar
6802 performance and greater functionality by setting up a prepared
6803 statement to define the function call. Then, executing the statement
6804 with binary transmission of parameters and results substitutes for a
6805 fast-path function call.
6810 The function
<function id=
"libpq-PQfn">PQfn
</function><indexterm><primary>PQfn
</primary></indexterm>
6811 requests execution of a server function via the fast-path interface:
6813 PGresult *PQfn(PGconn *conn,
6818 const PQArgBlock *args,
6835 The
<parameter>fnid
</parameter> argument is the OID of the function to be
6836 executed.
<parameter>args
</parameter> and
<parameter>nargs
</parameter> define the
6837 parameters to be passed to the function; they must match the declared
6838 function argument list. When the
<parameter>isint
</parameter> field of a
6839 parameter structure is true, the
<parameter>u.integer
</parameter> value is sent
6840 to the server as an integer of the indicated length (this must be
6841 2 or
4 bytes); proper byte-swapping occurs. When
<parameter>isint
</parameter>
6842 is false, the indicated number of bytes at
<parameter>*u.ptr
</parameter> are
6843 sent with no processing; the data must be in the format expected by
6844 the server for binary transmission of the function's argument data
6845 type. (The declaration of
<parameter>u.ptr
</parameter> as being of
6846 type
<type>int *
</type> is historical; it would be better to consider
6847 it
<type>void *
</type>.)
6848 <parameter>result_buf
</parameter> points to the buffer in which to place
6849 the function's return value. The caller must have allocated sufficient
6850 space to store the return value. (There is no check!) The actual result
6851 length in bytes will be returned in the integer pointed to by
6852 <parameter>result_len
</parameter>. If a
2- or
4-byte integer result
6853 is expected, set
<parameter>result_is_int
</parameter> to
1, otherwise
6854 set it to
0. Setting
<parameter>result_is_int
</parameter> to
1 causes
6855 <application>libpq
</application> to byte-swap the value if necessary, so that it
6856 is delivered as a proper
<type>int
</type> value for the client machine;
6857 note that a
4-byte integer is delivered into
<parameter>*result_buf
</parameter>
6858 for either allowed result size.
6859 When
<parameter>result_is_int
</parameter> is
0, the binary-format byte string
6860 sent by the server is returned unmodified. (In this case it's better
6861 to consider
<parameter>result_buf
</parameter> as being of
6862 type
<type>void *
</type>.)
6866 <function>PQfn
</function> always returns a valid
6867 <structname>PGresult
</structname> pointer, with
6868 status
<literal>PGRES_COMMAND_OK
</literal> for success
6869 or
<literal>PGRES_FATAL_ERROR
</literal> if some problem was encountered.
6870 The result status should be
6871 checked before the result is used. The caller is responsible for
6872 freeing the
<structname>PGresult
</structname> with
6873 <xref linkend=
"libpq-PQclear"/> when it is no longer needed.
6877 To pass a NULL argument to the function, set
6878 the
<parameter>len
</parameter> field of that parameter structure
6879 to
<literal>-
1</literal>; the
<parameter>isint
</parameter>
6880 and
<parameter>u
</parameter> fields are then irrelevant.
6884 If the function returns NULL,
<parameter>*result_len
</parameter> is set
6885 to
<literal>-
1</literal>, and
<parameter>*result_buf
</parameter> is not
6890 Note that it is not possible to handle set-valued results when using
6891 this interface. Also, the function must be a plain function, not an
6892 aggregate, window function, or procedure.
6897 <sect1 id=
"libpq-notify">
6898 <title>Asynchronous Notification
</title>
6900 <indexterm zone=
"libpq-notify">
6901 <primary>NOTIFY
</primary>
6902 <secondary>in libpq
</secondary>
6906 <productname>PostgreSQL
</productname> offers asynchronous notification
6907 via the
<command>LISTEN
</command> and
<command>NOTIFY
</command>
6908 commands. A client session registers its interest in a particular
6909 notification channel with the
<command>LISTEN
</command> command (and
6910 can stop listening with the
<command>UNLISTEN
</command> command). All
6911 sessions listening on a particular channel will be notified
6912 asynchronously when a
<command>NOTIFY
</command> command with that
6913 channel name is executed by any session. A
<quote>payload
</quote> string can
6914 be passed to communicate additional data to the listeners.
6918 <application>libpq
</application> applications submit
6919 <command>LISTEN
</command>,
<command>UNLISTEN
</command>,
6920 and
<command>NOTIFY
</command> commands as
6921 ordinary SQL commands. The arrival of
<command>NOTIFY
</command>
6922 messages can subsequently be detected by calling
6923 <function id=
"libpq-PQnotifies">PQnotifies
</function>.
<indexterm><primary>PQnotifies
</primary></indexterm>
6927 The function
<function>PQnotifies
</function> returns the next notification
6928 from a list of unhandled notification messages received from the server.
6929 It returns a null pointer if there are no pending notifications. Once a
6930 notification is returned from
<function>PQnotifies
</function>, it is considered
6931 handled and will be removed from the list of notifications.
6934 PGnotify *PQnotifies(PGconn *conn);
6936 typedef struct pgNotify
6938 char *relname; /* notification channel name */
6939 int be_pid; /* process ID of notifying server process */
6940 char *extra; /* notification payload string */
6944 After processing a
<structname>PGnotify
</structname> object returned
6945 by
<function>PQnotifies
</function>, be sure to free it with
6946 <xref linkend=
"libpq-PQfreemem"/>. It is sufficient to free the
6947 <structname>PGnotify
</structname> pointer; the
6948 <structfield>relname
</structfield> and
<structfield>extra
</structfield>
6949 fields do not represent separate allocations. (The names of these fields
6950 are historical; in particular, channel names need not have anything to
6951 do with relation names.)
6955 <xref linkend=
"libpq-example-2"/> gives a sample program that illustrates
6956 the use of asynchronous notification.
6960 <function>PQnotifies
</function> does not actually read data from the
6961 server; it just returns messages previously absorbed by another
6962 <application>libpq
</application> function. In ancient releases of
6963 <application>libpq
</application>, the only way to ensure timely receipt
6964 of
<command>NOTIFY
</command> messages was to constantly submit commands, even
6965 empty ones, and then check
<function>PQnotifies
</function> after each
6966 <xref linkend=
"libpq-PQexec"/>. While this still works, it is deprecated
6967 as a waste of processing power.
6971 A better way to check for
<command>NOTIFY
</command> messages when you have no
6972 useful commands to execute is to call
6973 <xref linkend=
"libpq-PQconsumeInput"/>, then check
6974 <function>PQnotifies
</function>. You can use
6975 <function>select()
</function> to wait for data to arrive from the
6976 server, thereby using no
<acronym>CPU
</acronym> power unless there is
6977 something to do. (See
<xref linkend=
"libpq-PQsocket"/> to obtain the file
6978 descriptor number to use with
<function>select()
</function>.) Note that
6979 this will work OK whether you submit commands with
6980 <xref linkend=
"libpq-PQsendQuery"/>/
<xref linkend=
"libpq-PQgetResult"/> or
6981 simply use
<xref linkend=
"libpq-PQexec"/>. You should, however, remember
6982 to check
<function>PQnotifies
</function> after each
6983 <xref linkend=
"libpq-PQgetResult"/> or
<xref linkend=
"libpq-PQexec"/>, to
6984 see if any notifications came in during the processing of the command.
6989 <sect1 id=
"libpq-copy">
6990 <title>Functions Associated with the
<command>COPY
</command> Command
</title>
6992 <indexterm zone=
"libpq-copy">
6993 <primary>COPY
</primary>
6994 <secondary>with libpq
</secondary>
6998 The
<command>COPY
</command> command in
6999 <productname>PostgreSQL
</productname> has options to read from or write
7000 to the network connection used by
<application>libpq
</application>.
7001 The functions described in this section allow applications to take
7002 advantage of this capability by supplying or consuming copied data.
7006 The overall process is that the application first issues the SQL
7007 <command>COPY
</command> command via
<xref linkend=
"libpq-PQexec"/> or one
7008 of the equivalent functions. The response to this (if there is no
7009 error in the command) will be a
<structname>PGresult
</structname> object bearing
7010 a status code of
<literal>PGRES_COPY_OUT
</literal> or
7011 <literal>PGRES_COPY_IN
</literal> (depending on the specified copy
7012 direction). The application should then use the functions of this
7013 section to receive or transmit data rows. When the data transfer is
7014 complete, another
<structname>PGresult
</structname> object is returned to indicate
7015 success or failure of the transfer. Its status will be
7016 <literal>PGRES_COMMAND_OK
</literal> for success or
7017 <literal>PGRES_FATAL_ERROR
</literal> if some problem was encountered.
7018 At this point further SQL commands can be issued via
7019 <xref linkend=
"libpq-PQexec"/>. (It is not possible to execute other SQL
7020 commands using the same connection while the
<command>COPY
</command>
7021 operation is in progress.)
7025 If a
<command>COPY
</command> command is issued via
7026 <xref linkend=
"libpq-PQexec"/> in a string that could contain additional
7027 commands, the application must continue fetching results via
7028 <xref linkend=
"libpq-PQgetResult"/> after completing the
<command>COPY
</command>
7029 sequence. Only when
<xref linkend=
"libpq-PQgetResult"/> returns
7030 <symbol>NULL
</symbol> is it certain that the
<xref linkend=
"libpq-PQexec"/>
7031 command string is done and it is safe to issue more commands.
7035 The functions of this section should be executed only after obtaining
7036 a result status of
<literal>PGRES_COPY_OUT
</literal> or
7037 <literal>PGRES_COPY_IN
</literal> from
<xref linkend=
"libpq-PQexec"/> or
7038 <xref linkend=
"libpq-PQgetResult"/>.
7042 A
<structname>PGresult
</structname> object bearing one of these status values
7043 carries some additional data about the
<command>COPY
</command> operation
7044 that is starting. This additional data is available using functions
7045 that are also used in connection with query results:
7048 <varlistentry id=
"libpq-PQnfields-1">
7049 <term><function>PQnfields
</function><indexterm
7050 ><primary>PQnfields
</primary><secondary>with COPY
</secondary></indexterm></term>
7054 Returns the number of columns (fields) to be copied.
7059 <varlistentry id=
"libpq-PQbinaryTuples-1">
7060 <term><function>PQbinaryTuples
</function><indexterm
7061 ><primary>PQbinaryTuples
</primary><secondary>with COPY
</secondary></indexterm></term>
7065 0 indicates the overall copy format is textual (rows separated by
7066 newlines, columns separated by separator characters, etc.).
1
7067 indicates the overall copy format is binary. See
<xref
7068 linkend=
"sql-copy"/> for more information.
7073 <varlistentry id=
"libpq-PQfformat-1">
7074 <term><function>PQfformat
</function><indexterm
7075 ><primary>PQfformat
</primary><secondary>with COPY
</secondary></indexterm></term>
7079 Returns the format code (
0 for text,
1 for binary) associated with
7080 each column of the copy operation. The per-column format codes
7081 will always be zero when the overall copy format is textual, but
7082 the binary format can support both text and binary columns.
7083 (However, as of the current implementation of
<command>COPY
</command>,
7084 only binary columns appear in a binary copy; so the per-column
7085 formats always match the overall format at present.)
7092 <sect2 id=
"libpq-copy-send">
7093 <title>Functions for Sending
<command>COPY
</command> Data
</title>
7096 These functions are used to send data during
<literal>COPY FROM
7097 STDIN
</literal>. They will fail if called when the connection is not in
7098 <literal>COPY_IN
</literal> state.
7102 <varlistentry id=
"libpq-PQputCopyData">
7103 <term><function>PQputCopyData
</function><indexterm><primary>PQputCopyData
</primary></indexterm></term>
7107 Sends data to the server during
<literal>COPY_IN
</literal> state.
7109 int PQputCopyData(PGconn *conn,
7116 Transmits the
<command>COPY
</command> data in the specified
7117 <parameter>buffer
</parameter>, of length
<parameter>nbytes
</parameter>, to the server.
7118 The result is
1 if the data was queued, zero if it was not queued
7119 because of full buffers (this will only happen in nonblocking mode),
7120 or -
1 if an error occurred.
7121 (Use
<xref linkend=
"libpq-PQerrorMessage"/> to retrieve details if
7122 the return value is -
1. If the value is zero, wait for write-ready
7127 The application can divide the
<command>COPY
</command> data stream
7128 into buffer loads of any convenient size. Buffer-load boundaries
7129 have no semantic significance when sending. The contents of the
7130 data stream must match the data format expected by the
7131 <command>COPY
</command> command; see
<xref linkend=
"sql-copy"/> for details.
7136 <varlistentry id=
"libpq-PQputCopyEnd">
7137 <term><function>PQputCopyEnd
</function><indexterm><primary>PQputCopyEnd
</primary></indexterm></term>
7141 Sends end-of-data indication to the server during
<literal>COPY_IN
</literal> state.
7143 int PQputCopyEnd(PGconn *conn,
7144 const char *errormsg);
7149 Ends the
<literal>COPY_IN
</literal> operation successfully if
7150 <parameter>errormsg
</parameter> is
<symbol>NULL
</symbol>. If
7151 <parameter>errormsg
</parameter> is not
<symbol>NULL
</symbol> then the
7152 <command>COPY
</command> is forced to fail, with the string pointed to by
7153 <parameter>errormsg
</parameter> used as the error message. (One should not
7154 assume that this exact error message will come back from the server,
7155 however, as the server might have already failed the
7156 <command>COPY
</command> for its own reasons.)
7160 The result is
1 if the termination message was sent; or in
7161 nonblocking mode, this may only indicate that the termination
7162 message was successfully queued. (In nonblocking mode, to be
7163 certain that the data has been sent, you should next wait for
7164 write-ready and call
<xref linkend=
"libpq-PQflush"/>, repeating until it
7165 returns zero.) Zero indicates that the function could not queue
7166 the termination message because of full buffers; this will only
7167 happen in nonblocking mode. (In this case, wait for
7168 write-ready and try the
<xref linkend=
"libpq-PQputCopyEnd"/> call
7169 again.) If a hard error occurs, -
1 is returned; you can use
7170 <xref linkend=
"libpq-PQerrorMessage"/> to retrieve details.
7174 After successfully calling
<xref linkend=
"libpq-PQputCopyEnd"/>, call
7175 <xref linkend=
"libpq-PQgetResult"/> to obtain the final result status of the
7176 <command>COPY
</command> command. One can wait for this result to be
7177 available in the usual way. Then return to normal operation.
7185 <sect2 id=
"libpq-copy-receive">
7186 <title>Functions for Receiving
<command>COPY
</command> Data
</title>
7189 These functions are used to receive data during
<literal>COPY TO
7190 STDOUT
</literal>. They will fail if called when the connection is not in
7191 <literal>COPY_OUT
</literal> state.
7195 <varlistentry id=
"libpq-PQgetCopyData">
7196 <term><function>PQgetCopyData
</function><indexterm><primary>PQgetCopyData
</primary></indexterm></term>
7200 Receives data from the server during
<literal>COPY_OUT
</literal> state.
7202 int PQgetCopyData(PGconn *conn,
7209 Attempts to obtain another row of data from the server during a
7210 <command>COPY
</command>. Data is always returned one data row at
7211 a time; if only a partial row is available, it is not returned.
7212 Successful return of a data row involves allocating a chunk of
7213 memory to hold the data. The
<parameter>buffer
</parameter> parameter must
7214 be non-
<symbol>NULL
</symbol>.
<parameter>*buffer
</parameter> is set to
7215 point to the allocated memory, or to
<symbol>NULL
</symbol> in cases
7216 where no buffer is returned. A non-
<symbol>NULL
</symbol> result
7217 buffer should be freed using
<xref linkend=
"libpq-PQfreemem"/> when no longer
7222 When a row is successfully returned, the return value is the number
7223 of data bytes in the row (this will always be greater than zero).
7224 The returned string is always null-terminated, though this is
7225 probably only useful for textual
<command>COPY
</command>. A result
7226 of zero indicates that the
<command>COPY
</command> is still in
7227 progress, but no row is yet available (this is only possible when
7228 <parameter>async
</parameter> is true). A result of -
1 indicates that the
7229 <command>COPY
</command> is done. A result of -
2 indicates that an
7230 error occurred (consult
<xref linkend=
"libpq-PQerrorMessage"/> for the reason).
7234 When
<parameter>async
</parameter> is true (not zero),
7235 <xref linkend=
"libpq-PQgetCopyData"/> will not block waiting for input; it
7236 will return zero if the
<command>COPY
</command> is still in progress
7237 but no complete row is available. (In this case wait for read-ready
7238 and then call
<xref linkend=
"libpq-PQconsumeInput"/> before calling
7239 <xref linkend=
"libpq-PQgetCopyData"/> again.) When
<parameter>async
</parameter> is
7240 false (zero),
<xref linkend=
"libpq-PQgetCopyData"/> will block until data is
7241 available or the operation completes.
7245 After
<xref linkend=
"libpq-PQgetCopyData"/> returns -
1, call
7246 <xref linkend=
"libpq-PQgetResult"/> to obtain the final result status of the
7247 <command>COPY
</command> command. One can wait for this result to be
7248 available in the usual way. Then return to normal operation.
7256 <sect2 id=
"libpq-copy-deprecated">
7257 <title>Obsolete Functions for
<command>COPY
</command></title>
7260 These functions represent older methods of handling
<command>COPY
</command>.
7261 Although they still work, they are deprecated due to poor error handling,
7262 inconvenient methods of detecting end-of-data, and lack of support for binary
7263 or nonblocking transfers.
7267 <varlistentry id=
"libpq-PQgetline">
7268 <term><function>PQgetline
</function><indexterm><primary>PQgetline
</primary></indexterm></term>
7272 Reads a newline-terminated line of characters (transmitted
7273 by the server) into a buffer string of size
<parameter>length
</parameter>.
7275 int PQgetline(PGconn *conn,
7282 This function copies up to
<parameter>length
</parameter>-
1 characters into
7283 the buffer and converts the terminating newline into a zero byte.
7284 <xref linkend=
"libpq-PQgetline"/> returns
<symbol>EOF
</symbol> at the
7285 end of input,
0 if the entire line has been read, and
1 if the
7286 buffer is full but the terminating newline has not yet been read.
7289 Note that the application must check to see if a new line consists
7290 of the two characters
<literal>\.
</literal>, which indicates
7291 that the server has finished sending the results of the
7292 <command>COPY
</command> command. If the application might receive
7293 lines that are more than
<parameter>length
</parameter>-
1 characters long,
7294 care is needed to be sure it recognizes the
<literal>\.
</literal>
7295 line correctly (and does not, for example, mistake the end of a
7296 long data line for a terminator line).
7301 <varlistentry id=
"libpq-PQgetlineAsync">
7302 <term><function>PQgetlineAsync
</function><indexterm><primary>PQgetlineAsync
</primary></indexterm></term>
7306 Reads a row of
<command>COPY
</command> data (transmitted by the
7307 server) into a buffer without blocking.
7309 int PQgetlineAsync(PGconn *conn,
7316 This function is similar to
<xref linkend=
"libpq-PQgetline"/>, but it can be used
7318 that must read
<command>COPY
</command> data asynchronously, that is, without blocking.
7319 Having issued the
<command>COPY
</command> command and gotten a
<literal>PGRES_COPY_OUT
</literal>
7321 application should call
<xref linkend=
"libpq-PQconsumeInput"/> and
7322 <xref linkend=
"libpq-PQgetlineAsync"/> until the
7323 end-of-data signal is detected.
7326 Unlike
<xref linkend=
"libpq-PQgetline"/>, this function takes
7327 responsibility for detecting end-of-data.
7331 On each call,
<xref linkend=
"libpq-PQgetlineAsync"/> will return data if a
7332 complete data row is available in
<application>libpq
</application>'s input buffer.
7333 Otherwise, no data is returned until the rest of the row arrives.
7334 The function returns -
1 if the end-of-copy-data marker has been recognized,
7335 or
0 if no data is available, or a positive number giving the number of
7336 bytes of data returned. If -
1 is returned, the caller must next call
7337 <xref linkend=
"libpq-PQendcopy"/>, and then return to normal processing.
7341 The data returned will not extend beyond a data-row boundary. If possible
7342 a whole row will be returned at one time. But if the buffer offered by
7343 the caller is too small to hold a row sent by the server, then a partial
7344 data row will be returned. With textual data this can be detected by testing
7345 whether the last returned byte is
<literal>\n
</literal> or not. (In a binary
7346 <command>COPY
</command>, actual parsing of the
<command>COPY
</command> data format will be needed to make the
7347 equivalent determination.)
7348 The returned string is not null-terminated. (If you want to add a
7349 terminating null, be sure to pass a
<parameter>bufsize
</parameter> one smaller
7350 than the room actually available.)
7355 <varlistentry id=
"libpq-PQputline">
7356 <term><function>PQputline
</function><indexterm><primary>PQputline
</primary></indexterm></term>
7360 Sends a null-terminated string to the server. Returns
0 if
7361 OK and
<symbol>EOF
</symbol> if unable to send the string.
7363 int PQputline(PGconn *conn,
7364 const char *string);
7369 The
<command>COPY
</command> data stream sent by a series of calls
7370 to
<xref linkend=
"libpq-PQputline"/> has the same format as that
7371 returned by
<xref linkend=
"libpq-PQgetlineAsync"/>, except that
7372 applications are not obliged to send exactly one data row per
7373 <xref linkend=
"libpq-PQputline"/> call; it is okay to send a partial
7374 line or multiple lines per call.
7379 Before
<productname>PostgreSQL
</productname> protocol
3.0, it was necessary
7380 for the application to explicitly send the two characters
7381 <literal>\.
</literal> as a final line to indicate to the server that it had
7382 finished sending
<command>COPY
</command> data. While this still works, it is deprecated and the
7383 special meaning of
<literal>\.
</literal> can be expected to be removed in a
7384 future release. It is sufficient to call
<xref linkend=
"libpq-PQendcopy"/> after
7385 having sent the actual data.
7391 <varlistentry id=
"libpq-PQputnbytes">
7392 <term><function>PQputnbytes
</function><indexterm><primary>PQputnbytes
</primary></indexterm></term>
7396 Sends a non-null-terminated string to the server. Returns
7397 0 if OK and
<symbol>EOF
</symbol> if unable to send the string.
7399 int PQputnbytes(PGconn *conn,
7406 This is exactly like
<xref linkend=
"libpq-PQputline"/>, except that the data
7407 buffer need not be null-terminated since the number of bytes to send is
7408 specified directly. Use this procedure when sending binary data.
7413 <varlistentry id=
"libpq-PQendcopy">
7414 <term><function>PQendcopy
</function><indexterm><primary>PQendcopy
</primary></indexterm></term>
7418 Synchronizes with the server.
7420 int PQendcopy(PGconn *conn);
7422 This function waits until the server has finished the copying.
7423 It should either be issued when the last string has been sent
7424 to the server using
<xref linkend=
"libpq-PQputline"/> or when the
7425 last string has been received from the server using
7426 <function>PQgetline
</function>. It must be issued or the server
7427 will get
<quote>out of sync
</quote> with the client. Upon return
7428 from this function, the server is ready to receive the next SQL
7429 command. The return value is
0 on successful completion,
7430 nonzero otherwise. (Use
<xref linkend=
"libpq-PQerrorMessage"/> to
7431 retrieve details if the return value is nonzero.)
7435 When using
<xref linkend=
"libpq-PQgetResult"/>, the application should
7436 respond to a
<literal>PGRES_COPY_OUT
</literal> result by executing
7437 <xref linkend=
"libpq-PQgetline"/> repeatedly, followed by
7438 <xref linkend=
"libpq-PQendcopy"/> after the terminator line is seen.
7439 It should then return to the
<xref linkend=
"libpq-PQgetResult"/> loop
7440 until
<xref linkend=
"libpq-PQgetResult"/> returns a null pointer.
7441 Similarly a
<literal>PGRES_COPY_IN
</literal> result is processed
7442 by a series of
<xref linkend=
"libpq-PQputline"/> calls followed by
7443 <xref linkend=
"libpq-PQendcopy"/>, then return to the
7444 <xref linkend=
"libpq-PQgetResult"/> loop. This arrangement will
7445 ensure that a
<command>COPY
</command> command embedded in a series
7446 of
<acronym>SQL
</acronym> commands will be executed correctly.
7450 Older applications are likely to submit a
<command>COPY
</command>
7451 via
<xref linkend=
"libpq-PQexec"/> and assume that the transaction
7452 is done after
<xref linkend=
"libpq-PQendcopy"/>. This will work
7453 correctly only if the
<command>COPY
</command> is the only
7454 <acronym>SQL
</acronym> command in the command string.
7464 <sect1 id=
"libpq-control">
7465 <title>Control Functions
</title>
7468 These functions control miscellaneous details of
<application>libpq
</application>'s
7473 <varlistentry id=
"libpq-PQclientEncoding">
7474 <term><function>PQclientEncoding
</function><indexterm><primary>PQclientEncoding
</primary></indexterm></term>
7478 Returns the client encoding.
7480 int PQclientEncoding(const PGconn *
<replaceable>conn
</replaceable>);
7483 Note that it returns the encoding ID, not a symbolic string
7484 such as
<literal>EUC_JP
</literal>. If unsuccessful, it returns -
1.
7485 To convert an encoding ID to an encoding name, you
7489 char *pg_encoding_to_char(int
<replaceable>encoding_id
</replaceable>);
7495 <varlistentry id=
"libpq-PQsetClientEncoding">
7496 <term><function>PQsetClientEncoding
</function><indexterm><primary>PQsetClientEncoding
</primary></indexterm></term>
7500 Sets the client encoding.
7502 int PQsetClientEncoding(PGconn *
<replaceable>conn
</replaceable>, const char *
<replaceable>encoding
</replaceable>);
7505 <replaceable>conn
</replaceable> is a connection to the server,
7506 and
<replaceable>encoding
</replaceable> is the encoding you want to
7507 use. If the function successfully sets the encoding, it returns
0,
7508 otherwise -
1. The current encoding for this connection can be
7509 determined by using
<xref linkend=
"libpq-PQclientEncoding"/>.
7514 <varlistentry id=
"libpq-PQsetErrorVerbosity">
7515 <term><function>PQsetErrorVerbosity
</function><indexterm><primary>PQsetErrorVerbosity
</primary></indexterm></term>
7519 Determines the verbosity of messages returned by
7520 <xref linkend=
"libpq-PQerrorMessage"/> and
<xref linkend=
"libpq-PQresultErrorMessage"/>.
7530 PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity);
7533 <xref linkend=
"libpq-PQsetErrorVerbosity"/> sets the verbosity mode,
7534 returning the connection's previous setting.
7535 In
<firstterm>TERSE
</firstterm> mode, returned messages include
7536 severity, primary text, and position only; this will normally fit on a
7537 single line. The
<firstterm>DEFAULT
</firstterm> mode produces messages
7538 that include the above plus any detail, hint, or context fields (these
7539 might span multiple lines). The
<firstterm>VERBOSE
</firstterm> mode
7540 includes all available fields. The
<firstterm>SQLSTATE
</firstterm>
7541 mode includes only the error severity and the
<symbol>SQLSTATE
</symbol>
7542 error code, if one is available (if not, the output is like
7543 <firstterm>TERSE
</firstterm> mode).
7547 Changing the verbosity setting does not affect the messages available
7548 from already-existing
<structname>PGresult
</structname> objects, only
7549 subsequently-created ones.
7550 (But see
<xref linkend=
"libpq-PQresultVerboseErrorMessage"/> if you
7551 want to print a previous error with a different verbosity.)
7556 <varlistentry id=
"libpq-PQsetErrorContextVisibility">
7557 <term><function>PQsetErrorContextVisibility
</function><indexterm><primary>PQsetErrorContextVisibility
</primary></indexterm></term>
7561 Determines the handling of
<literal>CONTEXT
</literal> fields in messages
7562 returned by
<xref linkend=
"libpq-PQerrorMessage"/>
7563 and
<xref linkend=
"libpq-PQresultErrorMessage"/>.
7567 PQSHOW_CONTEXT_NEVER,
7568 PQSHOW_CONTEXT_ERRORS,
7569 PQSHOW_CONTEXT_ALWAYS
7570 } PGContextVisibility;
7572 PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context);
7575 <xref linkend=
"libpq-PQsetErrorContextVisibility"/> sets the context display mode,
7576 returning the connection's previous setting. This mode controls
7577 whether the
<literal>CONTEXT
</literal> field is included in messages.
7578 The
<firstterm>NEVER
</firstterm> mode
7579 never includes
<literal>CONTEXT
</literal>, while
<firstterm>ALWAYS
</firstterm> always
7580 includes it if available. In
<firstterm>ERRORS
</firstterm> mode (the
7581 default),
<literal>CONTEXT
</literal> fields are included only in error
7582 messages, not in notices and warnings.
7583 (However, if the verbosity setting is
<firstterm>TERSE
</firstterm>
7584 or
<firstterm>SQLSTATE
</firstterm>,
<literal>CONTEXT
</literal> fields
7585 are omitted regardless of the context display mode.)
7589 Changing this mode does not
7590 affect the messages available from
7591 already-existing
<structname>PGresult
</structname> objects, only
7592 subsequently-created ones.
7593 (But see
<xref linkend=
"libpq-PQresultVerboseErrorMessage"/> if you
7594 want to print a previous error with a different display mode.)
7599 <varlistentry id=
"libpq-PQtrace">
7600 <term><function>PQtrace
</function><indexterm><primary>PQtrace
</primary></indexterm></term>
7604 Enables tracing of the client/server communication to a debugging file
7607 void PQtrace(PGconn *conn, FILE *stream);
7612 Each line consists of: an optional timestamp, a direction indicator
7613 (
<literal>F
</literal> for messages from client to server
7614 or
<literal>B
</literal> for messages from server to client),
7615 message length, message type, and message contents.
7616 Non-message contents fields (timestamp, direction, length and message type)
7617 are separated by a tab. Message contents are separated by a space.
7618 Protocol strings are enclosed in double quotes, while strings used as data
7619 values are enclosed in single quotes. Non-printable chars are printed as
7620 hexadecimal escapes.
7621 Further message-type-specific detail can be found in
7622 <xref linkend=
"protocol-message-formats"/>.
7627 On Windows, if the
<application>libpq
</application> library and an application are
7628 compiled with different flags, this function call will crash the
7629 application because the internal representation of the
<literal>FILE
</literal>
7630 pointers differ. Specifically, multithreaded/single-threaded,
7631 release/debug, and static/dynamic flags should be the same for the
7632 library and all applications using that library.
7639 <varlistentry id=
"libpq-PQsetTraceFlags">
7640 <term><function>PQsetTraceFlags
</function><indexterm><primary>PQsetTraceFlags
</primary></indexterm></term>
7644 Controls the tracing behavior of client/server communication.
7646 void PQsetTraceFlags(PGconn *conn, int flags);
7651 <literal>flags
</literal> contains flag bits describing the operating mode
7653 If
<literal>flags
</literal> contains
<literal>PQTRACE_SUPPRESS_TIMESTAMPS
</literal>,
7654 then the timestamp is not included when printing each message.
7655 If
<literal>flags
</literal> contains
<literal>PQTRACE_REGRESS_MODE
</literal>,
7656 then some fields are redacted when printing each message, such as object
7657 OIDs, to make the output more convenient to use in testing frameworks.
7658 This function must be called after calling
<function>PQtrace
</function>.
7664 <varlistentry id=
"libpq-PQuntrace">
7665 <term><function>PQuntrace
</function><indexterm><primary>PQuntrace
</primary></indexterm></term>
7669 Disables tracing started by
<xref linkend=
"libpq-PQtrace"/>.
7671 void PQuntrace(PGconn *conn);
7680 <sect1 id=
"libpq-misc">
7681 <title>Miscellaneous Functions
</title>
7684 As always, there are some functions that just don't fit anywhere.
7688 <varlistentry id=
"libpq-PQfreemem">
7689 <term><function>PQfreemem
</function><indexterm><primary>PQfreemem
</primary></indexterm></term>
7693 Frees memory allocated by
<application>libpq
</application>.
7695 void PQfreemem(void *ptr);
7700 Frees memory allocated by
<application>libpq
</application>, particularly
7701 <xref linkend=
"libpq-PQescapeByteaConn"/>,
7702 <xref linkend=
"libpq-PQescapeBytea"/>,
7703 <xref linkend=
"libpq-PQunescapeBytea"/>,
7704 and
<function>PQnotifies
</function>.
7705 It is particularly important that this function, rather than
7706 <function>free()
</function>, be used on Microsoft Windows. This is because
7707 allocating memory in a DLL and releasing it in the application works
7708 only if multithreaded/single-threaded, release/debug, and static/dynamic
7709 flags are the same for the DLL and the application. On non-Microsoft
7710 Windows platforms, this function is the same as the standard library
7711 function
<function>free()
</function>.
7716 <varlistentry id=
"libpq-PQconninfoFree">
7717 <term><function>PQconninfoFree
</function><indexterm><primary>PQconninfoFree
</primary></indexterm></term>
7721 Frees the data structures allocated by
7722 <xref linkend=
"libpq-PQconndefaults"/> or
<xref linkend=
"libpq-PQconninfoParse"/>.
7724 void PQconninfoFree(PQconninfoOption *connOptions);
7726 If the argument is a
<symbol>NULL
</symbol> pointer, no operation is
7731 A simple
<xref linkend=
"libpq-PQfreemem"/> will not do for this, since
7732 the array contains references to subsidiary strings.
7737 <varlistentry id=
"libpq-PQencryptPasswordConn">
7738 <term><function>PQencryptPasswordConn
</function><indexterm><primary>PQencryptPasswordConn
</primary></indexterm></term>
7742 Prepares the encrypted form of a
<productname>PostgreSQL
</productname> password.
7744 char *PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm);
7746 This function is intended to be used by client applications that
7747 wish to send commands like
<literal>ALTER USER joe PASSWORD
7748 'pwd'
</literal>. It is good practice not to send the original cleartext
7749 password in such a command, because it might be exposed in command
7750 logs, activity displays, and so on. Instead, use this function to
7751 convert the password to encrypted form before it is sent.
7755 The
<parameter>passwd
</parameter> and
<parameter>user
</parameter> arguments
7756 are the cleartext password, and the SQL name of the user it is for.
7757 <parameter>algorithm
</parameter> specifies the encryption algorithm
7758 to use to encrypt the password. Currently supported algorithms are
7759 <literal>md5
</literal> and
<literal>scram-sha-
256</literal> (
<literal>on
</literal> and
7760 <literal>off
</literal> are also accepted as aliases for
<literal>md5
</literal>, for
7761 compatibility with older server versions). Note that support for
7762 <literal>scram-sha-
256</literal> was introduced in
<productname>PostgreSQL
</productname>
7763 version
10, and will not work correctly with older server versions. If
7764 <parameter>algorithm
</parameter> is
<symbol>NULL
</symbol>, this function will query
7765 the server for the current value of the
7766 <xref linkend=
"guc-password-encryption"/> setting. That can block, and
7767 will fail if the current transaction is aborted, or if the connection
7768 is busy executing another query. If you wish to use the default
7769 algorithm for the server but want to avoid blocking, query
7770 <varname>password_encryption
</varname> yourself before calling
7771 <xref linkend=
"libpq-PQencryptPasswordConn"/>, and pass that value as the
7772 <parameter>algorithm
</parameter>.
7776 The return value is a string allocated by
<function>malloc
</function>.
7777 The caller can assume the string doesn't contain any special characters
7778 that would require escaping. Use
<xref linkend=
"libpq-PQfreemem"/> to free the
7779 result when done with it. On error, returns
<symbol>NULL
</symbol>, and
7780 a suitable message is stored in the connection object.
7786 <varlistentry id=
"libpq-PQchangePassword">
7787 <term><function>PQchangePassword
</function><indexterm><primary>PQchangePassword
</primary></indexterm></term>
7791 Changes a
<productname>PostgreSQL
</productname> password.
7793 PGresult *PQchangePassword(PGconn *conn, const char *user, const char *passwd);
7795 This function uses
<function>PQencryptPasswordConn
</function>
7796 to build and execute the command
<literal>ALTER USER ... PASSWORD
7797 '...'
</literal>, thereby changing the user's password. It exists for
7798 the same reason as
<function>PQencryptPasswordConn
</function>, but
7799 is more convenient as it both builds and runs the command for you.
7800 <xref linkend=
"libpq-PQencryptPasswordConn"/> is passed a
7801 <symbol>NULL
</symbol> for the algorithm argument, hence encryption is
7802 done according to the server's
<xref linkend=
"guc-password-encryption"/>
7807 The
<parameter>user
</parameter> and
<parameter>passwd
</parameter> arguments
7808 are the SQL name of the target user, and the new cleartext password.
7812 Returns a
<structname>PGresult
</structname> pointer representing
7813 the result of the
<literal>ALTER USER
</literal> command, or
7814 a null pointer if the routine failed before issuing any command.
7815 The
<xref linkend=
"libpq-PQresultStatus"/> function should be called
7816 to check the return value for any errors (including the value of a null
7817 pointer, in which case it will return
7818 <symbol>PGRES_FATAL_ERROR
</symbol>). Use
7819 <xref linkend=
"libpq-PQerrorMessage"/> to get more information about
7825 <varlistentry id=
"libpq-PQencryptPassword">
7826 <term><function>PQencryptPassword
</function><indexterm><primary>PQencryptPassword
</primary></indexterm></term>
7830 Prepares the md5-encrypted form of a
<productname>PostgreSQL
</productname> password.
7832 char *PQencryptPassword(const char *passwd, const char *user);
7834 <xref linkend=
"libpq-PQencryptPassword"/> is an older, deprecated version of
7835 <xref linkend=
"libpq-PQencryptPasswordConn"/>. The difference is that
7836 <xref linkend=
"libpq-PQencryptPassword"/> does not
7837 require a connection object, and
<literal>md5
</literal> is always used as the
7838 encryption algorithm.
7843 <varlistentry id=
"libpq-PQmakeEmptyPGresult">
7844 <term><function>PQmakeEmptyPGresult
</function><indexterm><primary>PQmakeEmptyPGresult
</primary></indexterm></term>
7848 Constructs an empty
<structname>PGresult
</structname> object with the given status.
7850 PGresult *PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status);
7855 This is
<application>libpq
</application>'s internal function to allocate and
7856 initialize an empty
<structname>PGresult
</structname> object. This
7857 function returns
<symbol>NULL
</symbol> if memory could not be allocated. It is
7858 exported because some applications find it useful to generate result
7859 objects (particularly objects with error status) themselves. If
7860 <parameter>conn
</parameter> is not null and
<parameter>status
</parameter>
7861 indicates an error, the current error message of the specified
7862 connection is copied into the
<structname>PGresult
</structname>.
7863 Also, if
<parameter>conn
</parameter> is not null, any event procedures
7864 registered in the connection are copied into the
7865 <structname>PGresult
</structname>. (They do not get
7866 <literal>PGEVT_RESULTCREATE
</literal> calls, but see
7867 <xref linkend=
"libpq-PQfireResultCreateEvents"/>.)
7868 Note that
<xref linkend=
"libpq-PQclear"/> should eventually be called
7869 on the object, just as with a
<structname>PGresult
</structname>
7870 returned by
<application>libpq
</application> itself.
7875 <varlistentry id=
"libpq-PQfireResultCreateEvents">
7876 <term><function>PQfireResultCreateEvents
</function><indexterm><primary>PQfireResultCreateEvents
</primary></indexterm></term>
7879 Fires a
<literal>PGEVT_RESULTCREATE
</literal> event (see
<xref
7880 linkend=
"libpq-events"/>) for each event procedure registered in the
7881 <structname>PGresult
</structname> object. Returns non-zero for success,
7882 zero if any event procedure fails.
7885 int PQfireResultCreateEvents(PGconn *conn, PGresult *res);
7890 The
<literal>conn
</literal> argument is passed through to event procedures
7891 but not used directly. It can be
<symbol>NULL
</symbol> if the event
7892 procedures won't use it.
7896 Event procedures that have already received a
7897 <literal>PGEVT_RESULTCREATE
</literal> or
<literal>PGEVT_RESULTCOPY
</literal> event
7898 for this object are not fired again.
7902 The main reason that this function is separate from
7903 <xref linkend=
"libpq-PQmakeEmptyPGresult"/> is that it is often appropriate
7904 to create a
<structname>PGresult
</structname> and fill it with data
7905 before invoking the event procedures.
7910 <varlistentry id=
"libpq-PQcopyResult">
7911 <term><function>PQcopyResult
</function><indexterm><primary>PQcopyResult
</primary></indexterm></term>
7915 Makes a copy of a
<structname>PGresult
</structname> object. The copy is
7916 not linked to the source result in any way and
7917 <xref linkend=
"libpq-PQclear"/> must be called when the copy is no longer
7918 needed. If the function fails,
<symbol>NULL
</symbol> is returned.
7921 PGresult *PQcopyResult(const PGresult *src, int flags);
7926 This is not intended to make an exact copy. The returned result is
7927 always put into
<literal>PGRES_TUPLES_OK
</literal> status, and does not
7928 copy any error message in the source. (It does copy the command status
7929 string, however.) The
<parameter>flags
</parameter> argument determines
7930 what else is copied. It is a bitwise OR of several flags.
7931 <literal>PG_COPYRES_ATTRS
</literal> specifies copying the source
7932 result's attributes (column definitions).
7933 <literal>PG_COPYRES_TUPLES
</literal> specifies copying the source
7934 result's tuples. (This implies copying the attributes, too.)
7935 <literal>PG_COPYRES_NOTICEHOOKS
</literal> specifies
7936 copying the source result's notify hooks.
7937 <literal>PG_COPYRES_EVENTS
</literal> specifies copying the source
7938 result's events. (But any instance data associated with the source
7940 The event procedures receive
<literal>PGEVT_RESULTCOPY
</literal> events.
7945 <varlistentry id=
"libpq-PQsetResultAttrs">
7946 <term><function>PQsetResultAttrs
</function><indexterm><primary>PQsetResultAttrs
</primary></indexterm></term>
7950 Sets the attributes of a
<structname>PGresult
</structname> object.
7952 int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs);
7957 The provided
<parameter>attDescs
</parameter> are copied into the result.
7958 If the
<parameter>attDescs
</parameter> pointer is
<symbol>NULL
</symbol> or
7959 <parameter>numAttributes
</parameter> is less than one, the request is
7960 ignored and the function succeeds. If
<parameter>res
</parameter>
7961 already contains attributes, the function will fail. If the function
7962 fails, the return value is zero. If the function succeeds, the return
7968 <varlistentry id=
"libpq-PQsetvalue">
7969 <term><function>PQsetvalue
</function><indexterm><primary>PQsetvalue
</primary></indexterm></term>
7973 Sets a tuple field value of a
<structname>PGresult
</structname> object.
7975 int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len);
7980 The function will automatically grow the result's internal tuples array
7981 as needed. However, the
<parameter>tup_num
</parameter> argument must be
7982 less than or equal to
<xref linkend=
"libpq-PQntuples"/>, meaning this
7983 function can only grow the tuples array one tuple at a time. But any
7984 field of any existing tuple can be modified in any order. If a value at
7985 <parameter>field_num
</parameter> already exists, it will be overwritten.
7986 If
<parameter>len
</parameter> is -
1 or
7987 <parameter>value
</parameter> is
<symbol>NULL
</symbol>, the field value
7988 will be set to an SQL null value. The
7989 <parameter>value
</parameter> is copied into the result's private storage,
7990 thus is no longer needed after the function
7991 returns. If the function fails, the return value is zero. If the
7992 function succeeds, the return value is non-zero.
7997 <varlistentry id=
"libpq-PQresultAlloc">
7998 <term><function>PQresultAlloc
</function><indexterm><primary>PQresultAlloc
</primary></indexterm></term>
8002 Allocate subsidiary storage for a
<structname>PGresult
</structname> object.
8004 void *PQresultAlloc(PGresult *res, size_t nBytes);
8009 Any memory allocated with this function will be freed when
8010 <parameter>res
</parameter> is cleared. If the function fails,
8011 the return value is
<symbol>NULL
</symbol>. The result is
8012 guaranteed to be adequately aligned for any type of data,
8013 just as for
<function>malloc
</function>.
8018 <varlistentry id=
"libpq-PQresultMemorySize">
8019 <term><function>PQresultMemorySize
</function><indexterm><primary>PQresultMemorySize
</primary></indexterm></term>
8023 Retrieves the number of bytes allocated for
8024 a
<structname>PGresult
</structname> object.
8026 size_t PQresultMemorySize(const PGresult *res);
8031 This value is the sum of all
<function>malloc
</function> requests
8032 associated with the
<structname>PGresult
</structname> object, that is,
8033 all the memory that will be freed by
<xref linkend=
"libpq-PQclear"/>.
8034 This information can be useful for managing memory consumption.
8039 <varlistentry id=
"libpq-PQlibVersion">
8040 <term><function>PQlibVersion
</function><indexterm
8041 ><primary>PQlibVersion
</primary><seealso>PQserverVersion
</seealso></indexterm></term>
8045 Return the version of
<productname>libpq
</productname> that is being used.
8047 int PQlibVersion(void);
8052 The result of this function can be used to determine, at
8053 run time, whether specific functionality is available in the currently
8054 loaded version of libpq. The function can be used, for example,
8055 to determine which connection options are available in
8056 <xref linkend=
"libpq-PQconnectdb"/>.
8060 The result is formed by multiplying the library's major version
8061 number by
10000 and adding the minor version number. For example,
8062 version
10.1 will be returned as
100001, and version
11.0 will be
8067 Prior to major version
10,
<productname>PostgreSQL
</productname> used
8068 three-part version numbers in which the first two parts together
8069 represented the major version. For those
8070 versions,
<xref linkend=
"libpq-PQlibVersion"/> uses two digits for each
8071 part; for example version
9.1.5 will be returned as
90105, and
8072 version
9.2.0 will be returned as
90200.
8076 Therefore, for purposes of determining feature compatibility,
8077 applications should divide the result of
<xref linkend=
"libpq-PQlibVersion"/>
8078 by
100 not
10000 to determine a logical major version number.
8079 In all release series, only the last two digits differ between
8080 minor releases (bug-fix releases).
8085 This function appeared in
<productname>PostgreSQL
</productname> version
9.1, so
8086 it cannot be used to detect required functionality in earlier
8087 versions, since calling it will create a link dependency
8088 on version
9.1 or later.
8094 <varlistentry id=
"libpq-PQgetCurrentTimeUSec">
8095 <term><function>PQgetCurrentTimeUSec
</function><indexterm><primary>PQgetCurrentTimeUSec
</primary></indexterm></term>
8099 Retrieves the current time, expressed as the number of microseconds
8100 since the Unix epoch (that is,
<type>time_t
</type> times
1 million).
8102 pg_usec_time_t PQgetCurrentTimeUSec(void);
8107 This is primarily useful for calculating timeout values to use with
8108 <xref linkend=
"libpq-PQsocketPoll"/>.
8117 <sect1 id=
"libpq-notice-processing">
8118 <title>Notice Processing
</title>
8120 <indexterm zone=
"libpq-notice-processing">
8121 <primary>notice processing
</primary>
8122 <secondary>in libpq
</secondary>
8126 Notice and warning messages generated by the server are not returned
8127 by the query execution functions, since they do not imply failure of
8128 the query. Instead they are passed to a notice handling function, and
8129 execution continues normally after the handler returns. The default
8130 notice handling function prints the message on
8131 <filename>stderr
</filename>, but the application can override this
8132 behavior by supplying its own handling function.
8136 For historical reasons, there are two levels of notice handling, called
8137 the notice receiver and notice processor. The default behavior is for
8138 the notice receiver to format the notice and pass a string to the notice
8139 processor for printing. However, an application that chooses to provide
8140 its own notice receiver will typically ignore the notice processor
8141 layer and just do all the work in the notice receiver.
8145 The function
<function id=
"libpq-PQsetNoticeReceiver">PQsetNoticeReceiver
</function>
8146 <indexterm><primary>notice receiver
</primary></indexterm>
8147 <indexterm><primary>PQsetNoticeReceiver
</primary></indexterm> sets or
8148 examines the current notice receiver for a connection object.
8149 Similarly,
<function id=
"libpq-PQsetNoticeProcessor">PQsetNoticeProcessor
</function>
8150 <indexterm><primary>notice processor
</primary></indexterm>
8151 <indexterm><primary>PQsetNoticeProcessor
</primary></indexterm> sets or
8152 examines the current notice processor.
8155 typedef void (*PQnoticeReceiver) (void *arg, const PGresult *res);
8158 PQsetNoticeReceiver(PGconn *conn,
8159 PQnoticeReceiver proc,
8162 typedef void (*PQnoticeProcessor) (void *arg, const char *message);
8165 PQsetNoticeProcessor(PGconn *conn,
8166 PQnoticeProcessor proc,
8170 Each of these functions returns the previous notice receiver or
8171 processor function pointer, and sets the new value. If you supply a
8172 null function pointer, no action is taken, but the current pointer is
8177 When a notice or warning message is received from the server, or
8178 generated internally by
<application>libpq
</application>, the notice
8179 receiver function is called. It is passed the message in the form of
8180 a
<symbol>PGRES_NONFATAL_ERROR
</symbol>
8181 <structname>PGresult
</structname>. (This allows the receiver to extract
8182 individual fields using
<xref linkend=
"libpq-PQresultErrorField"/>, or obtain a
8183 complete preformatted message using
<xref linkend=
"libpq-PQresultErrorMessage"/>
8184 or
<xref linkend=
"libpq-PQresultVerboseErrorMessage"/>.) The same
8185 void pointer passed to
<function>PQsetNoticeReceiver
</function> is also
8186 passed. (This pointer can be used to access application-specific state
8191 The default notice receiver simply extracts the message (using
8192 <xref linkend=
"libpq-PQresultErrorMessage"/>) and passes it to the notice
8197 The notice processor is responsible for handling a notice or warning
8198 message given in text form. It is passed the string text of the message
8199 (including a trailing newline), plus a void pointer that is the same
8200 one passed to
<function>PQsetNoticeProcessor
</function>. (This pointer
8201 can be used to access application-specific state if needed.)
8205 The default notice processor is simply:
8208 defaultNoticeProcessor(void *arg, const char *message)
8210 fprintf(stderr,
"%s", message);
8216 Once you have set a notice receiver or processor, you should expect
8217 that that function could be called as long as either the
8218 <structname>PGconn
</structname> object or
<structname>PGresult
</structname> objects made
8219 from it exist. At creation of a
<structname>PGresult
</structname>, the
8220 <structname>PGconn
</structname>'s current notice handling pointers are copied
8221 into the
<structname>PGresult
</structname> for possible use by functions like
8222 <xref linkend=
"libpq-PQgetvalue"/>.
8227 <sect1 id=
"libpq-events">
8228 <title>Event System
</title>
8231 <application>libpq
</application>'s event system is designed to notify
8232 registered event handlers about interesting
8233 <application>libpq
</application> events, such as the creation or
8234 destruction of
<structname>PGconn
</structname> and
8235 <structname>PGresult
</structname> objects. A principal use case is that
8236 this allows applications to associate their own data with a
8237 <structname>PGconn
</structname> or
<structname>PGresult
</structname>
8238 and ensure that that data is freed at an appropriate time.
8242 Each registered event handler is associated with two pieces of data,
8243 known to
<application>libpq
</application> only as opaque
<literal>void *
</literal>
8244 pointers. There is a
<firstterm>pass-through
</firstterm> pointer that is provided
8245 by the application when the event handler is registered with a
8246 <structname>PGconn
</structname>. The pass-through pointer never changes for the
8247 life of the
<structname>PGconn
</structname> and all
<structname>PGresult
</structname>s
8248 generated from it; so if used, it must point to long-lived data.
8249 In addition there is an
<firstterm>instance data
</firstterm> pointer, which starts
8250 out
<symbol>NULL
</symbol> in every
<structname>PGconn
</structname> and
<structname>PGresult
</structname>.
8251 This pointer can be manipulated using the
8252 <xref linkend=
"libpq-PQinstanceData"/>,
8253 <xref linkend=
"libpq-PQsetInstanceData"/>,
8254 <xref linkend=
"libpq-PQresultInstanceData"/> and
8255 <xref linkend=
"libpq-PQresultSetInstanceData"/> functions. Note that
8256 unlike the pass-through pointer, instance data of a
<structname>PGconn
</structname>
8257 is not automatically inherited by
<structname>PGresult
</structname>s created from
8258 it.
<application>libpq
</application> does not know what pass-through
8259 and instance data pointers point to (if anything) and will never attempt
8260 to free them
— that is the responsibility of the event handler.
8263 <sect2 id=
"libpq-events-types">
8264 <title>Event Types
</title>
8267 The enum
<literal>PGEventId
</literal> names the types of events handled by
8268 the event system. All its values have names beginning with
8269 <literal>PGEVT
</literal>. For each event type, there is a corresponding
8270 event info structure that carries the parameters passed to the event
8271 handlers. The event types are:
8275 <varlistentry id=
"libpq-pgevt-register">
8276 <term><literal>PGEVT_REGISTER
</literal></term>
8279 The register event occurs when
<xref linkend=
"libpq-PQregisterEventProc"/>
8280 is called. It is the ideal time to initialize any
8281 <literal>instanceData
</literal> an event procedure may need. Only one
8282 register event will be fired per event handler per connection. If the
8283 event procedure fails (returns zero), the registration is canceled.
8292 When a
<literal>PGEVT_REGISTER
</literal> event is received, the
8293 <parameter>evtInfo
</parameter> pointer should be cast to a
8294 <structname>PGEventRegister *
</structname>. This structure contains a
8295 <structname>PGconn
</structname> that should be in the
8296 <literal>CONNECTION_OK
</literal> status; guaranteed if one calls
8297 <xref linkend=
"libpq-PQregisterEventProc"/> right after obtaining a good
8298 <structname>PGconn
</structname>. When returning a failure code, all
8299 cleanup must be performed as no
<literal>PGEVT_CONNDESTROY
</literal>
8305 <varlistentry id=
"libpq-pgevt-connreset">
8306 <term><literal>PGEVT_CONNRESET
</literal></term>
8309 The connection reset event is fired on completion of
8310 <xref linkend=
"libpq-PQreset"/> or
<function>PQresetPoll
</function>. In
8311 both cases, the event is only fired if the reset was successful.
8312 The return value of the event procedure is ignored
8313 in
<productname>PostgreSQL
</productname> v15 and later.
8314 With earlier versions, however, it's important to return success
8315 (nonzero) or the connection will be aborted.
8324 When a
<literal>PGEVT_CONNRESET
</literal> event is received, the
8325 <parameter>evtInfo
</parameter> pointer should be cast to a
8326 <structname>PGEventConnReset *
</structname>. Although the contained
8327 <structname>PGconn
</structname> was just reset, all event data remains
8328 unchanged. This event should be used to reset/reload/requery any
8329 associated
<literal>instanceData
</literal>. Note that even if the
8330 event procedure fails to process
<literal>PGEVT_CONNRESET
</literal>, it will
8331 still receive a
<literal>PGEVT_CONNDESTROY
</literal> event when the connection
8337 <varlistentry id=
"libpq-pgevt-conndestroy">
8338 <term><literal>PGEVT_CONNDESTROY
</literal></term>
8341 The connection destroy event is fired in response to
8342 <xref linkend=
"libpq-PQfinish"/>. It is the event procedure's
8343 responsibility to properly clean up its event data as libpq has no
8344 ability to manage this memory. Failure to clean up will lead
8351 } PGEventConnDestroy;
8354 When a
<literal>PGEVT_CONNDESTROY
</literal> event is received, the
8355 <parameter>evtInfo
</parameter> pointer should be cast to a
8356 <structname>PGEventConnDestroy *
</structname>. This event is fired
8357 prior to
<xref linkend=
"libpq-PQfinish"/> performing any other cleanup.
8358 The return value of the event procedure is ignored since there is no
8359 way of indicating a failure from
<xref linkend=
"libpq-PQfinish"/>. Also,
8360 an event procedure failure should not abort the process of cleaning up
8366 <varlistentry id=
"libpq-pgevt-resultcreate">
8367 <term><literal>PGEVT_RESULTCREATE
</literal></term>
8370 The result creation event is fired in response to any query execution
8371 function that generates a result, including
8372 <xref linkend=
"libpq-PQgetResult"/>. This event will only be fired after
8373 the result has been created successfully.
8380 } PGEventResultCreate;
8383 When a
<literal>PGEVT_RESULTCREATE
</literal> event is received, the
8384 <parameter>evtInfo
</parameter> pointer should be cast to a
8385 <structname>PGEventResultCreate *
</structname>. The
8386 <parameter>conn
</parameter> is the connection used to generate the
8387 result. This is the ideal place to initialize any
8388 <literal>instanceData
</literal> that needs to be associated with the
8389 result. If an event procedure fails (returns zero), that event
8390 procedure will be ignored for the remaining lifetime of the result;
8391 that is, it will not receive
<literal>PGEVT_RESULTCOPY
</literal>
8392 or
<literal>PGEVT_RESULTDESTROY
</literal> events for this result or
8393 results copied from it.
8398 <varlistentry id=
"libpq-pgevt-resultcopy">
8399 <term><literal>PGEVT_RESULTCOPY
</literal></term>
8402 The result copy event is fired in response to
8403 <xref linkend=
"libpq-PQcopyResult"/>. This event will only be fired after
8404 the copy is complete. Only event procedures that have
8405 successfully handled the
<literal>PGEVT_RESULTCREATE
</literal>
8406 or
<literal>PGEVT_RESULTCOPY
</literal> event for the source result
8407 will receive
<literal>PGEVT_RESULTCOPY
</literal> events.
8412 const PGresult *src;
8414 } PGEventResultCopy;
8417 When a
<literal>PGEVT_RESULTCOPY
</literal> event is received, the
8418 <parameter>evtInfo
</parameter> pointer should be cast to a
8419 <structname>PGEventResultCopy *
</structname>. The
8420 <parameter>src
</parameter> result is what was copied while the
8421 <parameter>dest
</parameter> result is the copy destination. This event
8422 can be used to provide a deep copy of
<literal>instanceData
</literal>,
8423 since
<literal>PQcopyResult
</literal> cannot do that. If an event
8424 procedure fails (returns zero), that event procedure will be
8425 ignored for the remaining lifetime of the new result; that is, it
8426 will not receive
<literal>PGEVT_RESULTCOPY
</literal>
8427 or
<literal>PGEVT_RESULTDESTROY
</literal> events for that result or
8428 results copied from it.
8433 <varlistentry id=
"libpq-pgevt-resultdestroy">
8434 <term><literal>PGEVT_RESULTDESTROY
</literal></term>
8437 The result destroy event is fired in response to a
8438 <xref linkend=
"libpq-PQclear"/>. It is the event procedure's
8439 responsibility to properly clean up its event data as libpq has no
8440 ability to manage this memory. Failure to clean up will lead
8447 } PGEventResultDestroy;
8450 When a
<literal>PGEVT_RESULTDESTROY
</literal> event is received, the
8451 <parameter>evtInfo
</parameter> pointer should be cast to a
8452 <structname>PGEventResultDestroy *
</structname>. This event is fired
8453 prior to
<xref linkend=
"libpq-PQclear"/> performing any other cleanup.
8454 The return value of the event procedure is ignored since there is no
8455 way of indicating a failure from
<xref linkend=
"libpq-PQclear"/>. Also,
8456 an event procedure failure should not abort the process of cleaning up
8464 <sect2 id=
"libpq-events-proc">
8465 <title>Event Callback Procedure
</title>
8468 <varlistentry id=
"libpq-PGEventProc">
8469 <term><literal>PGEventProc
</literal><indexterm><primary>PGEventProc
</primary></indexterm></term>
8473 <literal>PGEventProc
</literal> is a typedef for a pointer to an
8474 event procedure, that is, the user callback function that receives
8475 events from libpq. The signature of an event procedure must be
8478 int eventproc(PGEventId evtId, void *evtInfo, void *passThrough)
8481 The
<parameter>evtId
</parameter> parameter indicates which
8482 <literal>PGEVT
</literal> event occurred. The
8483 <parameter>evtInfo
</parameter> pointer must be cast to the appropriate
8484 structure type to obtain further information about the event.
8485 The
<parameter>passThrough
</parameter> parameter is the pointer
8486 provided to
<xref linkend=
"libpq-PQregisterEventProc"/> when the event
8487 procedure was registered. The function should return a non-zero value
8488 if it succeeds and zero if it fails.
8492 A particular event procedure can be registered only once in any
8493 <structname>PGconn
</structname>. This is because the address of the procedure
8494 is used as a lookup key to identify the associated instance data.
8499 On Windows, functions can have two different addresses: one visible
8500 from outside a DLL and another visible from inside the DLL. One
8501 should be careful that only one of these addresses is used with
8502 <application>libpq
</application>'s event-procedure functions, else confusion will
8503 result. The simplest rule for writing code that will work is to
8504 ensure that event procedures are declared
<literal>static
</literal>. If the
8505 procedure's address must be available outside its own source file,
8506 expose a separate function to return the address.
8514 <sect2 id=
"libpq-events-funcs">
8515 <title>Event Support Functions
</title>
8518 <varlistentry id=
"libpq-PQregisterEventProc">
8519 <term><function>PQregisterEventProc
</function><indexterm><primary>PQregisterEventProc
</primary></indexterm></term>
8523 Registers an event callback procedure with libpq.
8526 int PQregisterEventProc(PGconn *conn, PGEventProc proc,
8527 const char *name, void *passThrough);
8532 An event procedure must be registered once on each
8533 <structname>PGconn
</structname> you want to receive events about. There is no
8534 limit, other than memory, on the number of event procedures that
8535 can be registered with a connection. The function returns a non-zero
8536 value if it succeeds and zero if it fails.
8540 The
<parameter>proc
</parameter> argument will be called when a libpq
8541 event is fired. Its memory address is also used to lookup
8542 <literal>instanceData
</literal>. The
<parameter>name
</parameter>
8543 argument is used to refer to the event procedure in error messages.
8544 This value cannot be
<symbol>NULL
</symbol> or a zero-length string. The name string is
8545 copied into the
<structname>PGconn
</structname>, so what is passed need not be
8546 long-lived. The
<parameter>passThrough
</parameter> pointer is passed
8547 to the
<parameter>proc
</parameter> whenever an event occurs. This
8548 argument can be
<symbol>NULL
</symbol>.
8553 <varlistentry id=
"libpq-PQsetInstanceData">
8554 <term><function>PQsetInstanceData
</function><indexterm><primary>PQsetInstanceData
</primary></indexterm></term>
8557 Sets the connection
<parameter>conn
</parameter>'s
<literal>instanceData
</literal>
8558 for procedure
<parameter>proc
</parameter> to
<parameter>data
</parameter>. This
8559 returns non-zero for success and zero for failure. (Failure is
8560 only possible if
<parameter>proc
</parameter> has not been properly
8561 registered in
<parameter>conn
</parameter>.)
8564 int PQsetInstanceData(PGconn *conn, PGEventProc proc, void *data);
8570 <varlistentry id=
"libpq-PQinstanceData">
8571 <term><function>PQinstanceData
</function><indexterm><primary>PQinstanceData
</primary></indexterm></term>
8575 connection
<parameter>conn
</parameter>'s
<literal>instanceData
</literal>
8576 associated with procedure
<parameter>proc
</parameter>,
8577 or
<symbol>NULL
</symbol> if there is none.
8580 void *PQinstanceData(const PGconn *conn, PGEventProc proc);
8586 <varlistentry id=
"libpq-PQresultSetInstanceData">
8587 <term><function>PQresultSetInstanceData
</function><indexterm><primary>PQresultSetInstanceData
</primary></indexterm></term>
8590 Sets the result's
<literal>instanceData
</literal>
8591 for
<parameter>proc
</parameter> to
<parameter>data
</parameter>. This returns
8592 non-zero for success and zero for failure. (Failure is only
8593 possible if
<parameter>proc
</parameter> has not been properly registered
8597 int PQresultSetInstanceData(PGresult *res, PGEventProc proc, void *data);
8602 Beware that any storage represented by
<parameter>data
</parameter>
8603 will not be accounted for by
<xref linkend=
"libpq-PQresultMemorySize"/>,
8604 unless it is allocated using
<xref linkend=
"libpq-PQresultAlloc"/>.
8605 (Doing so is recommendable because it eliminates the need to free
8606 such storage explicitly when the result is destroyed.)
8611 <varlistentry id=
"libpq-PQresultInstanceData">
8612 <term><function>PQresultInstanceData
</function><indexterm><primary>PQresultInstanceData
</primary></indexterm></term>
8615 Returns the result's
<literal>instanceData
</literal> associated with
<parameter>proc
</parameter>, or
<symbol>NULL
</symbol>
8619 void *PQresultInstanceData(const PGresult *res, PGEventProc proc);
8627 <sect2 id=
"libpq-events-example">
8628 <title>Event Example
</title>
8631 Here is a skeleton example of managing private data associated with
8632 libpq connections and results.
8637 /* required header for libpq events (note: includes libpq-fe.h) */
8638 #include
<libpq-events.h
>
8640 /* The instanceData */
8648 static int myEventProc(PGEventId evtId, void *evtInfo, void *passThrough);
8656 PQconnectdb(
"dbname=postgres options=-csearch_path=");
8658 if (PQstatus(conn) != CONNECTION_OK)
8660 /* PQerrorMessage's result includes a trailing newline */
8661 fprintf(stderr,
"%s", PQerrorMessage(conn));
8666 /* called once on any connection that should receive events.
8667 * Sends a PGEVT_REGISTER to myEventProc.
8669 if (!PQregisterEventProc(conn, myEventProc,
"mydata_proc", NULL))
8671 fprintf(stderr,
"Cannot register PGEventProc\n");
8676 /* conn instanceData is available */
8677 data = PQinstanceData(conn, myEventProc);
8679 /* Sends a PGEVT_RESULTCREATE to myEventProc */
8680 res = PQexec(conn,
"SELECT 1 + 1");
8682 /* result instanceData is available */
8683 data = PQresultInstanceData(res, myEventProc);
8685 /* If PG_COPYRES_EVENTS is used, sends a PGEVT_RESULTCOPY to myEventProc */
8686 res_copy = PQcopyResult(res, PG_COPYRES_TUPLES | PG_COPYRES_EVENTS);
8688 /* result instanceData is available if PG_COPYRES_EVENTS was
8689 * used during the PQcopyResult call.
8691 data = PQresultInstanceData(res_copy, myEventProc);
8693 /* Both clears send a PGEVT_RESULTDESTROY to myEventProc */
8697 /* Sends a PGEVT_CONNDESTROY to myEventProc */
8704 myEventProc(PGEventId evtId, void *evtInfo, void *passThrough)
8708 case PGEVT_REGISTER:
8710 PGEventRegister *e = (PGEventRegister *)evtInfo;
8711 mydata *data = get_mydata(e-
>conn);
8713 /* associate app specific data with connection */
8714 PQsetInstanceData(e-
>conn, myEventProc, data);
8718 case PGEVT_CONNRESET:
8720 PGEventConnReset *e = (PGEventConnReset *)evtInfo;
8721 mydata *data = PQinstanceData(e-
>conn, myEventProc);
8724 memset(data,
0, sizeof(mydata));
8728 case PGEVT_CONNDESTROY:
8730 PGEventConnDestroy *e = (PGEventConnDestroy *)evtInfo;
8731 mydata *data = PQinstanceData(e-
>conn, myEventProc);
8733 /* free instance data because the conn is being destroyed */
8739 case PGEVT_RESULTCREATE:
8741 PGEventResultCreate *e = (PGEventResultCreate *)evtInfo;
8742 mydata *conn_data = PQinstanceData(e-
>conn, myEventProc);
8743 mydata *res_data = dup_mydata(conn_data);
8745 /* associate app specific data with result (copy it from conn) */
8746 PQresultSetInstanceData(e-
>result, myEventProc, res_data);
8750 case PGEVT_RESULTCOPY:
8752 PGEventResultCopy *e = (PGEventResultCopy *)evtInfo;
8753 mydata *src_data = PQresultInstanceData(e-
>src, myEventProc);
8754 mydata *dest_data = dup_mydata(src_data);
8756 /* associate app specific data with result (copy it from a result) */
8757 PQresultSetInstanceData(e-
>dest, myEventProc, dest_data);
8761 case PGEVT_RESULTDESTROY:
8763 PGEventResultDestroy *e = (PGEventResultDestroy *)evtInfo;
8764 mydata *data = PQresultInstanceData(e-
>result, myEventProc);
8766 /* free instance data because the result is being destroyed */
8772 /* unknown event ID, just return true. */
8777 return true; /* event processing succeeded */
8784 <sect1 id=
"libpq-envars">
8785 <title>Environment Variables
</title>
8787 <indexterm zone=
"libpq-envars">
8788 <primary>environment variable
</primary>
8792 The following environment variables can be used to select default
8793 connection parameter values, which will be used by
8794 <xref linkend=
"libpq-PQconnectdb"/>,
<xref linkend=
"libpq-PQsetdbLogin"/> and
8795 <xref linkend=
"libpq-PQsetdb"/> if no value is directly specified by the calling
8796 code. These are useful to avoid hard-coding database connection
8797 information into simple client applications, for example.
8803 <primary><envar>PGHOST
</envar></primary>
8805 <envar>PGHOST
</envar> behaves the same as the
<xref
8806 linkend=
"libpq-connect-host"/> connection parameter.
8813 <primary><envar>PGSSLNEGOTIATION
</envar></primary>
8815 <envar>PGSSLNEGOTIATION
</envar> behaves the same as the
<xref
8816 linkend=
"libpq-connect-sslnegotiation"/> connection parameter.
8823 <primary><envar>PGHOSTADDR
</envar></primary>
8825 <envar>PGHOSTADDR
</envar> behaves the same as the
<xref
8826 linkend=
"libpq-connect-hostaddr"/> connection parameter.
8827 This can be set instead of or in addition to
<envar>PGHOST
</envar>
8828 to avoid DNS lookup overhead.
8835 <primary><envar>PGPORT
</envar></primary>
8837 <envar>PGPORT
</envar> behaves the same as the
<xref
8838 linkend=
"libpq-connect-port"/> connection parameter.
8845 <primary><envar>PGDATABASE
</envar></primary>
8847 <envar>PGDATABASE
</envar> behaves the same as the
<xref
8848 linkend=
"libpq-connect-dbname"/> connection parameter.
8855 <primary><envar>PGUSER
</envar></primary>
8857 <envar>PGUSER
</envar> behaves the same as the
<xref
8858 linkend=
"libpq-connect-user"/> connection parameter.
8865 <primary><envar>PGPASSWORD
</envar></primary>
8867 <envar>PGPASSWORD
</envar> behaves the same as the
<xref
8868 linkend=
"libpq-connect-password"/> connection parameter.
8869 Use of this environment variable
8870 is not recommended for security reasons, as some operating systems
8871 allow non-root users to see process environment variables via
8872 <application>ps
</application>; instead consider using a password file
8873 (see
<xref linkend=
"libpq-pgpass"/>).
8880 <primary><envar>PGPASSFILE
</envar></primary>
8882 <envar>PGPASSFILE
</envar> behaves the same as the
<xref
8883 linkend=
"libpq-connect-passfile"/> connection parameter.
8890 <primary><envar>PGREQUIREAUTH
</envar></primary>
8892 <envar>PGREQUIREAUTH
</envar> behaves the same as the
<xref
8893 linkend=
"libpq-connect-require-auth"/> connection parameter.
8900 <primary><envar>PGCHANNELBINDING
</envar></primary>
8902 <envar>PGCHANNELBINDING
</envar> behaves the same as the
<xref
8903 linkend=
"libpq-connect-channel-binding"/> connection parameter.
8910 <primary><envar>PGSERVICE
</envar></primary>
8912 <envar>PGSERVICE
</envar> behaves the same as the
<xref
8913 linkend=
"libpq-connect-service"/> connection parameter.
8920 <primary><envar>PGSERVICEFILE
</envar></primary>
8922 <envar>PGSERVICEFILE
</envar> specifies the name of the per-user
8923 connection service file
8924 (see
<xref linkend=
"libpq-pgservice"/>).
8925 Defaults to
<filename>~/.pg_service.conf
</filename>, or
8926 <filename>%APPDATA%\postgresql\.pg_service.conf
</filename> on
8934 <primary><envar>PGOPTIONS
</envar></primary>
8936 <envar>PGOPTIONS
</envar> behaves the same as the
<xref
8937 linkend=
"libpq-connect-options"/> connection parameter.
8944 <primary><envar>PGAPPNAME
</envar></primary>
8946 <envar>PGAPPNAME
</envar> behaves the same as the
<xref
8947 linkend=
"libpq-connect-application-name"/> connection parameter.
8954 <primary><envar>PGSSLMODE
</envar></primary>
8956 <envar>PGSSLMODE
</envar> behaves the same as the
<xref
8957 linkend=
"libpq-connect-sslmode"/> connection parameter.
8964 <primary><envar>PGREQUIRESSL
</envar></primary>
8966 <envar>PGREQUIRESSL
</envar> behaves the same as the
<xref
8967 linkend=
"libpq-connect-requiressl"/> connection parameter.
8968 This environment variable is deprecated in favor of the
8969 <envar>PGSSLMODE
</envar> variable; setting both variables suppresses the
8977 <primary><envar>PGSSLCOMPRESSION
</envar></primary>
8979 <envar>PGSSLCOMPRESSION
</envar> behaves the same as the
<xref
8980 linkend=
"libpq-connect-sslcompression"/> connection parameter.
8987 <primary><envar>PGSSLCERT
</envar></primary>
8989 <envar>PGSSLCERT
</envar> behaves the same as the
<xref
8990 linkend=
"libpq-connect-sslcert"/> connection parameter.
8997 <primary><envar>PGSSLKEY
</envar></primary>
8999 <envar>PGSSLKEY
</envar> behaves the same as the
<xref
9000 linkend=
"libpq-connect-sslkey"/> connection parameter.
9007 <primary><envar>PGSSLCERTMODE
</envar></primary>
9009 <envar>PGSSLCERTMODE
</envar> behaves the same as the
<xref
9010 linkend=
"libpq-connect-sslcertmode"/> connection parameter.
9017 <primary><envar>PGSSLROOTCERT
</envar></primary>
9019 <envar>PGSSLROOTCERT
</envar> behaves the same as the
<xref
9020 linkend=
"libpq-connect-sslrootcert"/> connection parameter.
9027 <primary><envar>PGSSLCRL
</envar></primary>
9029 <envar>PGSSLCRL
</envar> behaves the same as the
<xref
9030 linkend=
"libpq-connect-sslcrl"/> connection parameter.
9037 <primary><envar>PGSSLCRLDIR
</envar></primary>
9039 <envar>PGSSLCRLDIR
</envar> behaves the same as the
<xref
9040 linkend=
"libpq-connect-sslcrldir"/> connection parameter.
9047 <primary><envar>PGSSLSNI
</envar></primary>
9049 <envar>PGSSLSNI
</envar> behaves the same as the
<xref
9050 linkend=
"libpq-connect-sslsni"/> connection parameter.
9057 <primary><envar>PGREQUIREPEER
</envar></primary>
9059 <envar>PGREQUIREPEER
</envar> behaves the same as the
<xref
9060 linkend=
"libpq-connect-requirepeer"/> connection parameter.
9067 <primary><envar>PGSSLMINPROTOCOLVERSION
</envar></primary>
9069 <envar>PGSSLMINPROTOCOLVERSION
</envar> behaves the same as the
<xref
9070 linkend=
"libpq-connect-ssl-min-protocol-version"/> connection parameter.
9077 <primary><envar>PGSSLMAXPROTOCOLVERSION
</envar></primary>
9079 <envar>PGSSLMAXPROTOCOLVERSION
</envar> behaves the same as the
<xref
9080 linkend=
"libpq-connect-ssl-max-protocol-version"/> connection parameter.
9087 <primary><envar>PGGSSENCMODE
</envar></primary>
9089 <envar>PGGSSENCMODE
</envar> behaves the same as the
<xref
9090 linkend=
"libpq-connect-gssencmode"/> connection parameter.
9097 <primary><envar>PGKRBSRVNAME
</envar></primary>
9099 <envar>PGKRBSRVNAME
</envar> behaves the same as the
<xref
9100 linkend=
"libpq-connect-krbsrvname"/> connection parameter.
9107 <primary><envar>PGGSSLIB
</envar></primary>
9109 <envar>PGGSSLIB
</envar> behaves the same as the
<xref
9110 linkend=
"libpq-connect-gsslib"/> connection parameter.
9117 <primary><envar>PGGSSDELEGATION
</envar></primary>
9119 <envar>PGGSSDELEGATION
</envar> behaves the same as the
<xref
9120 linkend=
"libpq-connect-gssdelegation"/> connection parameter.
9127 <primary><envar>PGCONNECT_TIMEOUT
</envar></primary>
9129 <envar>PGCONNECT_TIMEOUT
</envar> behaves the same as the
<xref
9130 linkend=
"libpq-connect-connect-timeout"/> connection parameter.
9137 <primary><envar>PGCLIENTENCODING
</envar></primary>
9139 <envar>PGCLIENTENCODING
</envar> behaves the same as the
<xref
9140 linkend=
"libpq-connect-client-encoding"/> connection parameter.
9147 <primary><envar>PGTARGETSESSIONATTRS
</envar></primary>
9149 <envar>PGTARGETSESSIONATTRS
</envar> behaves the same as the
<xref
9150 linkend=
"libpq-connect-target-session-attrs"/> connection parameter.
9157 <primary><envar>PGLOADBALANCEHOSTS
</envar></primary>
9159 <envar>PGLOADBALANCEHOSTS
</envar> behaves the same as the
<xref
9160 linkend=
"libpq-connect-load-balance-hosts"/> connection parameter.
9167 The following environment variables can be used to specify default
9168 behavior for each
<productname>PostgreSQL
</productname> session. (See
9169 also the
<xref linkend=
"sql-alterrole"/>
9170 and
<xref linkend=
"sql-alterdatabase"/>
9171 commands for ways to set default behavior on a per-user or per-database
9178 <primary><envar>PGDATESTYLE
</envar></primary>
9180 <envar>PGDATESTYLE
</envar> sets the default style of date/time
9181 representation. (Equivalent to
<literal>SET datestyle TO
9189 <primary><envar>PGTZ
</envar></primary>
9191 <envar>PGTZ
</envar> sets the default time zone. (Equivalent to
9192 <literal>SET timezone TO ...
</literal>.)
9199 <primary><envar>PGGEQO
</envar></primary>
9201 <envar>PGGEQO
</envar> sets the default mode for the genetic query
9202 optimizer. (Equivalent to
<literal>SET geqo TO ...
</literal>.)
9207 Refer to the
<acronym>SQL
</acronym> command
<xref linkend=
"sql-set"/>
9208 for information on correct values for these
9209 environment variables.
9213 The following environment variables determine internal behavior of
9214 <application>libpq
</application>; they override compiled-in defaults.
9220 <primary><envar>PGSYSCONFDIR
</envar></primary>
9222 <envar>PGSYSCONFDIR
</envar> sets the directory containing the
9223 <filename>pg_service.conf
</filename> file and in a future version
9224 possibly other system-wide configuration files.
9231 <primary><envar>PGLOCALEDIR
</envar></primary>
9233 <envar>PGLOCALEDIR
</envar> sets the directory containing the
9234 <literal>locale
</literal> files for message localization.
9243 <sect1 id=
"libpq-pgpass">
9244 <title>The Password File
</title>
9246 <indexterm zone=
"libpq-pgpass">
9247 <primary>password file
</primary>
9249 <indexterm zone=
"libpq-pgpass">
9250 <primary>.pgpass
</primary>
9254 The file
<filename>.pgpass
</filename> in a user's home directory can
9255 contain passwords to
9256 be used if the connection requires a password (and no password has been
9257 specified otherwise). On Microsoft Windows the file is named
9258 <filename>%APPDATA%\postgresql\pgpass.conf
</filename> (where
9259 <filename>%APPDATA%
</filename> refers to the Application Data subdirectory in
9260 the user's profile).
9261 Alternatively, the password file to use can be specified
9262 using the connection parameter
<xref linkend=
"libpq-connect-passfile"/>
9263 or the environment variable
<envar>PGPASSFILE
</envar>.
9267 This file should contain lines of the following format:
9269 <replaceable>hostname
</replaceable>:
<replaceable>port
</replaceable>:
<replaceable>database
</replaceable>:
<replaceable>username
</replaceable>:
<replaceable>password
</replaceable>
9271 (You can add a reminder comment to the file by copying the line above and
9272 preceding it with
<literal>#
</literal>.)
9273 Each of the first four fields can be a literal value, or
9274 <literal>*
</literal>, which matches anything. The password field from
9275 the first line that matches the current connection parameters will be
9276 used. (Therefore, put more-specific entries first when you are using
9277 wildcards.) If an entry needs to contain
<literal>:
</literal> or
9278 <literal>\
</literal>, escape this character with
<literal>\
</literal>.
9279 The host name field is matched to the
<literal>host
</literal> connection
9280 parameter if that is specified, otherwise to
9281 the
<literal>hostaddr
</literal> parameter if that is specified; if neither
9282 are given then the host name
<literal>localhost
</literal> is searched for.
9283 The host name
<literal>localhost
</literal> is also searched for when
9284 the connection is a Unix-domain socket connection and
9285 the
<literal>host
</literal> parameter
9286 matches
<application>libpq
</application>'s default socket directory path.
9287 In a standby server, a database field of
<literal>replication
</literal>
9288 matches streaming replication connections made to the primary server.
9289 The database field is of limited usefulness otherwise, because users have
9290 the same password for all databases in the same cluster.
9294 On Unix systems, the permissions on a password file must
9295 disallow any access to world or group; achieve this by a command such as
9296 <command>chmod
0600 ~/.pgpass
</command>. If the permissions are less
9297 strict than this, the file will be ignored. On Microsoft Windows, it
9298 is assumed that the file is stored in a directory that is secure, so
9299 no special permissions check is made.
9304 <sect1 id=
"libpq-pgservice">
9305 <title>The Connection Service File
</title>
9307 <indexterm zone=
"libpq-pgservice">
9308 <primary>connection service file
</primary>
9310 <indexterm zone=
"libpq-pgservice">
9311 <primary>pg_service.conf
</primary>
9313 <indexterm zone=
"libpq-pgservice">
9314 <primary>.pg_service.conf
</primary>
9318 The connection service file allows libpq connection parameters to be
9319 associated with a single service name. That service name can then be
9320 specified in a libpq connection string, and the associated settings will be
9321 used. This allows connection parameters to be modified without requiring
9322 a recompile of the libpq-using application. The service name can also be
9323 specified using the
<envar>PGSERVICE
</envar> environment variable.
9327 Service names can be defined in either a per-user service file or a
9328 system-wide file. If the same service name exists in both the user
9329 and the system file, the user file takes precedence.
9330 By default, the per-user service file is named
9331 <filename>~/.pg_service.conf
</filename>.
9332 On Microsoft Windows, it is named
9333 <filename>%APPDATA%\postgresql\.pg_service.conf
</filename> (where
9334 <filename>%APPDATA%
</filename> refers to the Application Data subdirectory
9335 in the user's profile). A different file name can be specified by
9336 setting the environment variable
<envar>PGSERVICEFILE
</envar>.
9337 The system-wide file is named
<filename>pg_service.conf
</filename>.
9338 By default it is sought in the
<filename>etc
</filename> directory
9339 of the
<productname>PostgreSQL
</productname> installation
9340 (use
<literal>pg_config --sysconfdir
</literal> to identify this
9341 directory precisely). Another directory, but not a different file
9342 name, can be specified by setting the environment variable
9343 <envar>PGSYSCONFDIR
</envar>.
9347 Either service file uses an
<quote>INI file
</quote> format where the section
9348 name is the service name and the parameters are connection
9349 parameters; see
<xref linkend=
"libpq-paramkeywords"/> for a list. For
9358 An example file is provided in
9359 the
<productname>PostgreSQL
</productname> installation at
9360 <filename>share/pg_service.conf.sample
</filename>.
9364 Connection parameters obtained from a service file are combined with
9365 parameters obtained from other sources. A service file setting
9366 overrides the corresponding environment variable, and in turn can be
9367 overridden by a value given directly in the connection string.
9368 For example, using the above service file, a connection string
9369 <literal>service=mydb port=
5434</literal> will use
9370 host
<literal>somehost
</literal>, port
<literal>5434</literal>,
9371 user
<literal>admin
</literal>, and other parameters as set by
9372 environment variables or built-in defaults.
9377 <sect1 id=
"libpq-ldap">
9378 <title>LDAP Lookup of Connection Parameters
</title>
9380 <indexterm zone=
"libpq-ldap">
9381 <primary>LDAP connection parameter lookup
</primary>
9385 If
<application>libpq
</application> has been compiled with LDAP support (option
9386 <literal><option>--with-ldap
</option></literal> for
<command>configure
</command>)
9387 it is possible to retrieve connection options like
<literal>host
</literal>
9388 or
<literal>dbname
</literal> via LDAP from a central server.
9389 The advantage is that if the connection parameters for a database change,
9390 the connection information doesn't have to be updated on all client machines.
9394 LDAP connection parameter lookup uses the connection service file
9395 <filename>pg_service.conf
</filename> (see
<xref
9396 linkend=
"libpq-pgservice"/>). A line in a
9397 <filename>pg_service.conf
</filename> stanza that starts with
9398 <literal>ldap://
</literal> will be recognized as an LDAP URL and an
9399 LDAP query will be performed. The result must be a list of
9400 <literal>keyword = value
</literal> pairs which will be used to set
9401 connection options. The URL must conform to
9402 <ulink url=
"https://datatracker.ietf.org/doc/html/rfc1959">RFC
1959</ulink>
9405 ldap://[
<replaceable>hostname
</replaceable>[:
<replaceable>port
</replaceable>]]/
<replaceable>search_base
</replaceable>?
<replaceable>attribute
</replaceable>?
<replaceable>search_scope
</replaceable>?
<replaceable>filter
</replaceable>
9407 where
<replaceable>hostname
</replaceable> defaults to
9408 <literal>localhost
</literal> and
<replaceable>port
</replaceable>
9413 Processing of
<filename>pg_service.conf
</filename> is terminated after
9414 a successful LDAP lookup, but is continued if the LDAP server cannot
9415 be contacted. This is to provide a fallback with further LDAP URL
9416 lines that point to different LDAP servers, classical
<literal>keyword
9417 = value
</literal> pairs, or default connection options. If you would
9418 rather get an error message in this case, add a syntactically incorrect
9419 line after the LDAP URL.
9423 A sample LDAP entry that has been created with the LDIF file
9426 dn:cn=mydatabase,dc=mycompany,dc=com
9431 description:host=dbserver.mycompany.com
9432 description:port=
5439
9433 description:dbname=mydb
9434 description:user=mydb_user
9435 description:sslmode=require
9437 might be queried with the following LDAP URL:
9439 ldap://ldap.mycompany.com/dc=mycompany,dc=com?description?one?(cn=mydatabase)
9444 You can also mix regular service file entries with LDAP lookups.
9445 A complete example for a stanza in
<filename>pg_service.conf
</filename>
9448 # only host and port are stored in LDAP, specify dbname and user explicitly
9452 ldap://ldap.acme.com/cn=dbserver,cn=hosts?pgconnectinfo?base?(objectclass=*)
9459 <sect1 id=
"libpq-ssl">
9460 <title>SSL Support
</title>
9462 <indexterm zone=
"libpq-ssl">
9463 <primary>SSL
</primary>
9464 <secondary>TLS
</secondary>
9468 <productname>PostgreSQL
</productname> has native support for using
<acronym>SSL
</acronym>
9469 connections to encrypt client/server communications using
9470 <acronym>TLS
</acronym> protocols for increased security.
9471 See
<xref linkend=
"ssl-tcp"/> for details about the server-side
9472 <acronym>SSL
</acronym> functionality.
9476 <application>libpq
</application> reads the system-wide
9477 <productname>OpenSSL
</productname> configuration file. By default, this
9478 file is named
<filename>openssl.cnf
</filename> and is located in the
9479 directory reported by
<literal>openssl version -d
</literal>. This default
9480 can be overridden by setting environment variable
9481 <envar>OPENSSL_CONF
</envar> to the name of the desired configuration
9485 <sect2 id=
"libq-ssl-certificates">
9486 <title>Client Verification of Server Certificates
</title>
9489 By default,
<productname>PostgreSQL
</productname> will not perform any verification of
9490 the server certificate. This means that it is possible to spoof the server
9491 identity (for example by modifying a DNS record or by taking over the server
9492 IP address) without the client knowing. In order to prevent spoofing,
9493 the client must be able to verify the server's identity via a chain of
9494 trust. A chain of trust is established by placing a root (self-signed)
9495 certificate authority (
<acronym>CA
</acronym>) certificate on one
9496 computer and a leaf certificate
<emphasis>signed
</emphasis> by the
9497 root certificate on another computer. It is also possible to use an
9498 <quote>intermediate
</quote> certificate which is signed by the root
9499 certificate and signs leaf certificates.
9503 To allow the client to verify the identity of the server, place a root
9504 certificate on the client and a leaf certificate signed by the root
9505 certificate on the server. To allow the server to verify the identity
9506 of the client, place a root certificate on the server and a leaf
9507 certificate signed by the root certificate on the client. One or more
9508 intermediate certificates (usually stored with the leaf certificate)
9509 can also be used to link the leaf certificate to the root certificate.
9513 Once a chain of trust has been established, there are two ways for
9514 the client to validate the leaf certificate sent by the server.
9515 If the parameter
<literal>sslmode
</literal> is set to
<literal>verify-ca
</literal>,
9516 libpq will verify that the server is trustworthy by checking the
9517 certificate chain up to the root certificate stored on the client.
9518 If
<literal>sslmode
</literal> is set to
<literal>verify-full
</literal>,
9519 libpq will
<emphasis>also
</emphasis> verify that the server host
9520 name matches the name stored in the server certificate. The
9521 SSL connection will fail if the server certificate cannot be
9522 verified.
<literal>verify-full
</literal> is recommended in most
9523 security-sensitive environments.
9527 In
<literal>verify-full
</literal> mode, the host name is matched against the
9528 certificate's Subject Alternative Name attribute(s) (SAN), or against the
9529 Common Name attribute if no SAN of type
<literal>dNSName
</literal> is
9530 present. If the certificate's name attribute starts with an asterisk
9531 (
<literal>*
</literal>), the asterisk will be treated as
9532 a wildcard, which will match all characters
<emphasis>except
</emphasis> a dot
9533 (
<literal>.
</literal>). This means the certificate will not match subdomains.
9534 If the connection is made using an IP address instead of a host name, the
9535 IP address will be matched (without doing any DNS lookups) against SANs of
9536 type
<literal>iPAddress
</literal> or
<literal>dNSName
</literal>. If no
9537 <literal>iPAddress
</literal> SAN is present and no
9538 matching
<literal>dNSName
</literal> SAN is present, the host IP address is
9539 matched against the Common Name attribute.
9544 For backward compatibility with earlier versions of PostgreSQL, the host
9545 IP address is verified in a manner different
9546 from
<ulink url=
"https://datatracker.ietf.org/doc/html/rfc6125">RFC
6125</ulink>.
9547 The host IP address is always matched against
<literal>dNSName
</literal>
9548 SANs as well as
<literal>iPAddress
</literal> SANs, and can be matched
9549 against the Common Name attribute if no relevant SANs exist.
9554 To allow server certificate verification, one or more root certificates
9555 must be placed in the file
<filename>~/.postgresql/root.crt
</filename>
9556 in the user's home directory. (On Microsoft Windows the file is named
9557 <filename>%APPDATA%\postgresql\root.crt
</filename>.) Intermediate
9558 certificates should also be added to the file if they are needed to link
9559 the certificate chain sent by the server to the root certificates
9560 stored on the client.
9564 Certificate Revocation List (CRL) entries are also checked
9565 if the file
<filename>~/.postgresql/root.crl
</filename> exists
9566 (
<filename>%APPDATA%\postgresql\root.crl
</filename> on Microsoft
9571 The location of the root certificate file and the CRL can be changed by
9573 the connection parameters
<literal>sslrootcert
</literal> and
<literal>sslcrl
</literal>
9574 or the environment variables
<envar>PGSSLROOTCERT
</envar> and
<envar>PGSSLCRL
</envar>.
9575 <literal>sslcrldir
</literal> or the environment variable
<envar>PGSSLCRLDIR
</envar>
9576 can also be used to specify a directory containing CRL files.
9581 For backwards compatibility with earlier versions of PostgreSQL, if a
9582 root CA file exists, the behavior of
9583 <literal>sslmode
</literal>=
<literal>require
</literal> will be the same
9584 as that of
<literal>verify-ca
</literal>, meaning the server certificate
9585 is validated against the CA. Relying on this behavior is discouraged,
9586 and applications that need certificate validation should always use
9587 <literal>verify-ca
</literal> or
<literal>verify-full
</literal>.
9592 <sect2 id=
"libpq-ssl-clientcert">
9593 <title>Client Certificates
</title>
9596 If the server attempts to verify the identity of the
9597 client by requesting the client's leaf certificate,
9598 <application>libpq
</application> will send the certificate(s) stored in
9599 file
<filename>~/.postgresql/postgresql.crt
</filename> in the user's home
9600 directory. The certificates must chain to the root certificate trusted
9601 by the server. A matching
9602 private key file
<filename>~/.postgresql/postgresql.key
</filename> must also
9604 On Microsoft Windows these files are named
9605 <filename>%APPDATA%\postgresql\postgresql.crt
</filename> and
9606 <filename>%APPDATA%\postgresql\postgresql.key
</filename>.
9607 The location of the certificate and key files can be overridden by the
9608 connection parameters
<literal>sslcert
</literal>
9609 and
<literal>sslkey
</literal>, or by the
9610 environment variables
<envar>PGSSLCERT
</envar> and
<envar>PGSSLKEY
</envar>.
9614 On Unix systems, the permissions on the private key file must disallow
9615 any access to world or group; achieve this by a command such as
9616 <command>chmod
0600 ~/.postgresql/postgresql.key
</command>.
9617 Alternatively, the file can be owned by root and have group read access
9618 (that is,
<literal>0640</literal> permissions). That setup is intended
9619 for installations where certificate and key files are managed by the
9620 operating system. The user of
<application>libpq
</application> should
9621 then be made a member of the group that has access to those certificate
9622 and key files. (On Microsoft Windows, there is no file permissions
9623 check, since the
<filename>%APPDATA%\postgresql
</filename> directory is
9628 The first certificate in
<filename>postgresql.crt
</filename> must be the
9629 client's certificate because it must match the client's private key.
9630 <quote>Intermediate
</quote> certificates can be optionally appended
9631 to the file
— doing so avoids requiring storage of intermediate
9632 certificates on the server (
<xref linkend=
"guc-ssl-ca-file"/>).
9636 The certificate and key may be in PEM or ASN
.1 DER format.
9641 stored in cleartext or encrypted with a passphrase using any algorithm
9642 supported by
<productname>OpenSSL
</productname>, like AES-
128. If the key
9643 is stored encrypted, then the passphrase may be provided in the
9644 <xref linkend=
"libpq-connect-sslpassword"/> connection option. If an
9645 encrypted key is supplied and the
<literal>sslpassword
</literal> option
9646 is absent or blank, a password will be prompted for interactively by
9647 <productname>OpenSSL
</productname> with a
9648 <literal>Enter PEM pass phrase:
</literal> prompt if a TTY is available.
9649 Applications can override the client certificate prompt and the handling
9650 of the
<literal>sslpassword
</literal> parameter by supplying their own
9651 key password callback; see
9652 <xref linkend=
"libpq-pqsetsslkeypasshook-openssl"/>.
9656 For instructions on creating certificates, see
<xref
9657 linkend=
"ssl-certificate-creation"/>.
9661 <sect2 id=
"libpq-ssl-protection">
9662 <title>Protection Provided in Different Modes
</title>
9665 The different values for the
<literal>sslmode
</literal> parameter provide different
9666 levels of protection. SSL can provide
9667 protection against three types of attacks:
9671 <term>Eavesdropping
</term>
9673 <para>If a third party can examine the network traffic between the
9674 client and the server, it can read both connection information (including
9675 the user name and password) and the data that is passed.
<acronym>SSL
</acronym>
9676 uses encryption to prevent this.
9682 <term>Man-in-the-middle (
<acronym>MITM
</acronym>)
</term>
9684 <para>If a third party can modify the data while passing between the
9685 client and server, it can pretend to be the server and therefore see and
9686 modify data
<emphasis>even if it is encrypted
</emphasis>. The third party can then
9687 forward the connection information and data to the original server,
9688 making it impossible to detect this attack. Common vectors to do this
9689 include DNS poisoning and address hijacking, whereby the client is directed
9690 to a different server than intended. There are also several other
9691 attack methods that can accomplish this.
<acronym>SSL
</acronym> uses certificate
9692 verification to prevent this, by authenticating the server to the client.
9698 <term>Impersonation
</term>
9700 <para>If a third party can pretend to be an authorized client, it can
9701 simply access data it should not have access to. Typically this can
9702 happen through insecure password management.
<acronym>SSL
</acronym> uses
9703 client certificates to prevent this, by making sure that only holders
9704 of valid certificates can access the server.
9712 For a connection to be known SSL-secured, SSL usage must be configured
9713 on
<emphasis>both the client and the server
</emphasis> before the connection
9714 is made. If it is only configured on the server, the client may end up
9715 sending sensitive information (e.g., passwords) before
9716 it knows that the server requires high security. In libpq, secure
9717 connections can be ensured
9718 by setting the
<literal>sslmode
</literal> parameter to
<literal>verify-full
</literal> or
9719 <literal>verify-ca
</literal>, and providing the system with a root certificate to
9720 verify against. This is analogous to using an
<literal>https
</literal>
9721 <acronym>URL
</acronym> for encrypted web browsing.
9725 Once the server has been authenticated, the client can pass sensitive data.
9726 This means that up until this point, the client does not need to know if
9727 certificates will be used for authentication, making it safe to specify that
9728 only in the server configuration.
9732 All
<acronym>SSL
</acronym> options carry overhead in the form of encryption and
9733 key-exchange, so there is a trade-off that has to be made between performance
9734 and security.
<xref linkend=
"libpq-ssl-sslmode-statements"/>
9735 illustrates the risks the different
<literal>sslmode
</literal> values
9736 protect against, and what statement they make about security and overhead.
9739 <table id=
"libpq-ssl-sslmode-statements">
9740 <title>SSL Mode Descriptions
</title>
9742 <colspec colname=
"col1" colwidth=
"1*"/>
9743 <colspec colname=
"col2" colwidth=
"1*"/>
9744 <colspec colname=
"col3" colwidth=
"1*"/>
9745 <colspec colname=
"col4" colwidth=
"2*"/>
9748 <entry><literal>sslmode
</literal></entry>
9749 <entry>Eavesdropping protection
</entry>
9750 <entry><acronym>MITM
</acronym> protection
</entry>
9751 <entry>Statement
</entry>
9757 <entry><literal>disable
</literal></entry>
9760 <entry>I don't care about security, and I don't want to pay the overhead
9766 <entry><literal>allow
</literal></entry>
9767 <entry>Maybe
</entry>
9769 <entry>I don't care about security, but I will pay the overhead of
9770 encryption if the server insists on it.
9775 <entry><literal>prefer
</literal></entry>
9776 <entry>Maybe
</entry>
9778 <entry>I don't care about encryption, but I wish to pay the overhead of
9779 encryption if the server supports it.
9784 <entry><literal>require
</literal></entry>
9787 <entry>I want my data to be encrypted, and I accept the overhead. I trust
9788 that the network will make sure I always connect to the server I want.
9793 <entry><literal>verify-ca
</literal></entry>
9795 <entry>Depends on CA policy
</entry>
9796 <entry>I want my data encrypted, and I accept the overhead. I want to be
9797 sure that I connect to a server that I trust.
9802 <entry><literal>verify-full
</literal></entry>
9805 <entry>I want my data encrypted, and I accept the overhead. I want to be
9806 sure that I connect to a server I trust, and that it's the one I
9816 The difference between
<literal>verify-ca
</literal> and
<literal>verify-full
</literal>
9817 depends on the policy of the root
<acronym>CA
</acronym>. If a public
9818 <acronym>CA
</acronym> is used,
<literal>verify-ca
</literal> allows connections to a server
9819 that
<emphasis>somebody else
</emphasis> may have registered with the
<acronym>CA
</acronym>.
9820 In this case,
<literal>verify-full
</literal> should always be used. If
9821 a local
<acronym>CA
</acronym> is used, or even a self-signed certificate, using
9822 <literal>verify-ca
</literal> often provides enough protection.
9826 The default value for
<literal>sslmode
</literal> is
<literal>prefer
</literal>. As is shown
9827 in the table, this makes no sense from a security point of view, and it only
9828 promises performance overhead if possible. It is only provided as the default
9829 for backward compatibility, and is not recommended in secure deployments.
9834 <sect2 id=
"libpq-ssl-fileusage">
9835 <title>SSL Client File Usage
</title>
9838 <xref linkend=
"libpq-ssl-file-usage"/> summarizes the files that are
9839 relevant to the SSL setup on the client.
9842 <table id=
"libpq-ssl-file-usage">
9843 <title>Libpq/Client SSL File Usage
</title>
9848 <entry>Contents
</entry>
9849 <entry>Effect
</entry>
9856 <entry><filename>~/.postgresql/postgresql.crt
</filename></entry>
9857 <entry>client certificate
</entry>
9858 <entry>sent to server
</entry>
9862 <entry><filename>~/.postgresql/postgresql.key
</filename></entry>
9863 <entry>client private key
</entry>
9864 <entry>proves client certificate sent by owner; does not indicate
9865 certificate owner is trustworthy
</entry>
9869 <entry><filename>~/.postgresql/root.crt
</filename></entry>
9870 <entry>trusted certificate authorities
</entry>
9871 <entry>checks that server certificate is signed by a trusted certificate
9876 <entry><filename>~/.postgresql/root.crl
</filename></entry>
9877 <entry>certificates revoked by certificate authorities
</entry>
9878 <entry>server certificate must not be on this list
</entry>
9886 <sect2 id=
"libpq-ssl-initialize">
9887 <title>SSL Library Initialization
</title>
9890 Applications which need to be compatible with older versions of
9891 <productname>PostgreSQL
</productname>, using
<productname>OpenSSL
</productname>
9892 version
1.0.2 or older, need to initialize the SSL library before using it.
9893 Applications which initialize
<literal>libssl
</literal> and/or
9894 <literal>libcrypto
</literal> libraries should call
9895 <xref linkend=
"libpq-PQinitOpenSSL"/> to tell
<application>libpq
</application>
9896 that the
<literal>libssl
</literal> and/or
<literal>libcrypto
</literal> libraries
9897 have been initialized by your application, so that
9898 <application>libpq
</application> will not also initialize those libraries.
9899 However, this is unnecessary when using
<productname>OpenSSL
</productname>
9900 version
1.1.0 or later, as duplicate initializations are no longer problematic.
9903 Refer to the documentation for the version of
<productname>PostgreSQL
</productname>
9904 that you are targeting for details on their use.
9909 <varlistentry id=
"libpq-PQinitOpenSSL">
9910 <term><function>PQinitOpenSSL
</function><indexterm><primary>PQinitOpenSSL
</primary></indexterm></term>
9914 Allows applications to select which security libraries to initialize.
9916 void PQinitOpenSSL(int do_ssl, int do_crypto);
9921 This function is deprecated and only present for backwards compatibility,
9927 <varlistentry id=
"libpq-PQinitSSL">
9928 <term><function>PQinitSSL
</function><indexterm><primary>PQinitSSL
</primary></indexterm></term><listitem>
9930 Allows applications to select which security libraries to initialize.
9932 void PQinitSSL(int do_ssl);
9937 This function is equivalent to
9938 <literal>PQinitOpenSSL(do_ssl, do_ssl)
</literal>.
9939 This function is deprecated and only present for backwards compatibility,
9944 <xref linkend=
"libpq-PQinitSSL"/> and
<xref linkend=
"libpq-PQinitOpenSSL"/>
9945 are maintained for backwards compatibility, but are no longer required
9946 since
<productname>PostgreSQL
</productname> 18.
9947 <xref linkend=
"libpq-PQinitSSL"/> has been present since
9948 <productname>PostgreSQL
</productname> 8.0, while
<xref linkend=
"libpq-PQinitOpenSSL"/>
9949 was added in
<productname>PostgreSQL
</productname> 8.4, so
<xref linkend=
"libpq-PQinitSSL"/>
9950 might be preferable for applications that need to work with older
9951 versions of
<application>libpq
</application>.
9962 <sect1 id=
"libpq-threading">
9963 <title>Behavior in Threaded Programs
</title>
9965 <indexterm zone=
"libpq-threading">
9966 <primary>threads
</primary>
9967 <secondary>with libpq
</secondary>
9971 As of version
17,
<application>libpq
</application> is always reentrant and thread-safe.
9972 However, one restriction is that no two threads attempt to manipulate
9973 the same
<structname>PGconn
</structname> object at the same time. In particular,
9974 you cannot issue concurrent commands from different threads through
9975 the same connection object. (If you need to run concurrent commands,
9976 use multiple connections.)
9980 <structname>PGresult
</structname> objects are normally read-only after creation,
9981 and so can be passed around freely between threads. However, if you use
9982 any of the
<structname>PGresult
</structname>-modifying functions described in
9983 <xref linkend=
"libpq-misc"/> or
<xref linkend=
"libpq-events"/>, it's up
9984 to you to avoid concurrent operations on the same
<structname>PGresult
</structname>,
9989 In earlier versions,
<application>libpq
</application> could be compiled
9990 with or without thread support, depending on compiler options. This
9991 function allows the querying of
<application>libpq
</application>'s
9996 <varlistentry id=
"libpq-PQisthreadsafe">
9997 <term><function>PQisthreadsafe
</function><indexterm><primary>PQisthreadsafe
</primary></indexterm></term>
10001 Returns the thread safety status of the
10002 <application>libpq
</application> library.
10004 int PQisthreadsafe();
10009 Returns
1 if the
<application>libpq
</application> is thread-safe
10010 and
0 if it is not. Always returns
1 on version
17 and above.
10017 The deprecated functions
<xref linkend=
"libpq-PQrequestCancel"/> and
10018 <xref linkend=
"libpq-PQoidStatus"/> are not thread-safe and should not be
10019 used in multithread programs.
<xref linkend=
"libpq-PQrequestCancel"/>
10020 can be replaced by
<xref linkend=
"libpq-PQcancelBlocking"/>.
10021 <xref linkend=
"libpq-PQoidStatus"/> can be replaced by
10022 <xref linkend=
"libpq-PQoidValue"/>.
10026 If you are using Kerberos inside your application (in addition to inside
10027 <application>libpq
</application>), you will need to do locking around
10028 Kerberos calls because Kerberos functions are not thread-safe. See
10029 function
<function>PQregisterThreadLock
</function> in the
10030 <application>libpq
</application> source code for a way to do cooperative
10031 locking between
<application>libpq
</application> and your application.
10036 <sect1 id=
"libpq-build">
10037 <title>Building
<application>libpq
</application> Programs
</title>
10039 <indexterm zone=
"libpq-build">
10040 <primary>compiling
</primary>
10041 <secondary>libpq applications
</secondary>
10045 To build (i.e., compile and link) a program using
10046 <application>libpq
</application> you need to do all of the following
10052 Include the
<filename>libpq-fe.h
</filename> header file:
10054 #include
<libpq-fe.h
>
10056 If you failed to do that then you will normally get error messages
10057 from your compiler similar to:
10059 foo.c: In function `main':
10060 foo.c:
34: `PGconn' undeclared (first use in this function)
10061 foo.c:
35: `PGresult' undeclared (first use in this function)
10062 foo.c:
54: `CONNECTION_BAD' undeclared (first use in this function)
10063 foo.c:
68: `PGRES_COMMAND_OK' undeclared (first use in this function)
10064 foo.c:
95: `PGRES_TUPLES_OK' undeclared (first use in this function)
10071 Point your compiler to the directory where the
<productname>PostgreSQL
</productname> header
10072 files were installed, by supplying the
10073 <literal>-I
<replaceable>directory
</replaceable></literal> option
10074 to your compiler. (In some cases the compiler will look into
10075 the directory in question by default, so you can omit this
10076 option.) For instance, your compile command line could look
10079 cc -c -I/usr/local/pgsql/include testprog.c
10081 If you are using makefiles then add the option to the
10082 <varname>CPPFLAGS
</varname> variable:
10084 CPPFLAGS += -I/usr/local/pgsql/include
10089 If there is any chance that your program might be compiled by
10090 other users then you should not hardcode the directory location
10091 like that. Instead, you can run the utility
10092 <command>pg_config
</command><indexterm><primary>pg_config
</primary><secondary
10093 sortas=
"libpq">with libpq
</secondary></indexterm> to find out where the header
10094 files are on the local system:
10096 <prompt>$
</prompt> pg_config --includedir
10097 <computeroutput>/usr/local/include
</computeroutput>
10103 have
<command>pkg-config
</command><indexterm><primary>pkg-config
</primary><secondary sortas=
"libpq">with
10104 libpq
</secondary></indexterm> installed, you can run instead:
10106 <prompt>$
</prompt> pkg-config --cflags libpq
10107 <computeroutput>-I/usr/local/include
</computeroutput>
10109 Note that this will already include the
<option>-I
</option> in front of
10114 Failure to specify the correct option to the compiler will
10115 result in an error message such as:
10117 testlibpq.c:
8:
22: libpq-fe.h: No such file or directory
10124 When linking the final program, specify the option
10125 <literal>-lpq
</literal> so that the
<application>libpq
</application>
10126 library gets pulled in, as well as the option
10127 <literal>-L
<replaceable>directory
</replaceable></literal> to point
10128 the compiler to the directory where the
10129 <application>libpq
</application> library resides. (Again, the
10130 compiler will search some directories by default.) For maximum
10131 portability, put the
<option>-L
</option> option before the
10132 <option>-lpq
</option> option. For example:
10134 cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq
10139 You can find out the library directory using
10140 <command>pg_config
</command> as well:
10142 <prompt>$
</prompt> pg_config --libdir
10143 <computeroutput>/usr/local/pgsql/lib
</computeroutput>
10148 Or again use
<command>pkg-config
</command>:
10150 <prompt>$
</prompt> pkg-config --libs libpq
10151 <computeroutput>-L/usr/local/pgsql/lib -lpq
</computeroutput>
10153 Note again that this prints the full options, not only the path.
10157 Error messages that point to problems in this area could look like
10160 testlibpq.o: In function `main':
10161 testlibpq.o(.text+
0x60): undefined reference to `PQsetdbLogin'
10162 testlibpq.o(.text+
0x71): undefined reference to `PQstatus'
10163 testlibpq.o(.text+
0xa4): undefined reference to `PQerrorMessage'
10165 This means you forgot
<option>-lpq
</option>.
10167 /usr/bin/ld: cannot find -lpq
10169 This means you forgot the
<option>-L
</option> option or did not
10170 specify the right directory.
10179 <sect1 id=
"libpq-example">
10180 <title>Example Programs
</title>
10183 These examples and others can be found in the
10184 directory
<filename>src/test/examples
</filename> in the source code
10188 <example id=
"libpq-example-1">
10189 <title><application>libpq
</application> Example Program
1</title>
10194 * src/test/examples/testlibpq.c
10199 * Test the C version of libpq, the PostgreSQL frontend library.
10202 #include
<stdlib.h
>
10203 #include
"libpq-fe.h"
10206 exit_nicely(PGconn *conn)
10213 main(int argc, char **argv)
10215 const char *conninfo;
10223 * If the user supplies a parameter on the command line, use it as the
10224 * conninfo string; otherwise default to setting dbname=postgres and using
10225 * environment variables or defaults for all other connection parameters.
10228 conninfo = argv[
1];
10230 conninfo =
"dbname = postgres";
10232 /* Make a connection to the database */
10233 conn = PQconnectdb(conninfo);
10235 /* Check to see that the backend connection was successfully made */
10236 if (PQstatus(conn) != CONNECTION_OK)
10238 fprintf(stderr,
"%s", PQerrorMessage(conn));
10242 /* Set always-secure search path, so malicious users can't take control. */
10244 "SELECT pg_catalog.set_config('search_path', '', false)");
10245 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10247 fprintf(stderr,
"SET failed: %s", PQerrorMessage(conn));
10253 * Should PQclear PGresult whenever it is no longer needed to avoid memory
10259 * Our test case here involves using a cursor, for which we must be inside
10260 * a transaction block. We could do the whole thing with a single
10261 * PQexec() of
"select * from pg_database", but that's too trivial to make
10265 /* Start a transaction block */
10266 res = PQexec(conn,
"BEGIN");
10267 if (PQresultStatus(res) != PGRES_COMMAND_OK)
10269 fprintf(stderr,
"BEGIN command failed: %s", PQerrorMessage(conn));
10276 * Fetch rows from pg_database, the system catalog of databases
10278 res = PQexec(conn,
"DECLARE myportal CURSOR FOR select * from pg_database");
10279 if (PQresultStatus(res) != PGRES_COMMAND_OK)
10281 fprintf(stderr,
"DECLARE CURSOR failed: %s", PQerrorMessage(conn));
10287 res = PQexec(conn,
"FETCH ALL in myportal");
10288 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10290 fprintf(stderr,
"FETCH ALL failed: %s", PQerrorMessage(conn));
10295 /* first, print out the attribute names */
10296 nFields = PQnfields(res);
10297 for (i =
0; i < nFields; i++)
10298 printf(
"%-15s", PQfname(res, i));
10301 /* next, print out the rows */
10302 for (i =
0; i < PQntuples(res); i++)
10304 for (j =
0; j < nFields; j++)
10305 printf(
"%-15s", PQgetvalue(res, i, j));
10311 /* close the portal ... we don't bother to check for errors ... */
10312 res = PQexec(conn,
"CLOSE myportal");
10315 /* end the transaction */
10316 res = PQexec(conn,
"END");
10319 /* close the connection to the database and cleanup */
10328 <example id=
"libpq-example-2">
10329 <title><application>libpq
</application> Example Program
2</title>
10334 * src/test/examples/testlibpq2.c
10338 * Test of the asynchronous notification interface
10340 * Start this program, then from psql in another window do
10342 * Repeat four times to get this program to exit.
10344 * Or, if you want to get fancy, try this:
10345 * populate a database with the following commands
10346 * (provided in src/test/examples/testlibpq2.sql):
10348 * CREATE SCHEMA TESTLIBPQ2;
10349 * SET search_path = TESTLIBPQ2;
10350 * CREATE TABLE TBL1 (i int4);
10351 * CREATE TABLE TBL2 (i int4);
10352 * CREATE RULE r1 AS ON INSERT TO TBL1 DO
10353 * (INSERT INTO TBL2 VALUES (new.i); NOTIFY TBL2);
10355 * Start this program, then from psql do this four times:
10357 * INSERT INTO TESTLIBPQ2.TBL1 VALUES (
10);
10361 #include
<windows.h
>
10364 #include
<stdlib.h
>
10365 #include
<string.h
>
10367 #include
<sys/select.h
>
10368 #include
<sys/time.h
>
10369 #include
<sys/types.h
>
10371 #include
"libpq-fe.h"
10374 exit_nicely(PGconn *conn)
10381 main(int argc, char **argv)
10383 const char *conninfo;
10390 * If the user supplies a parameter on the command line, use it as the
10391 * conninfo string; otherwise default to setting dbname=postgres and using
10392 * environment variables or defaults for all other connection parameters.
10395 conninfo = argv[
1];
10397 conninfo =
"dbname = postgres";
10399 /* Make a connection to the database */
10400 conn = PQconnectdb(conninfo);
10402 /* Check to see that the backend connection was successfully made */
10403 if (PQstatus(conn) != CONNECTION_OK)
10405 fprintf(stderr,
"%s", PQerrorMessage(conn));
10409 /* Set always-secure search path, so malicious users can't take control. */
10411 "SELECT pg_catalog.set_config('search_path', '', false)");
10412 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10414 fprintf(stderr,
"SET failed: %s", PQerrorMessage(conn));
10420 * Should PQclear PGresult whenever it is no longer needed to avoid memory
10426 * Issue LISTEN command to enable notifications from the rule's NOTIFY.
10428 res = PQexec(conn,
"LISTEN TBL2");
10429 if (PQresultStatus(res) != PGRES_COMMAND_OK)
10431 fprintf(stderr,
"LISTEN command failed: %s", PQerrorMessage(conn));
10437 /* Quit after four notifies are received. */
10439 while (nnotifies <
4)
10442 * Sleep until something happens on the connection. We use select(
2)
10443 * to wait for input, but you could also use poll() or similar
10449 sock = PQsocket(conn);
10452 break; /* shouldn't happen */
10454 FD_ZERO(&input_mask);
10455 FD_SET(sock, &input_mask);
10457 if (select(sock +
1, &input_mask, NULL, NULL, NULL) <
0)
10459 fprintf(stderr,
"select() failed: %s\n", strerror(errno));
10463 /* Now check for input */
10464 PQconsumeInput(conn);
10465 while ((notify = PQnotifies(conn)) != NULL)
10468 "ASYNC NOTIFY of '%s' received from backend PID %d\n",
10469 notify-
>relname, notify-
>be_pid);
10472 PQconsumeInput(conn);
10476 fprintf(stderr,
"Done.\n");
10478 /* close the connection to the database and cleanup */
10487 <example id=
"libpq-example-3">
10488 <title><application>libpq
</application> Example Program
3</title>
10493 * src/test/examples/testlibpq3.c
10497 * Test out-of-line parameters and binary I/O.
10499 * Before running this, populate a database with the following commands
10500 * (provided in src/test/examples/testlibpq3.sql):
10502 * CREATE SCHEMA testlibpq3;
10503 * SET search_path = testlibpq3;
10504 * SET standard_conforming_strings = ON;
10505 * CREATE TABLE test1 (i int4, t text, b bytea);
10506 * INSERT INTO test1 values (
1, 'joe''s place', '\
000\
001\
002\
003\
004');
10507 * INSERT INTO test1 values (
2, 'ho there', '\
004\
003\
002\
001\
000');
10509 * The expected output is:
10513 * t = (
11 bytes) 'joe's place'
10514 * b = (
5 bytes) \
000\
001\
002\
003\
004
10518 * t = (
8 bytes) 'ho there'
10519 * b = (
5 bytes) \
004\
003\
002\
001\
000
10523 #include
<windows.h
>
10527 #include
<stdlib.h
>
10528 #include
<stdint.h
>
10529 #include
<string.h
>
10530 #include
<sys/types.h
>
10531 #include
"libpq-fe.h"
10533 /* for ntohl/htonl */
10534 #include
<netinet/in.h
>
10535 #include
<arpa/inet.h
>
10539 exit_nicely(PGconn *conn)
10546 * This function prints a query result that is a binary-format fetch from
10547 * a table defined as in the comment above. We split it out because the
10548 * main() function uses it twice.
10551 show_binary_results(PGresult *res)
10559 /* Use PQfnumber to avoid assumptions about field order in result */
10560 i_fnum = PQfnumber(res,
"i");
10561 t_fnum = PQfnumber(res,
"t");
10562 b_fnum = PQfnumber(res,
"b");
10564 for (i =
0; i < PQntuples(res); i++)
10572 /* Get the field values (we ignore possibility they are null!) */
10573 iptr = PQgetvalue(res, i, i_fnum);
10574 tptr = PQgetvalue(res, i, t_fnum);
10575 bptr = PQgetvalue(res, i, b_fnum);
10578 * The binary representation of INT4 is in network byte order, which
10579 * we'd better coerce to the local byte order.
10581 ival = ntohl(*((uint32_t *) iptr));
10584 * The binary representation of TEXT is, well, text, and since libpq
10585 * was nice enough to append a zero byte to it, it'll work just fine
10588 * The binary representation of BYTEA is a bunch of bytes, which could
10589 * include embedded nulls so we have to pay attention to field length.
10591 blen = PQgetlength(res, i, b_fnum);
10593 printf(
"tuple %d: got\n", i);
10594 printf(
" i = (%d bytes) %d\n",
10595 PQgetlength(res, i, i_fnum), ival);
10596 printf(
" t = (%d bytes) '%s'\n",
10597 PQgetlength(res, i, t_fnum), tptr);
10598 printf(
" b = (%d bytes) ", blen);
10599 for (j =
0; j < blen; j++)
10600 printf(
"\\%03o", bptr[j]);
10606 main(int argc, char **argv)
10608 const char *conninfo;
10611 const char *paramValues[
1];
10612 int paramLengths[
1];
10613 int paramFormats[
1];
10614 uint32_t binaryIntVal;
10617 * If the user supplies a parameter on the command line, use it as the
10618 * conninfo string; otherwise default to setting dbname=postgres and using
10619 * environment variables or defaults for all other connection parameters.
10622 conninfo = argv[
1];
10624 conninfo =
"dbname = postgres";
10626 /* Make a connection to the database */
10627 conn = PQconnectdb(conninfo);
10629 /* Check to see that the backend connection was successfully made */
10630 if (PQstatus(conn) != CONNECTION_OK)
10632 fprintf(stderr,
"%s", PQerrorMessage(conn));
10636 /* Set always-secure search path, so malicious users can't take control. */
10637 res = PQexec(conn,
"SET search_path = testlibpq3");
10638 if (PQresultStatus(res) != PGRES_COMMAND_OK)
10640 fprintf(stderr,
"SET failed: %s", PQerrorMessage(conn));
10647 * The point of this program is to illustrate use of PQexecParams() with
10648 * out-of-line parameters, as well as binary transmission of data.
10650 * This first example transmits the parameters as text, but receives the
10651 * results in binary format. By using out-of-line parameters we can avoid
10652 * a lot of tedious mucking about with quoting and escaping, even though
10653 * the data is text. Notice how we don't have to do anything special with
10654 * the quote mark in the parameter value.
10657 /* Here is our out-of-line parameter value */
10658 paramValues[
0] =
"joe's place";
10660 res = PQexecParams(conn,
10661 "SELECT * FROM test1 WHERE t = $1",
10663 NULL, /* let the backend deduce param type */
10665 NULL, /* don't need param lengths since text */
10666 NULL, /* default to all text params */
10667 1); /* ask for binary results */
10669 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10671 fprintf(stderr,
"SELECT failed: %s", PQerrorMessage(conn));
10676 show_binary_results(res);
10681 * In this second example we transmit an integer parameter in binary form,
10682 * and again retrieve the results in binary form.
10684 * Although we tell PQexecParams we are letting the backend deduce
10685 * parameter type, we really force the decision by casting the parameter
10686 * symbol in the query text. This is a good safety measure when sending
10687 * binary parameters.
10690 /* Convert integer value
"2" to network byte order */
10691 binaryIntVal = htonl((uint32_t)
2);
10693 /* Set up parameter arrays for PQexecParams */
10694 paramValues[
0] = (char *)
&binaryIntVal;
10695 paramLengths[
0] = sizeof(binaryIntVal);
10696 paramFormats[
0] =
1; /* binary */
10698 res = PQexecParams(conn,
10699 "SELECT * FROM test1 WHERE i = $1::int4",
10701 NULL, /* let the backend deduce param type */
10705 1); /* ask for binary results */
10707 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10709 fprintf(stderr,
"SELECT failed: %s", PQerrorMessage(conn));
10714 show_binary_results(res);
10718 /* close the connection to the database and cleanup */