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>server_encoding
</varname></member>
2647 <member><varname>server_version
</varname></member>
2648 <member><varname>session_authorization
</varname></member>
2649 <member><varname>standard_conforming_strings
</varname></member>
2650 <member><varname>TimeZone
</varname></member>
2652 (
<varname>default_transaction_read_only
</varname> and
2653 <varname>in_hot_standby
</varname> were not reported by releases before
2654 14;
<varname>scram_iterations
</varname> was not reported by releases
2657 <varname>server_version
</varname>,
2658 <varname>server_encoding
</varname> and
2659 <varname>integer_datetimes
</varname>
2660 cannot change after startup.
2664 If no value for
<varname>standard_conforming_strings
</varname> is reported,
2665 applications can assume it is
<literal>off
</literal>, that is, backslashes
2666 are treated as escapes in string literals. Also, the presence of
2667 this parameter can be taken as an indication that the escape string
2668 syntax (
<literal>E'...'
</literal>) is accepted.
2672 Although the returned pointer is declared
<literal>const
</literal>, it in fact
2673 points to mutable storage associated with the
<literal>PGconn
</literal> structure.
2674 It is unwise to assume the pointer will remain valid across queries.
2679 <varlistentry id=
"libpq-PQprotocolVersion">
2680 <term><function>PQprotocolVersion
</function><indexterm><primary>PQprotocolVersion
</primary></indexterm></term>
2684 Interrogates the frontend/backend protocol being used.
2686 int PQprotocolVersion(const PGconn *conn);
2688 Applications might wish to use this function to determine whether certain
2689 features are supported. Currently, the possible values are
3
2690 (
3.0 protocol), or zero (connection bad). The protocol version will
2691 not change after connection startup is complete, but it could
2692 theoretically change during a connection reset. The
3.0 protocol is
2693 supported by
<productname>PostgreSQL
</productname> server versions
7.4
2699 <varlistentry id=
"libpq-PQserverVersion">
2700 <term><function>PQserverVersion
</function><indexterm><primary>PQserverVersion
</primary></indexterm></term>
2704 Returns an integer representing the server version.
2706 int PQserverVersion(const PGconn *conn);
2711 Applications might use this function to determine the version of the
2712 database server they are connected to. The result is formed by
2713 multiplying the server's major version number by
10000 and adding
2714 the minor version number. For example, version
10.1 will be
2715 returned as
100001, and version
11.0 will be returned as
110000.
2716 Zero is returned if the connection is bad.
2720 Prior to major version
10,
<productname>PostgreSQL
</productname> used
2721 three-part version numbers in which the first two parts together
2722 represented the major version. For those
2723 versions,
<xref linkend=
"libpq-PQserverVersion"/> uses two digits for each
2724 part; for example version
9.1.5 will be returned as
90105, and
2725 version
9.2.0 will be returned as
90200.
2729 Therefore, for purposes of determining feature compatibility,
2730 applications should divide the result of
<xref linkend=
"libpq-PQserverVersion"/>
2731 by
100 not
10000 to determine a logical major version number.
2732 In all release series, only the last two digits differ between
2733 minor releases (bug-fix releases).
2738 <varlistentry id=
"libpq-PQerrorMessage">
2740 <function>PQerrorMessage
</function><indexterm><primary>PQerrorMessage
</primary></indexterm>
2741 <indexterm><primary>error message
</primary><secondary>in
<structname>PGconn
</structname></secondary></indexterm>
2746 Returns the error message most recently generated by
2747 an operation on the connection.
2750 char *PQerrorMessage(const PGconn *conn);
2755 Nearly all
<application>libpq
</application> functions will set a message for
2756 <xref linkend=
"libpq-PQerrorMessage"/> if they fail. Note that by
2757 <application>libpq
</application> convention, a nonempty
2758 <xref linkend=
"libpq-PQerrorMessage"/> result can consist of multiple lines,
2759 and will include a trailing newline. The caller should not free
2760 the result directly. It will be freed when the associated
2761 <structname>PGconn
</structname> handle is passed to
2762 <xref linkend=
"libpq-PQfinish"/>. The result string should not be
2763 expected to remain the same across operations on the
2764 <literal>PGconn
</literal> structure.
2769 <varlistentry id=
"libpq-PQsocket">
2770 <term><function>PQsocket
</function><indexterm><primary>PQsocket
</primary></indexterm></term>
2773 Obtains the file descriptor number of the connection socket to
2774 the server. A valid descriptor will be greater than or equal
2775 to
0; a result of -
1 indicates that no server connection is
2776 currently open. (This will not change during normal operation,
2777 but could change during connection setup or reset.)
2780 int PQsocket(const PGconn *conn);
2787 <varlistentry id=
"libpq-PQbackendPID">
2788 <term><function>PQbackendPID
</function><indexterm><primary>PQbackendPID
</primary></indexterm></term>
2791 Returns the process
<acronym>ID
</acronym> (PID)
<indexterm>
2792 <primary>PID
</primary>
2793 <secondary>determining PID of server process
</secondary>
2794 <tertiary>in libpq
</tertiary>
2796 of the backend process handling this connection.
2799 int PQbackendPID(const PGconn *conn);
2804 The backend
<acronym>PID
</acronym> is useful for debugging
2805 purposes and for comparison to
<command>NOTIFY
</command>
2806 messages (which include the
<acronym>PID
</acronym> of the
2807 notifying backend process). Note that the
2808 <acronym>PID
</acronym> belongs to a process executing on the
2809 database server host, not the local host!
2814 <varlistentry id=
"libpq-PQconnectionNeedsPassword">
2815 <term><function>PQconnectionNeedsPassword
</function><indexterm><primary>PQconnectionNeedsPassword
</primary></indexterm></term>
2818 Returns true (
1) if the connection authentication method
2819 required a password, but none was available.
2820 Returns false (
0) if not.
2823 int PQconnectionNeedsPassword(const PGconn *conn);
2828 This function can be applied after a failed connection attempt
2829 to decide whether to prompt the user for a password.
2834 <varlistentry id=
"libpq-PQconnectionUsedPassword">
2835 <term><function>PQconnectionUsedPassword
</function><indexterm><primary>PQconnectionUsedPassword
</primary></indexterm></term>
2838 Returns true (
1) if the connection authentication method
2839 used a password. Returns false (
0) if not.
2842 int PQconnectionUsedPassword(const PGconn *conn);
2847 This function can be applied after either a failed or successful
2848 connection attempt to detect whether the server demanded a password.
2853 <varlistentry id=
"libpq-PQconnectionUsedGSSAPI">
2854 <term><function>PQconnectionUsedGSSAPI
</function><indexterm><primary>PQconnectionUsedGSSAPI
</primary></indexterm></term>
2857 Returns true (
1) if the connection authentication method
2858 used GSSAPI. Returns false (
0) if not.
2861 int PQconnectionUsedGSSAPI(const PGconn *conn);
2866 This function can be applied to detect whether the connection was
2867 authenticated with GSSAPI.
2875 The following functions return information related to SSL. This information
2876 usually doesn't change after a connection is established.
2879 <varlistentry id=
"libpq-PQsslInUse">
2880 <term><function>PQsslInUse
</function><indexterm><primary>PQsslInUse
</primary></indexterm></term>
2883 Returns true (
1) if the connection uses SSL, false (
0) if not.
2886 int PQsslInUse(const PGconn *conn);
2893 <varlistentry id=
"libpq-PQsslAttribute">
2894 <term><function>PQsslAttribute
</function><indexterm><primary>PQsslAttribute
</primary></indexterm></term>
2897 Returns SSL-related information about the connection.
2900 const char *PQsslAttribute(const PGconn *conn, const char *attribute_name);
2905 The list of available attributes varies depending on the SSL library
2906 being used and the type of connection. Returns NULL if the connection
2907 does not use SSL or the specified attribute name is not defined for the
2912 The following attributes are commonly available:
2915 <term><literal>library
</literal></term>
2918 Name of the SSL implementation in use. (Currently, only
2919 <literal>"OpenSSL"</literal> is implemented)
2924 <term><literal>protocol
</literal></term>
2927 SSL/TLS version in use. Common values
2928 are
<literal>"TLSv1"</literal>,
<literal>"TLSv1.1"</literal>
2929 and
<literal>"TLSv1.2"</literal>, but an implementation may
2930 return other strings if some other protocol is used.
2935 <term><literal>key_bits
</literal></term>
2938 Number of key bits used by the encryption algorithm.
2943 <term><literal>cipher
</literal></term>
2946 A short name of the ciphersuite used, e.g.,
2947 <literal>"DHE-RSA-DES-CBC3-SHA"</literal>. The names are specific
2948 to each SSL implementation.
2953 <term><literal>compression
</literal></term>
2956 Returns
"on" if SSL compression is in use, else it returns
"off".
2961 <term><literal>alpn
</literal></term>
2964 Application protocol selected by the TLS Application-Layer
2965 Protocol Negotiation (ALPN) extension. The only protocol
2966 supported by libpq is
<literal>postgresql
</literal>, so this is
2967 mainly useful for checking whether the server supported ALPN or
2968 not. Empty string if ALPN was not used.
2976 As a special case, the
<literal>library
</literal> attribute may be
2977 queried without a connection by passing NULL as
2978 the
<literal>conn
</literal> argument. The result will be the default
2979 SSL library name, or NULL if
<application>libpq
</application> was
2980 compiled without any SSL support. (Prior
2981 to
<productname>PostgreSQL
</productname> version
15, passing NULL as
2982 the
<literal>conn
</literal> argument always resulted in NULL.
2983 Client programs needing to differentiate between the newer and older
2984 implementations of this case may check the
2985 <literal>LIBPQ_HAS_SSL_LIBRARY_DETECTION
</literal> feature macro.)
2990 <varlistentry id=
"libpq-PQsslAttributeNames">
2991 <term><function>PQsslAttributeNames
</function><indexterm><primary>PQsslAttributeNames
</primary></indexterm></term>
2994 Returns an array of SSL attribute names that can be used
2995 in
<function>PQsslAttribute()
</function>.
2996 The array is terminated by a NULL pointer.
2998 const char * const * PQsslAttributeNames(const PGconn *conn);
3003 If
<literal>conn
</literal> is NULL, the attributes available for the
3004 default SSL library are returned, or an empty list
3005 if
<application>libpq
</application> was compiled without any SSL
3006 support. If
<literal>conn
</literal> is not NULL, the attributes
3007 available for the SSL library in use for the connection are returned,
3008 or an empty list if the connection is not encrypted.
3013 <varlistentry id=
"libpq-PQsslStruct">
3014 <term><function>PQsslStruct
</function><indexterm><primary>PQsslStruct
</primary></indexterm></term>
3017 Returns a pointer to an SSL-implementation-specific object describing
3018 the connection. Returns NULL if the connection is not encrypted
3019 or the requested type of object is not available from the connection's
3022 void *PQsslStruct(const PGconn *conn, const char *struct_name);
3026 The struct(s) available depend on the SSL implementation in use.
3027 For
<productname>OpenSSL
</productname>, there is one struct,
3028 available under the name
<literal>OpenSSL
</literal>,
3029 and it returns a pointer to
3030 <productname>OpenSSL
</productname>'s
<literal>SSL
</literal> struct.
3031 To use this function, code along the following lines could be used:
3032 <programlisting><![CDATA[
3033 #include
<libpq-fe.h
>
3034 #include
<openssl/ssl.h
>
3040 dbconn = PQconnectdb(...);
3043 ssl = PQsslStruct(dbconn,
"OpenSSL");
3046 /* use OpenSSL functions to access ssl */
3048 ]]
></programlisting>
3051 This structure can be used to verify encryption levels, check server
3052 certificates, and more. Refer to the
<productname>OpenSSL
</productname>
3053 documentation for information about this structure.
3058 <varlistentry id=
"libpq-PQgetssl">
3059 <term><function>PQgetssl
</function><indexterm><primary>PQgetssl
</primary></indexterm></term>
3062 <indexterm><primary>SSL
</primary><secondary sortas=
"libpq">in libpq
</secondary></indexterm>
3063 Returns the SSL structure used in the connection, or NULL
3064 if SSL is not in use.
3067 void *PQgetssl(const PGconn *conn);
3072 This function is equivalent to
<literal>PQsslStruct(conn,
"OpenSSL")
</literal>. It should
3073 not be used in new applications, because the returned struct is
3074 specific to
<productname>OpenSSL
</productname> and will not be
3075 available if another
<acronym>SSL
</acronym> implementation is used.
3076 To check if a connection uses SSL, call
3077 <xref linkend=
"libpq-PQsslInUse"/> instead, and for more details about the
3078 connection, use
<xref linkend=
"libpq-PQsslAttribute"/>.
3088 <sect1 id=
"libpq-exec">
3089 <title>Command Execution Functions
</title>
3092 Once a connection to a database server has been successfully
3093 established, the functions described here are used to perform
3094 SQL queries and commands.
3097 <sect2 id=
"libpq-exec-main">
3098 <title>Main Functions
</title>
3102 <varlistentry id=
"libpq-PQexec">
3103 <term><function>PQexec
</function><indexterm><primary>PQexec
</primary></indexterm></term>
3107 Submits a command to the server and waits for the result.
3110 PGresult *PQexec(PGconn *conn, const char *command);
3115 Returns a
<structname>PGresult
</structname> pointer or possibly a null
3116 pointer. A non-null pointer will generally be returned except in
3117 out-of-memory conditions or serious errors such as inability to send
3118 the command to the server. The
<xref linkend=
"libpq-PQresultStatus"/> function
3119 should be called to check the return value for any errors (including
3120 the value of a null pointer, in which case it will return
3121 <symbol>PGRES_FATAL_ERROR
</symbol>). Use
3122 <xref linkend=
"libpq-PQerrorMessage"/> to get more information about such
3129 The command string can include multiple SQL commands
3130 (separated by semicolons). Multiple queries sent in a single
3131 <xref linkend=
"libpq-PQexec"/> call are processed in a single transaction, unless
3132 there are explicit
<command>BEGIN
</command>/
<command>COMMIT
</command>
3133 commands included in the query string to divide it into multiple
3134 transactions. (See
<xref linkend=
"protocol-flow-multi-statement"/>
3135 for more details about how the server handles multi-query strings.)
3136 Note however that the returned
3137 <structname>PGresult
</structname> structure describes only the result
3138 of the last command executed from the string. Should one of the
3139 commands fail, processing of the string stops with it and the returned
3140 <structname>PGresult
</structname> describes the error condition.
3145 <varlistentry id=
"libpq-PQexecParams">
3146 <term><function>PQexecParams
</function><indexterm><primary>PQexecParams
</primary></indexterm></term>
3150 Submits a command to the server and waits for the result,
3151 with the ability to pass parameters separately from the SQL
3155 PGresult *PQexecParams(PGconn *conn,
3156 const char *command,
3158 const Oid *paramTypes,
3159 const char * const *paramValues,
3160 const int *paramLengths,
3161 const int *paramFormats,
3167 <xref linkend=
"libpq-PQexecParams"/> is like
<xref linkend=
"libpq-PQexec"/>, but offers additional
3168 functionality: parameter values can be specified separately from the command
3169 string proper, and query results can be requested in either text or binary
3174 The function arguments are:
3178 <term><parameter>conn
</parameter></term>
3182 The connection object to send the command through.
3188 <term><parameter>command
</parameter></term>
3191 The SQL command string to be executed. If parameters are used,
3192 they are referred to in the command string as
<literal>$
1</literal>,
3193 <literal>$
2</literal>, etc.
3199 <term><parameter>nParams
</parameter></term>
3202 The number of parameters supplied; it is the length of the arrays
3203 <parameter>paramTypes[]
</parameter>,
<parameter>paramValues[]
</parameter>,
3204 <parameter>paramLengths[]
</parameter>, and
<parameter>paramFormats[]
</parameter>. (The
3205 array pointers can be
<symbol>NULL
</symbol> when
<parameter>nParams
</parameter>
3212 <term><parameter>paramTypes[]
</parameter></term>
3215 Specifies, by OID, the data types to be assigned to the
3216 parameter symbols. If
<parameter>paramTypes
</parameter> is
3217 <symbol>NULL
</symbol>, or any particular element in the array
3218 is zero, the server infers a data type for the parameter symbol
3219 in the same way it would do for an untyped literal string.
3225 <term><parameter>paramValues[]
</parameter></term>
3228 Specifies the actual values of the parameters. A null pointer
3229 in this array means the corresponding parameter is null;
3230 otherwise the pointer points to a zero-terminated text string
3231 (for text format) or binary data in the format expected by the
3232 server (for binary format).
3238 <term><parameter>paramLengths[]
</parameter></term>
3241 Specifies the actual data lengths of binary-format parameters.
3242 It is ignored for null parameters and text-format parameters.
3243 The array pointer can be null when there are no binary parameters.
3249 <term><parameter>paramFormats[]
</parameter></term>
3252 Specifies whether parameters are text (put a zero in the
3253 array entry for the corresponding parameter) or binary (put
3254 a one in the array entry for the corresponding parameter).
3255 If the array pointer is null then all parameters are presumed
3259 Values passed in binary format require knowledge of
3260 the internal representation expected by the backend.
3261 For example, integers must be passed in network byte
3262 order. Passing
<type>numeric
</type> values requires
3263 knowledge of the server storage format, as implemented
3265 <filename>src/backend/utils/adt/numeric.c::numeric_send()
</filename> and
3266 <filename>src/backend/utils/adt/numeric.c::numeric_recv()
</filename>.
3272 <term><parameter>resultFormat
</parameter></term>
3275 Specify zero to obtain results in text format, or one to obtain
3276 results in binary format. (There is not currently a provision
3277 to obtain different result columns in different formats,
3278 although that is possible in the underlying protocol.)
3290 The primary advantage of
<xref linkend=
"libpq-PQexecParams"/> over
3291 <xref linkend=
"libpq-PQexec"/> is that parameter values can be separated from the
3292 command string, thus avoiding the need for tedious and error-prone
3293 quoting and escaping.
3297 Unlike
<xref linkend=
"libpq-PQexec"/>,
<xref linkend=
"libpq-PQexecParams"/> allows at most
3298 one SQL command in the given string. (There can be semicolons in it,
3299 but not more than one nonempty command.) This is a limitation of the
3300 underlying protocol, but has some usefulness as an extra defense against
3301 SQL-injection attacks.
3306 Specifying parameter types via OIDs is tedious, particularly if you prefer
3307 not to hard-wire particular OID values into your program. However, you can
3308 avoid doing so even in cases where the server by itself cannot determine the
3309 type of the parameter, or chooses a different type than you want. In the
3310 SQL command text, attach an explicit cast to the parameter symbol to show what
3311 data type you will send. For example:
3313 SELECT * FROM mytable WHERE x = $
1::bigint;
3315 This forces parameter
<literal>$
1</literal> to be treated as
<type>bigint
</type>, whereas
3316 by default it would be assigned the same type as
<literal>x
</literal>. Forcing the
3317 parameter type decision, either this way or by specifying a numeric type OID,
3318 is strongly recommended when sending parameter values in binary format, because
3319 binary format has less redundancy than text format and so there is less chance
3320 that the server will detect a type mismatch mistake for you.
3326 <varlistentry id=
"libpq-PQprepare">
3327 <term><function>PQprepare
</function><indexterm><primary>PQprepare
</primary></indexterm></term>
3331 Submits a request to create a prepared statement with the
3332 given parameters, and waits for completion.
3334 PGresult *PQprepare(PGconn *conn,
3335 const char *stmtName,
3338 const Oid *paramTypes);
3343 <xref linkend=
"libpq-PQprepare"/> creates a prepared statement for later
3344 execution with
<xref linkend=
"libpq-PQexecPrepared"/>. This feature allows
3345 commands to be executed repeatedly without being parsed and
3346 planned each time; see
<xref linkend=
"sql-prepare"/> for details.
3350 The function creates a prepared statement named
3351 <parameter>stmtName
</parameter> from the
<parameter>query
</parameter> string, which
3352 must contain a single SQL command.
<parameter>stmtName
</parameter> can be
3353 <literal>""</literal> to create an unnamed statement, in which case any
3354 pre-existing unnamed statement is automatically replaced; otherwise
3355 it is an error if the statement name is already defined in the
3356 current session. If any parameters are used, they are referred
3357 to in the query as
<literal>$
1</literal>,
<literal>$
2</literal>, etc.
3358 <parameter>nParams
</parameter> is the number of parameters for which types
3359 are pre-specified in the array
<parameter>paramTypes[]
</parameter>. (The
3360 array pointer can be
<symbol>NULL
</symbol> when
3361 <parameter>nParams
</parameter> is zero.)
<parameter>paramTypes[]
</parameter>
3362 specifies, by OID, the data types to be assigned to the parameter
3363 symbols. If
<parameter>paramTypes
</parameter> is
<symbol>NULL
</symbol>,
3364 or any particular element in the array is zero, the server assigns
3365 a data type to the parameter symbol in the same way it would do
3366 for an untyped literal string. Also, the query can use parameter
3367 symbols with numbers higher than
<parameter>nParams
</parameter>; data types
3368 will be inferred for these symbols as well. (See
3369 <xref linkend=
"libpq-PQdescribePrepared"/> for a means to find out
3370 what data types were inferred.)
3374 As with
<xref linkend=
"libpq-PQexec"/>, the result is normally a
3375 <structname>PGresult
</structname> object whose contents indicate
3376 server-side success or failure. A null result indicates
3377 out-of-memory or inability to send the command at all. Use
3378 <xref linkend=
"libpq-PQerrorMessage"/> to get more information about
3385 Prepared statements for use with
<xref linkend=
"libpq-PQexecPrepared"/> can also
3386 be created by executing SQL
<xref linkend=
"sql-prepare"/>
3392 <varlistentry id=
"libpq-PQexecPrepared">
3393 <term><function>PQexecPrepared
</function><indexterm><primary>PQexecPrepared
</primary></indexterm></term>
3397 Sends a request to execute a prepared statement with given
3398 parameters, and waits for the result.
3400 PGresult *PQexecPrepared(PGconn *conn,
3401 const char *stmtName,
3403 const char * const *paramValues,
3404 const int *paramLengths,
3405 const int *paramFormats,
3411 <xref linkend=
"libpq-PQexecPrepared"/> is like
<xref linkend=
"libpq-PQexecParams"/>,
3412 but the command to be executed is specified by naming a
3413 previously-prepared statement, instead of giving a query string.
3414 This feature allows commands that will be used repeatedly to be
3415 parsed and planned just once, rather than each time they are
3416 executed. The statement must have been prepared previously in
3417 the current session.
3421 The parameters are identical to
<xref linkend=
"libpq-PQexecParams"/>, except that the
3422 name of a prepared statement is given instead of a query string, and the
3423 <parameter>paramTypes[]
</parameter> parameter is not present (it is not needed since
3424 the prepared statement's parameter types were determined when it was created).
3429 <varlistentry id=
"libpq-PQdescribePrepared">
3430 <term><function>PQdescribePrepared
</function><indexterm><primary>PQdescribePrepared
</primary></indexterm></term>
3434 Submits a request to obtain information about the specified
3435 prepared statement, and waits for completion.
3437 PGresult *PQdescribePrepared(PGconn *conn, const char *stmtName);
3442 <xref linkend=
"libpq-PQdescribePrepared"/> allows an application to obtain
3443 information about a previously prepared statement.
3447 <parameter>stmtName
</parameter> can be
<literal>""</literal> or
<symbol>NULL
</symbol> to reference
3448 the unnamed statement, otherwise it must be the name of an existing
3449 prepared statement. On success, a
<structname>PGresult
</structname> with
3450 status
<literal>PGRES_COMMAND_OK
</literal> is returned. The
3451 functions
<xref linkend=
"libpq-PQnparams"/> and
3452 <xref linkend=
"libpq-PQparamtype"/> can be applied to this
3453 <structname>PGresult
</structname> to obtain information about the parameters
3454 of the prepared statement, and the functions
3455 <xref linkend=
"libpq-PQnfields"/>,
<xref linkend=
"libpq-PQfname"/>,
3456 <xref linkend=
"libpq-PQftype"/>, etc. provide information about the
3457 result columns (if any) of the statement.
3462 <varlistentry id=
"libpq-PQdescribePortal">
3463 <term><function>PQdescribePortal
</function><indexterm><primary>PQdescribePortal
</primary></indexterm></term>
3467 Submits a request to obtain information about the specified
3468 portal, and waits for completion.
3470 PGresult *PQdescribePortal(PGconn *conn, const char *portalName);
3475 <xref linkend=
"libpq-PQdescribePortal"/> allows an application to obtain
3476 information about a previously created portal.
3477 (
<application>libpq
</application> does not provide any direct access to
3478 portals, but you can use this function to inspect the properties
3479 of a cursor created with a
<command>DECLARE CURSOR
</command> SQL command.)
3483 <parameter>portalName
</parameter> can be
<literal>""</literal> or
<symbol>NULL
</symbol> to reference
3484 the unnamed portal, otherwise it must be the name of an existing
3485 portal. On success, a
<structname>PGresult
</structname> with status
3486 <literal>PGRES_COMMAND_OK
</literal> is returned. The functions
3487 <xref linkend=
"libpq-PQnfields"/>,
<xref linkend=
"libpq-PQfname"/>,
3488 <xref linkend=
"libpq-PQftype"/>, etc. can be applied to the
3489 <structname>PGresult
</structname> to obtain information about the result
3490 columns (if any) of the portal.
3495 <varlistentry id=
"libpq-PQclosePrepared">
3496 <term><function>PQclosePrepared
</function><indexterm><primary>PQclosePrepared
</primary></indexterm></term>
3500 Submits a request to close the specified prepared statement, and waits
3503 PGresult *PQclosePrepared(PGconn *conn, const char *stmtName);
3508 <xref linkend=
"libpq-PQclosePrepared"/> allows an application to close
3509 a previously prepared statement. Closing a statement releases all
3510 of its associated resources on the server and allows its name to be
3515 <parameter>stmtName
</parameter> can be
<literal>""</literal> or
3516 <symbol>NULL
</symbol> to reference the unnamed statement. It is fine
3517 if no statement exists with this name, in that case the operation is a
3518 no-op. On success, a
<structname>PGresult
</structname> with
3519 status
<literal>PGRES_COMMAND_OK
</literal> is returned.
3524 <varlistentry id=
"libpq-PQclosePortal">
3525 <term><function>PQclosePortal
</function><indexterm><primary>PQclosePortal
</primary></indexterm></term>
3529 Submits a request to close the specified portal, and waits for
3532 PGresult *PQclosePortal(PGconn *conn, const char *portalName);
3537 <xref linkend=
"libpq-PQclosePortal"/> allows an application to trigger
3538 a close of a previously created portal. Closing a portal releases all
3539 of its associated resources on the server and allows its name to be
3540 reused. (
<application>libpq
</application> does not provide any
3541 direct access to portals, but you can use this function to close a
3542 cursor created with a
<command>DECLARE CURSOR
</command> SQL command.)
3546 <parameter>portalName
</parameter> can be
<literal>""</literal> or
3547 <symbol>NULL
</symbol> to reference the unnamed portal. It is fine
3548 if no portal exists with this name, in that case the operation is a
3549 no-op. On success, a
<structname>PGresult
</structname> with status
3550 <literal>PGRES_COMMAND_OK
</literal> is returned.
3558 The
<structname>PGresult
</structname><indexterm><primary>PGresult
</primary></indexterm>
3559 structure encapsulates the result returned by the server.
3560 <application>libpq
</application> application programmers should be
3561 careful to maintain the
<structname>PGresult
</structname> abstraction.
3562 Use the accessor functions below to get at the contents of
3563 <structname>PGresult
</structname>. Avoid directly referencing the
3564 fields of the
<structname>PGresult
</structname> structure because they
3565 are subject to change in the future.
3568 <varlistentry id=
"libpq-PQresultStatus">
3569 <term><function>PQresultStatus
</function><indexterm><primary>PQresultStatus
</primary></indexterm></term>
3573 Returns the result status of the command.
3575 ExecStatusType PQresultStatus(const PGresult *res);
3580 <xref linkend=
"libpq-PQresultStatus"/> can return one of the following values:
3583 <varlistentry id=
"libpq-pgres-empty-query">
3584 <term><literal>PGRES_EMPTY_QUERY
</literal></term>
3587 The string sent to the server was empty.
3592 <varlistentry id=
"libpq-pgres-command-ok">
3593 <term><literal>PGRES_COMMAND_OK
</literal></term>
3596 Successful completion of a command returning no data.
3601 <varlistentry id=
"libpq-pgres-tuples-ok">
3602 <term><literal>PGRES_TUPLES_OK
</literal></term>
3605 Successful completion of a command returning data (such as
3606 a
<command>SELECT
</command> or
<command>SHOW
</command>).
3611 <varlistentry id=
"libpq-pgres-copy-out">
3612 <term><literal>PGRES_COPY_OUT
</literal></term>
3615 Copy Out (from server) data transfer started.
3620 <varlistentry id=
"libpq-pgres-copy-in">
3621 <term><literal>PGRES_COPY_IN
</literal></term>
3624 Copy In (to server) data transfer started.
3629 <varlistentry id=
"libpq-pgres-bad-response">
3630 <term><literal>PGRES_BAD_RESPONSE
</literal></term>
3633 The server's response was not understood.
3638 <varlistentry id=
"libpq-pgres-nonfatal-error">
3639 <term><literal>PGRES_NONFATAL_ERROR
</literal></term>
3642 A nonfatal error (a notice or warning) occurred.
3647 <varlistentry id=
"libpq-pgres-fatal-error">
3648 <term><literal>PGRES_FATAL_ERROR
</literal></term>
3651 A fatal error occurred.
3656 <varlistentry id=
"libpq-pgres-copy-both">
3657 <term><literal>PGRES_COPY_BOTH
</literal></term>
3660 Copy In/Out (to and from server) data transfer started. This
3661 feature is currently used only for streaming replication,
3662 so this status should not occur in ordinary applications.
3667 <varlistentry id=
"libpq-pgres-single-tuple">
3668 <term><literal>PGRES_SINGLE_TUPLE
</literal></term>
3671 The
<structname>PGresult
</structname> contains a single result tuple
3672 from the current command. This status occurs only when
3673 single-row mode has been selected for the query
3674 (see
<xref linkend=
"libpq-single-row-mode"/>).
3679 <varlistentry id=
"libpq-pgres-tuples-chunk">
3680 <term><literal>PGRES_TUPLES_CHUNK
</literal></term>
3683 The
<structname>PGresult
</structname> contains several result tuples
3684 from the current command. This status occurs only when
3685 chunked mode has been selected for the query
3686 (see
<xref linkend=
"libpq-single-row-mode"/>).
3687 The number of tuples will not exceed the limit passed to
3688 <xref linkend=
"libpq-PQsetChunkedRowsMode"/>.
3693 <varlistentry id=
"libpq-pgres-pipeline-sync">
3694 <term><literal>PGRES_PIPELINE_SYNC
</literal></term>
3697 The
<structname>PGresult
</structname> represents a
3698 synchronization point in pipeline mode, requested by either
3699 <xref linkend=
"libpq-PQpipelineSync"/> or
3700 <xref linkend=
"libpq-PQsendPipelineSync"/>.
3701 This status occurs only when pipeline mode has been selected.
3706 <varlistentry id=
"libpq-pgres-pipeline-aborted">
3707 <term><literal>PGRES_PIPELINE_ABORTED
</literal></term>
3710 The
<structname>PGresult
</structname> represents a pipeline that has
3711 received an error from the server.
<function>PQgetResult
</function>
3712 must be called repeatedly, and each time it will return this status code
3713 until the end of the current pipeline, at which point it will return
3714 <literal>PGRES_PIPELINE_SYNC
</literal> and normal processing can
3722 If the result status is
<literal>PGRES_TUPLES_OK
</literal>,
3723 <literal>PGRES_SINGLE_TUPLE
</literal>, or
3724 <literal>PGRES_TUPLES_CHUNK
</literal>, then
3725 the functions described below can be used to retrieve the rows
3726 returned by the query. Note that a
<command>SELECT
</command>
3727 command that happens to retrieve zero rows still shows
3728 <literal>PGRES_TUPLES_OK
</literal>.
3729 <literal>PGRES_COMMAND_OK
</literal> is for commands that can never
3730 return rows (
<command>INSERT
</command> or
<command>UPDATE
</command>
3731 without a
<literal>RETURNING
</literal> clause,
3732 etc.). A response of
<literal>PGRES_EMPTY_QUERY
</literal> might
3733 indicate a bug in the client software.
3737 A result of status
<symbol>PGRES_NONFATAL_ERROR
</symbol> will
3738 never be returned directly by
<xref linkend=
"libpq-PQexec"/> or other
3739 query execution functions; results of this kind are instead passed
3740 to the notice processor (see
<xref
3741 linkend=
"libpq-notice-processing"/>).
3746 <varlistentry id=
"libpq-PQresStatus">
3747 <term><function>PQresStatus
</function><indexterm><primary>PQresStatus
</primary></indexterm></term>
3751 Converts the enumerated type returned by
3752 <xref linkend=
"libpq-PQresultStatus"/> into a string constant describing the
3753 status code. The caller should not free the result.
3756 char *PQresStatus(ExecStatusType status);
3762 <varlistentry id=
"libpq-PQresultErrorMessage">
3763 <term><function>PQresultErrorMessage
</function><indexterm><primary>PQresultErrorMessage
</primary></indexterm></term>
3767 Returns the error message associated with the command, or an empty string
3768 if there was no error.
3770 char *PQresultErrorMessage(const PGresult *res);
3772 If there was an error, the returned string will include a trailing
3773 newline. The caller should not free the result directly. It will
3774 be freed when the associated
<structname>PGresult
</structname> handle is
3775 passed to
<xref linkend=
"libpq-PQclear"/>.
3779 Immediately following a
<xref linkend=
"libpq-PQexec"/> or
3780 <xref linkend=
"libpq-PQgetResult"/> call,
3781 <xref linkend=
"libpq-PQerrorMessage"/> (on the connection) will return
3782 the same string as
<xref linkend=
"libpq-PQresultErrorMessage"/> (on
3783 the result). However, a
<structname>PGresult
</structname> will
3784 retain its error message until destroyed, whereas the connection's
3785 error message will change when subsequent operations are done.
3786 Use
<xref linkend=
"libpq-PQresultErrorMessage"/> when you want to
3787 know the status associated with a particular
3788 <structname>PGresult
</structname>; use
3789 <xref linkend=
"libpq-PQerrorMessage"/> when you want to know the
3790 status from the latest operation on the connection.
3795 <varlistentry id=
"libpq-PQresultVerboseErrorMessage">
3796 <term><function>PQresultVerboseErrorMessage
</function><indexterm><primary>PQresultVerboseErrorMessage
</primary></indexterm></term>
3800 Returns a reformatted version of the error message associated with
3801 a
<structname>PGresult
</structname> object.
3803 char *PQresultVerboseErrorMessage(const PGresult *res,
3804 PGVerbosity verbosity,
3805 PGContextVisibility show_context);
3807 In some situations a client might wish to obtain a more detailed
3808 version of a previously-reported error.
3809 <xref linkend=
"libpq-PQresultVerboseErrorMessage"/> addresses this need
3810 by computing the message that would have been produced
3811 by
<xref linkend=
"libpq-PQresultErrorMessage"/> if the specified
3812 verbosity settings had been in effect for the connection when the
3813 given
<structname>PGresult
</structname> was generated. If
3814 the
<structname>PGresult
</structname> is not an error result,
3815 <quote>PGresult is not an error result
</quote> is reported instead.
3816 The returned string includes a trailing newline.
3820 Unlike most other functions for extracting data from
3821 a
<structname>PGresult
</structname>, the result of this function is a freshly
3822 allocated string. The caller must free it
3823 using
<function>PQfreemem()
</function> when the string is no longer needed.
3827 A NULL return is possible if there is insufficient memory.
3832 <varlistentry id=
"libpq-PQresultErrorField">
3833 <term><function>PQresultErrorField
</function><indexterm><primary>PQresultErrorField
</primary></indexterm></term>
3836 Returns an individual field of an error report.
3838 char *PQresultErrorField(const PGresult *res, int fieldcode);
3840 <parameter>fieldcode
</parameter> is an error field identifier; see the symbols
3841 listed below.
<symbol>NULL
</symbol> is returned if the
3842 <structname>PGresult
</structname> is not an error or warning result,
3843 or does not include the specified field. Field values will normally
3844 not include a trailing newline. The caller should not free the
3845 result directly. It will be freed when the
3846 associated
<structname>PGresult
</structname> handle is passed to
3847 <xref linkend=
"libpq-PQclear"/>.
3851 The following field codes are available:
3853 <varlistentry id=
"libpq-pg-diag-severity">
3854 <term><symbol>PG_DIAG_SEVERITY
</symbol></term>
3857 The severity; the field contents are
<literal>ERROR
</literal>,
3858 <literal>FATAL
</literal>, or
<literal>PANIC
</literal> (in an error message),
3859 or
<literal>WARNING
</literal>,
<literal>NOTICE
</literal>,
<literal>DEBUG
</literal>,
3860 <literal>INFO
</literal>, or
<literal>LOG
</literal> (in a notice message), or
3861 a localized translation of one of these. Always present.
3866 <varlistentry id=
"libpq-PG-diag-severity-nonlocalized">
3867 <term><symbol>PG_DIAG_SEVERITY_NONLOCALIZED
</symbol></term>
3870 The severity; the field contents are
<literal>ERROR
</literal>,
3871 <literal>FATAL
</literal>, or
<literal>PANIC
</literal> (in an error message),
3872 or
<literal>WARNING
</literal>,
<literal>NOTICE
</literal>,
<literal>DEBUG
</literal>,
3873 <literal>INFO
</literal>, or
<literal>LOG
</literal> (in a notice message).
3874 This is identical to the
<symbol>PG_DIAG_SEVERITY
</symbol> field except
3875 that the contents are never localized. This is present only in
3876 reports generated by
<productname>PostgreSQL
</productname> versions
9.6
3882 <varlistentry id=
"libpq-pg-diag-sqlstate">
3883 <term><symbol>PG_DIAG_SQLSTATE
</symbol><indexterm
3884 ><primary>error codes
</primary><secondary>libpq
</secondary></indexterm></term>
3887 The SQLSTATE code for the error. The SQLSTATE code identifies
3888 the type of error that has occurred; it can be used by
3889 front-end applications to perform specific operations (such
3890 as error handling) in response to a particular database error.
3891 For a list of the possible SQLSTATE codes, see
<xref
3892 linkend=
"errcodes-appendix"/>. This field is not localizable,
3893 and is always present.
3898 <varlistentry id=
"libpq-pg-diag-message-primary">
3899 <term><symbol>PG_DIAG_MESSAGE_PRIMARY
</symbol></term>
3902 The primary human-readable error message (typically one line).
3908 <varlistentry id=
"libpq-pg-diag-message-detail">
3909 <term><symbol>PG_DIAG_MESSAGE_DETAIL
</symbol></term>
3912 Detail: an optional secondary error message carrying more
3913 detail about the problem. Might run to multiple lines.
3918 <varlistentry id=
"libpq-pg-diag-message-hint">
3919 <term><symbol>PG_DIAG_MESSAGE_HINT
</symbol></term>
3922 Hint: an optional suggestion what to do about the problem.
3923 This is intended to differ from detail in that it offers advice
3924 (potentially inappropriate) rather than hard facts. Might
3925 run to multiple lines.
3930 <varlistentry id=
"libpq-pg-diag-statement-position">
3931 <term><symbol>PG_DIAG_STATEMENT_POSITION
</symbol></term>
3934 A string containing a decimal integer indicating an error cursor
3935 position as an index into the original statement string. The
3936 first character has index
1, and positions are measured in
3937 characters not bytes.
3942 <varlistentry id=
"libpq-pg-diag-internal-position">
3943 <term><symbol>PG_DIAG_INTERNAL_POSITION
</symbol></term>
3946 This is defined the same as the
3947 <symbol>PG_DIAG_STATEMENT_POSITION
</symbol> field, but it is used
3948 when the cursor position refers to an internally generated
3949 command rather than the one submitted by the client. The
3950 <symbol>PG_DIAG_INTERNAL_QUERY
</symbol> field will always appear when
3956 <varlistentry id=
"libpq-pg-diag-internal-query">
3957 <term><symbol>PG_DIAG_INTERNAL_QUERY
</symbol></term>
3960 The text of a failed internally-generated command. This could
3961 be, for example, an SQL query issued by a PL/pgSQL function.
3966 <varlistentry id=
"libpq-pg-diag-context">
3967 <term><symbol>PG_DIAG_CONTEXT
</symbol></term>
3970 An indication of the context in which the error occurred.
3971 Presently this includes a call stack traceback of active
3972 procedural language functions and internally-generated queries.
3973 The trace is one entry per line, most recent first.
3978 <varlistentry id=
"libpq-pg-diag-schema-name">
3979 <term><symbol>PG_DIAG_SCHEMA_NAME
</symbol></term>
3982 If the error was associated with a specific database object,
3983 the name of the schema containing that object, if any.
3988 <varlistentry id=
"libpq-pg-diag-table-name">
3989 <term><symbol>PG_DIAG_TABLE_NAME
</symbol></term>
3992 If the error was associated with a specific table, the name of the
3993 table. (Refer to the schema name field for the name of the
3999 <varlistentry id=
"libpq-pg-diag-column-name">
4000 <term><symbol>PG_DIAG_COLUMN_NAME
</symbol></term>
4003 If the error was associated with a specific table column, the name
4004 of the column. (Refer to the schema and table name fields to
4005 identify the table.)
4010 <varlistentry id=
"libpq-pg-diag-datatype-name">
4011 <term><symbol>PG_DIAG_DATATYPE_NAME
</symbol></term>
4014 If the error was associated with a specific data type, the name of
4015 the data type. (Refer to the schema name field for the name of
4016 the data type's schema.)
4021 <varlistentry id=
"libpq-pg-diag-constraint-name">
4022 <term><symbol>PG_DIAG_CONSTRAINT_NAME
</symbol></term>
4025 If the error was associated with a specific constraint, the name
4026 of the constraint. Refer to fields listed above for the
4027 associated table or domain. (For this purpose, indexes are
4028 treated as constraints, even if they weren't created with
4034 <varlistentry id=
"libpq-pg-diag-source-file">
4035 <term><symbol>PG_DIAG_SOURCE_FILE
</symbol></term>
4038 The file name of the source-code location where the error was
4044 <varlistentry id=
"libpq-pg-diag-source-line">
4045 <term><symbol>PG_DIAG_SOURCE_LINE
</symbol></term>
4048 The line number of the source-code location where the error
4054 <varlistentry id=
"libpq-pg-diag-source-function">
4055 <term><symbol>PG_DIAG_SOURCE_FUNCTION
</symbol></term>
4058 The name of the source-code function reporting the error.
4067 The fields for schema name, table name, column name, data type name,
4068 and constraint name are supplied only for a limited number of error
4069 types; see
<xref linkend=
"errcodes-appendix"/>. Do not assume that
4070 the presence of any of these fields guarantees the presence of
4071 another field. Core error sources observe the interrelationships
4072 noted above, but user-defined functions may use these fields in other
4073 ways. In the same vein, do not assume that these fields denote
4074 contemporary objects in the current database.
4079 The client is responsible for formatting displayed information to meet
4080 its needs; in particular it should break long lines as needed.
4081 Newline characters appearing in the error message fields should be
4082 treated as paragraph breaks, not line breaks.
4086 Errors generated internally by
<application>libpq
</application> will
4087 have severity and primary message, but typically no other fields.
4091 Note that error fields are only available from
4092 <structname>PGresult
</structname> objects, not
4093 <structname>PGconn
</structname> objects; there is no
4094 <function>PQerrorField
</function> function.
4099 <varlistentry id=
"libpq-PQclear">
4100 <term><function>PQclear
</function><indexterm><primary>PQclear
</primary></indexterm></term>
4103 Frees the storage associated with a
4104 <structname>PGresult
</structname>. Every command result should be
4105 freed via
<xref linkend=
"libpq-PQclear"/> when it is no longer
4109 void PQclear(PGresult *res);
4112 If the argument is a
<symbol>NULL
</symbol> pointer, no operation is
4117 You can keep a
<structname>PGresult
</structname> object around for
4118 as long as you need it; it does not go away when you issue a new
4119 command, nor even if you close the connection. To get rid of it,
4120 you must call
<xref linkend=
"libpq-PQclear"/>. Failure to do this
4121 will result in memory leaks in your application.
4129 <sect2 id=
"libpq-exec-select-info">
4130 <title>Retrieving Query Result Information
</title>
4133 These functions are used to extract information from a
4134 <structname>PGresult
</structname> object that represents a successful
4135 query result (that is, one that has status
4136 <literal>PGRES_TUPLES_OK
</literal>,
4137 <literal>PGRES_SINGLE_TUPLE
</literal>, or
4138 <literal>PGRES_TUPLES_CHUNK
</literal>).
4139 They can also be used to extract
4140 information from a successful Describe operation: a Describe's result
4141 has all the same column information that actual execution of the query
4142 would provide, but it has zero rows. For objects with other status values,
4143 these functions will act as though the result has zero rows and zero columns.
4147 <varlistentry id=
"libpq-PQntuples">
4148 <term><function>PQntuples
</function><indexterm><primary>PQntuples
</primary></indexterm></term>
4152 Returns the number of rows (tuples) in the query result.
4153 (Note that
<structname>PGresult
</structname> objects are limited to no more
4154 than
<literal>INT_MAX
</literal> rows, so an
<type>int
</type> result is
4158 int PQntuples(const PGresult *res);
4165 <varlistentry id=
"libpq-PQnfields">
4166 <term><function>PQnfields
</function><indexterm><primary>PQnfields
</primary></indexterm></term>
4170 Returns the number of columns (fields) in each row of the query
4174 int PQnfields(const PGresult *res);
4180 <varlistentry id=
"libpq-PQfname">
4181 <term><function>PQfname
</function><indexterm><primary>PQfname
</primary></indexterm></term>
4185 Returns the column name associated with the given column number.
4186 Column numbers start at
0. The caller should not free the result
4187 directly. It will be freed when the associated
4188 <structname>PGresult
</structname> handle is passed to
4189 <xref linkend=
"libpq-PQclear"/>.
4191 char *PQfname(const PGresult *res,
4197 <symbol>NULL
</symbol> is returned if the column number is out of range.
4202 <varlistentry id=
"libpq-PQfnumber">
4203 <term><function>PQfnumber
</function><indexterm><primary>PQfnumber
</primary></indexterm></term>
4207 Returns the column number associated with the given column name.
4209 int PQfnumber(const PGresult *res,
4210 const char *column_name);
4215 -
1 is returned if the given name does not match any column.
4219 The given name is treated like an identifier in an SQL command,
4220 that is, it is downcased unless double-quoted. For example, given
4221 a query result generated from the SQL command:
4223 SELECT
1 AS FOO,
2 AS
"BAR";
4225 we would have the results:
4227 PQfname(res,
0)
<lineannotation>foo
</lineannotation>
4228 PQfname(res,
1)
<lineannotation>BAR
</lineannotation>
4229 PQfnumber(res,
"FOO")
<lineannotation>0</lineannotation>
4230 PQfnumber(res,
"foo")
<lineannotation>0</lineannotation>
4231 PQfnumber(res,
"BAR")
<lineannotation>-
1</lineannotation>
4232 PQfnumber(res,
"\"BAR\
"")
<lineannotation>1</lineannotation>
4238 <varlistentry id=
"libpq-PQftable">
4239 <term><function>PQftable
</function><indexterm><primary>PQftable
</primary></indexterm></term>
4243 Returns the OID of the table from which the given column was
4244 fetched. Column numbers start at
0.
4246 Oid PQftable(const PGresult *res,
4252 <literal>InvalidOid
</literal> is returned if the column number is out of range,
4253 or if the specified column is not a simple reference to a table column.
4254 You can query the system table
<literal>pg_class
</literal> to determine
4255 exactly which table is referenced.
4259 The type
<type>Oid
</type> and the constant
4260 <literal>InvalidOid
</literal> will be defined when you include
4261 the
<application>libpq
</application> header file. They will both
4262 be some integer type.
4267 <varlistentry id=
"libpq-PQftablecol">
4268 <term><function>PQftablecol
</function><indexterm><primary>PQftablecol
</primary></indexterm></term>
4272 Returns the column number (within its table) of the column making
4273 up the specified query result column. Query-result column numbers
4274 start at
0, but table columns have nonzero numbers.
4276 int PQftablecol(const PGresult *res,
4282 Zero is returned if the column number is out of range, or if the
4283 specified column is not a simple reference to a table column.
4288 <varlistentry id=
"libpq-PQfformat">
4289 <term><function>PQfformat
</function><indexterm><primary>PQfformat
</primary></indexterm></term>
4293 Returns the format code indicating the format of the given
4294 column. Column numbers start at
0.
4296 int PQfformat(const PGresult *res,
4302 Format code zero indicates textual data representation, while format
4303 code one indicates binary representation. (Other codes are reserved
4304 for future definition.)
4309 <varlistentry id=
"libpq-PQftype">
4310 <term><function>PQftype
</function><indexterm><primary>PQftype
</primary></indexterm></term>
4314 Returns the data type associated with the given column number.
4315 The integer returned is the internal OID number of the type.
4316 Column numbers start at
0.
4318 Oid PQftype(const PGresult *res,
4324 You can query the system table
<literal>pg_type
</literal> to
4325 obtain the names and properties of the various data types. The
4326 <acronym>OID
</acronym>s of the built-in data types are defined
4327 in the file
<filename>catalog/pg_type_d.h
</filename>
4328 in the
<productname>PostgreSQL
</productname>
4329 installation's
<filename>include
</filename> directory.
4334 <varlistentry id=
"libpq-PQfmod">
4335 <term><function>PQfmod
</function><indexterm><primary>PQfmod
</primary></indexterm></term>
4339 Returns the type modifier of the column associated with the
4340 given column number. Column numbers start at
0.
4342 int PQfmod(const PGresult *res,
4348 The interpretation of modifier values is type-specific; they
4349 typically indicate precision or size limits. The value -
1 is
4350 used to indicate
<quote>no information available
</quote>. Most data
4351 types do not use modifiers, in which case the value is always
4357 <varlistentry id=
"libpq-PQfsize">
4358 <term><function>PQfsize
</function><indexterm><primary>PQfsize
</primary></indexterm></term>
4362 Returns the size in bytes of the column associated with the
4363 given column number. Column numbers start at
0.
4365 int PQfsize(const PGresult *res,
4371 <xref linkend=
"libpq-PQfsize"/> returns the space allocated for this column
4372 in a database row, in other words the size of the server's
4373 internal representation of the data type. (Accordingly, it is
4374 not really very useful to clients.) A negative value indicates
4375 the data type is variable-length.
4380 <varlistentry id=
"libpq-PQbinaryTuples">
4381 <term><function>PQbinaryTuples
</function><indexterm><primary>PQbinaryTuples
</primary></indexterm></term>
4385 Returns
1 if the
<structname>PGresult
</structname> contains binary data
4386 and
0 if it contains text data.
4388 int PQbinaryTuples(const PGresult *res);
4393 This function is deprecated (except for its use in connection with
4394 <command>COPY
</command>), because it is possible for a single
4395 <structname>PGresult
</structname> to contain text data in some columns and
4396 binary data in others.
<xref linkend=
"libpq-PQfformat"/> is preferred.
4397 <xref linkend=
"libpq-PQbinaryTuples"/> returns
1 only if all columns of the
4398 result are binary (format
1).
4403 <varlistentry id=
"libpq-PQgetvalue">
4404 <term><function>PQgetvalue
</function><indexterm><primary>PQgetvalue
</primary></indexterm></term>
4408 Returns a single field value of one row of a
4409 <structname>PGresult
</structname>. Row and column numbers start
4410 at
0. The caller should not free the result directly. It will
4411 be freed when the associated
<structname>PGresult
</structname> handle is
4412 passed to
<xref linkend=
"libpq-PQclear"/>.
4414 char *PQgetvalue(const PGresult *res,
4421 For data in text format, the value returned by
4422 <xref linkend=
"libpq-PQgetvalue"/> is a null-terminated character
4423 string representation of the field value. For data in binary
4424 format, the value is in the binary representation determined by
4425 the data type's
<function>typsend
</function> and
<function>typreceive
</function>
4426 functions. (The value is actually followed by a zero byte in
4427 this case too, but that is not ordinarily useful, since the
4428 value is likely to contain embedded nulls.)
4432 An empty string is returned if the field value is null. See
4433 <xref linkend=
"libpq-PQgetisnull"/> to distinguish null values from
4434 empty-string values.
4438 The pointer returned by
<xref linkend=
"libpq-PQgetvalue"/> points
4439 to storage that is part of the
<structname>PGresult
</structname>
4440 structure. One should not modify the data it points to, and one
4441 must explicitly copy the data into other storage if it is to be
4442 used past the lifetime of the
<structname>PGresult
</structname>
4448 <varlistentry id=
"libpq-PQgetisnull">
4449 <term><function>PQgetisnull
</function><indexterm
4450 ><primary>PQgetisnull
</primary></indexterm><indexterm
4451 ><primary>null value
</primary><secondary sortas=
"libpq">in libpq
</secondary></indexterm></term>
4455 Tests a field for a null value. Row and column numbers start
4458 int PQgetisnull(const PGresult *res,
4465 This function returns
1 if the field is null and
0 if it
4466 contains a non-null value. (Note that
4467 <xref linkend=
"libpq-PQgetvalue"/> will return an empty string,
4468 not a null pointer, for a null field.)
4473 <varlistentry id=
"libpq-PQgetlength">
4474 <term><function>PQgetlength
</function><indexterm><primary>PQgetlength
</primary></indexterm></term>
4478 Returns the actual length of a field value in bytes. Row and
4479 column numbers start at
0.
4481 int PQgetlength(const PGresult *res,
4488 This is the actual data length for the particular data value,
4489 that is, the size of the object pointed to by
4490 <xref linkend=
"libpq-PQgetvalue"/>. For text data format this is
4491 the same as
<function>strlen()
</function>. For binary format this is
4492 essential information. Note that one should
<emphasis>not
</emphasis>
4493 rely on
<xref linkend=
"libpq-PQfsize"/> to obtain the actual data
4499 <varlistentry id=
"libpq-PQnparams">
4500 <term><function>PQnparams
</function><indexterm><primary>PQnparams
</primary></indexterm></term>
4504 Returns the number of parameters of a prepared statement.
4506 int PQnparams(const PGresult *res);
4511 This function is only useful when inspecting the result of
4512 <xref linkend=
"libpq-PQdescribePrepared"/>. For other types of results it
4518 <varlistentry id=
"libpq-PQparamtype">
4519 <term><function>PQparamtype
</function><indexterm><primary>PQparamtype
</primary></indexterm></term>
4523 Returns the data type of the indicated statement parameter.
4524 Parameter numbers start at
0.
4526 Oid PQparamtype(const PGresult *res, int param_number);
4531 This function is only useful when inspecting the result of
4532 <xref linkend=
"libpq-PQdescribePrepared"/>. For other types of results it
4538 <varlistentry id=
"libpq-PQprint">
4539 <term><function>PQprint
</function><indexterm><primary>PQprint
</primary></indexterm></term>
4543 Prints out all the rows and, optionally, the column names to
4544 the specified output stream.
4546 void PQprint(FILE *fout, /* output stream */
4547 const PGresult *res,
4548 const PQprintOpt *po);
4551 pqbool header; /* print output field headings and row count */
4552 pqbool align; /* fill align the fields */
4553 pqbool standard; /* old brain dead format */
4554 pqbool html3; /* output HTML tables */
4555 pqbool expanded; /* expand tables */
4556 pqbool pager; /* use pager for output if needed */
4557 char *fieldSep; /* field separator */
4558 char *tableOpt; /* attributes for HTML table element */
4559 char *caption; /* HTML table caption */
4560 char **fieldName; /* null-terminated array of replacement field names */
4566 This function was formerly used by
<application>psql
</application>
4567 to print query results, but this is no longer the case. Note
4568 that it assumes all the data is in text format.
4575 <sect2 id=
"libpq-exec-nonselect">
4576 <title>Retrieving Other Result Information
</title>
4579 These functions are used to extract other information from
4580 <structname>PGresult
</structname> objects.
4584 <varlistentry id=
"libpq-PQcmdStatus">
4585 <term><function>PQcmdStatus
</function><indexterm><primary>PQcmdStatus
</primary></indexterm></term>
4589 Returns the command status tag from the SQL command that generated
4590 the
<structname>PGresult
</structname>.
4592 char *PQcmdStatus(PGresult *res);
4597 Commonly this is just the name of the command, but it might include
4598 additional data such as the number of rows processed. The caller
4599 should not free the result directly. It will be freed when the
4600 associated
<structname>PGresult
</structname> handle is passed to
4601 <xref linkend=
"libpq-PQclear"/>.
4606 <varlistentry id=
"libpq-PQcmdTuples">
4607 <term><function>PQcmdTuples
</function><indexterm><primary>PQcmdTuples
</primary></indexterm></term>
4611 Returns the number of rows affected by the SQL command.
4613 char *PQcmdTuples(PGresult *res);
4618 This function returns a string containing the number of rows
4619 affected by the
<acronym>SQL
</acronym> statement that generated the
4620 <structname>PGresult
</structname>. This function can only be used following
4621 the execution of a
<command>SELECT
</command>,
<command>CREATE TABLE AS
</command>,
4622 <command>INSERT
</command>,
<command>UPDATE
</command>,
<command>DELETE
</command>,
4623 <command>MERGE
</command>,
<command>MOVE
</command>,
<command>FETCH
</command>,
4624 or
<command>COPY
</command> statement, or an
<command>EXECUTE
</command> of a
4625 prepared query that contains an
<command>INSERT
</command>,
4626 <command>UPDATE
</command>,
<command>DELETE
</command>,
4627 or
<command>MERGE
</command> statement.
4628 If the command that generated the
<structname>PGresult
</structname> was anything
4629 else,
<xref linkend=
"libpq-PQcmdTuples"/> returns an empty string. The caller
4630 should not free the return value directly. It will be freed when
4631 the associated
<structname>PGresult
</structname> handle is passed to
4632 <xref linkend=
"libpq-PQclear"/>.
4637 <varlistentry id=
"libpq-PQoidValue">
4638 <term><function>PQoidValue
</function><indexterm><primary>PQoidValue
</primary></indexterm></term>
4642 Returns the OID
<indexterm><primary>OID
</primary><secondary>in libpq
</secondary></indexterm>
4643 of the inserted row, if the
<acronym>SQL
</acronym> command was an
4644 <command>INSERT
</command> that inserted exactly one row into a table that
4645 has OIDs, or a
<command>EXECUTE
</command> of a prepared query containing
4646 a suitable
<command>INSERT
</command> statement. Otherwise, this function
4647 returns
<literal>InvalidOid
</literal>. This function will also
4648 return
<literal>InvalidOid
</literal> if the table affected by the
4649 <command>INSERT
</command> statement does not contain OIDs.
4651 Oid PQoidValue(const PGresult *res);
4657 <varlistentry id=
"libpq-PQoidStatus">
4658 <term><function>PQoidStatus
</function><indexterm><primary>PQoidStatus
</primary></indexterm></term>
4662 This function is deprecated in favor of
4663 <xref linkend=
"libpq-PQoidValue"/> and is not thread-safe.
4664 It returns a string with the OID of the inserted row, while
4665 <xref linkend=
"libpq-PQoidValue"/> returns the OID value.
4667 char *PQoidStatus(const PGresult *res);
4677 <sect2 id=
"libpq-exec-escape-string">
4678 <title>Escaping Strings for Inclusion in SQL Commands
</title>
4680 <indexterm zone=
"libpq-exec-escape-string">
4681 <primary>escaping strings
</primary>
4682 <secondary>in libpq
</secondary>
4686 <varlistentry id=
"libpq-PQescapeLiteral">
4687 <term><function>PQescapeLiteral
</function><indexterm><primary>PQescapeLiteral
</primary></indexterm></term>
4692 char *PQescapeLiteral(PGconn *conn, const char *str, size_t length);
4697 <xref linkend=
"libpq-PQescapeLiteral"/> escapes a string for
4698 use within an SQL command. This is useful when inserting data
4699 values as literal constants in SQL commands. Certain characters
4700 (such as quotes and backslashes) must be escaped to prevent them
4701 from being interpreted specially by the SQL parser.
4702 <xref linkend=
"libpq-PQescapeLiteral"/> performs this operation.
4706 <xref linkend=
"libpq-PQescapeLiteral"/> returns an escaped version of the
4707 <parameter>str
</parameter> parameter in memory allocated with
4708 <function>malloc()
</function>. This memory should be freed using
4709 <function>PQfreemem()
</function> when the result is no longer needed.
4710 A terminating zero byte is not required, and should not be
4711 counted in
<parameter>length
</parameter>. (If a terminating zero byte is found
4712 before
<parameter>length
</parameter> bytes are processed,
4713 <xref linkend=
"libpq-PQescapeLiteral"/> stops at the zero; the behavior is
4714 thus rather like
<function>strncpy
</function>.) The
4715 return string has all special characters replaced so that they can
4716 be properly processed by the
<productname>PostgreSQL
</productname>
4717 string literal parser. A terminating zero byte is also added. The
4718 single quotes that must surround
<productname>PostgreSQL
</productname>
4719 string literals are included in the result string.
4723 On error,
<xref linkend=
"libpq-PQescapeLiteral"/> returns
<symbol>NULL
</symbol> and a suitable
4724 message is stored in the
<parameter>conn
</parameter> object.
4729 It is especially important to do proper escaping when handling
4730 strings that were received from an untrustworthy source.
4731 Otherwise there is a security risk: you are vulnerable to
4732 <quote>SQL injection
</quote> attacks wherein unwanted SQL commands are
4733 fed to your database.
4738 Note that it is neither necessary nor correct to do escaping when a data
4739 value is passed as a separate parameter in
<xref linkend=
"libpq-PQexecParams"/> or
4740 its sibling routines.
4745 <varlistentry id=
"libpq-PQescapeIdentifier">
4746 <term><function>PQescapeIdentifier
</function><indexterm><primary>PQescapeIdentifier
</primary></indexterm></term>
4751 char *PQescapeIdentifier(PGconn *conn, const char *str, size_t length);
4756 <xref linkend=
"libpq-PQescapeIdentifier"/> escapes a string for
4757 use as an SQL identifier, such as a table, column, or function name.
4758 This is useful when a user-supplied identifier might contain
4759 special characters that would otherwise not be interpreted as part
4760 of the identifier by the SQL parser, or when the identifier might
4761 contain upper case characters whose case should be preserved.
4765 <xref linkend=
"libpq-PQescapeIdentifier"/> returns a version of the
4766 <parameter>str
</parameter> parameter escaped as an SQL identifier
4767 in memory allocated with
<function>malloc()
</function>. This memory must be
4768 freed using
<function>PQfreemem()
</function> when the result is no longer
4769 needed. A terminating zero byte is not required, and should not be
4770 counted in
<parameter>length
</parameter>. (If a terminating zero byte is found
4771 before
<parameter>length
</parameter> bytes are processed,
4772 <xref linkend=
"libpq-PQescapeIdentifier"/> stops at the zero; the behavior is
4773 thus rather like
<function>strncpy
</function>.) The
4774 return string has all special characters replaced so that it
4775 will be properly processed as an SQL identifier. A terminating zero byte
4776 is also added. The return string will also be surrounded by double
4781 On error,
<xref linkend=
"libpq-PQescapeIdentifier"/> returns
<symbol>NULL
</symbol> and a suitable
4782 message is stored in the
<parameter>conn
</parameter> object.
4787 As with string literals, to prevent SQL injection attacks,
4788 SQL identifiers must be escaped when they are received from an
4789 untrustworthy source.
4795 <varlistentry id=
"libpq-PQescapeStringConn">
4796 <term><function>PQescapeStringConn
</function><indexterm><primary>PQescapeStringConn
</primary></indexterm></term>
4801 size_t PQescapeStringConn(PGconn *conn,
4802 char *to, const char *from, size_t length,
4808 <xref linkend=
"libpq-PQescapeStringConn"/> escapes string literals, much like
4809 <xref linkend=
"libpq-PQescapeLiteral"/>. Unlike
<xref linkend=
"libpq-PQescapeLiteral"/>,
4810 the caller is responsible for providing an appropriately sized buffer.
4811 Furthermore,
<xref linkend=
"libpq-PQescapeStringConn"/> does not generate the
4812 single quotes that must surround
<productname>PostgreSQL
</productname> string
4813 literals; they should be provided in the SQL command that the
4814 result is inserted into. The parameter
<parameter>from
</parameter> points to
4815 the first character of the string that is to be escaped, and the
4816 <parameter>length
</parameter> parameter gives the number of bytes in this
4817 string. A terminating zero byte is not required, and should not be
4818 counted in
<parameter>length
</parameter>. (If a terminating zero byte is found
4819 before
<parameter>length
</parameter> bytes are processed,
4820 <xref linkend=
"libpq-PQescapeStringConn"/> stops at the zero; the behavior is
4821 thus rather like
<function>strncpy
</function>.)
<parameter>to
</parameter> shall point
4822 to a buffer that is able to hold at least one more byte than twice
4823 the value of
<parameter>length
</parameter>, otherwise the behavior is undefined.
4824 Behavior is likewise undefined if the
<parameter>to
</parameter> and
4825 <parameter>from
</parameter> strings overlap.
4829 If the
<parameter>error
</parameter> parameter is not
<symbol>NULL
</symbol>, then
4830 <literal>*error
</literal> is set to zero on success, nonzero on error.
4831 Presently the only possible error conditions involve invalid multibyte
4832 encoding in the source string. The output string is still generated
4833 on error, but it can be expected that the server will reject it as
4834 malformed. On error, a suitable message is stored in the
4835 <parameter>conn
</parameter> object, whether or not
<parameter>error
</parameter> is
<symbol>NULL
</symbol>.
4839 <xref linkend=
"libpq-PQescapeStringConn"/> returns the number of bytes written
4840 to
<parameter>to
</parameter>, not including the terminating zero byte.
4845 <varlistentry id=
"libpq-PQescapeString">
4846 <term><function>PQescapeString
</function><indexterm><primary>PQescapeString
</primary></indexterm></term>
4850 <xref linkend=
"libpq-PQescapeString"/> is an older, deprecated version of
4851 <xref linkend=
"libpq-PQescapeStringConn"/>.
4853 size_t PQescapeString (char *to, const char *from, size_t length);
4858 The only difference from
<xref linkend=
"libpq-PQescapeStringConn"/> is that
4859 <xref linkend=
"libpq-PQescapeString"/> does not take
<structname>PGconn
</structname>
4860 or
<parameter>error
</parameter> parameters.
4861 Because of this, it cannot adjust its behavior depending on the
4862 connection properties (such as character encoding) and therefore
4863 <emphasis>it might give the wrong results
</emphasis>. Also, it has no way
4864 to report error conditions.
4868 <xref linkend=
"libpq-PQescapeString"/> can be used safely in
4869 client programs that work with only one
<productname>PostgreSQL
</productname>
4870 connection at a time (in this case it can find out what it needs to
4871 know
<quote>behind the scenes
</quote>). In other contexts it is a security
4872 hazard and should be avoided in favor of
4873 <xref linkend=
"libpq-PQescapeStringConn"/>.
4878 <varlistentry id=
"libpq-PQescapeByteaConn">
4879 <term><function>PQescapeByteaConn
</function><indexterm><primary>PQescapeByteaConn
</primary></indexterm></term>
4883 Escapes binary data for use within an SQL command with the type
4884 <type>bytea
</type>. As with
<xref linkend=
"libpq-PQescapeStringConn"/>,
4885 this is only used when inserting data directly into an SQL command string.
4887 unsigned char *PQescapeByteaConn(PGconn *conn,
4888 const unsigned char *from,
4895 Certain byte values must be escaped when used as part of a
4896 <type>bytea
</type> literal in an
<acronym>SQL
</acronym> statement.
4897 <xref linkend=
"libpq-PQescapeByteaConn"/> escapes bytes using
4898 either hex encoding or backslash escaping. See
<xref
4899 linkend=
"datatype-binary"/> for more information.
4903 The
<parameter>from
</parameter> parameter points to the first
4904 byte of the string that is to be escaped, and the
4905 <parameter>from_length
</parameter> parameter gives the number of
4906 bytes in this binary string. (A terminating zero byte is
4907 neither necessary nor counted.) The
<parameter>to_length
</parameter>
4908 parameter points to a variable that will hold the resultant
4909 escaped string length. This result string length includes the terminating
4910 zero byte of the result.
4914 <xref linkend=
"libpq-PQescapeByteaConn"/> returns an escaped version of the
4915 <parameter>from
</parameter> parameter binary string in memory
4916 allocated with
<function>malloc()
</function>. This memory should be freed using
4917 <function>PQfreemem()
</function> when the result is no longer needed. The
4918 return string has all special characters replaced so that they can
4919 be properly processed by the
<productname>PostgreSQL
</productname>
4920 string literal parser, and the
<type>bytea
</type> input function. A
4921 terminating zero byte is also added. The single quotes that must
4922 surround
<productname>PostgreSQL
</productname> string literals are
4923 not part of the result string.
4927 On error, a null pointer is returned, and a suitable error message
4928 is stored in the
<parameter>conn
</parameter> object. Currently, the only
4929 possible error is insufficient memory for the result string.
4934 <varlistentry id=
"libpq-PQescapeBytea">
4935 <term><function>PQescapeBytea
</function><indexterm><primary>PQescapeBytea
</primary></indexterm></term>
4939 <xref linkend=
"libpq-PQescapeBytea"/> is an older, deprecated version of
4940 <xref linkend=
"libpq-PQescapeByteaConn"/>.
4942 unsigned char *PQescapeBytea(const unsigned char *from,
4949 The only difference from
<xref linkend=
"libpq-PQescapeByteaConn"/> is that
4950 <xref linkend=
"libpq-PQescapeBytea"/> does not take a
<structname>PGconn
</structname>
4951 parameter. Because of this,
<xref linkend=
"libpq-PQescapeBytea"/> can
4952 only be used safely in client programs that use a single
4953 <productname>PostgreSQL
</productname> connection at a time (in this case
4954 it can find out what it needs to know
<quote>behind the
4955 scenes
</quote>). It
<emphasis>might give the wrong results
</emphasis> if
4956 used in programs that use multiple database connections (use
4957 <xref linkend=
"libpq-PQescapeByteaConn"/> in such cases).
4962 <varlistentry id=
"libpq-PQunescapeBytea">
4963 <term><function>PQunescapeBytea
</function><indexterm><primary>PQunescapeBytea
</primary></indexterm></term>
4967 Converts a string representation of binary data into binary data
4968 — the reverse of
<xref linkend=
"libpq-PQescapeBytea"/>. This
4969 is needed when retrieving
<type>bytea
</type> data in text format,
4970 but not when retrieving it in binary format.
4973 unsigned char *PQunescapeBytea(const unsigned char *from, size_t *to_length);
4978 The
<parameter>from
</parameter> parameter points to a string
4979 such as might be returned by
<xref linkend=
"libpq-PQgetvalue"/> when applied
4980 to a
<type>bytea
</type> column.
<xref linkend=
"libpq-PQunescapeBytea"/>
4981 converts this string representation into its binary representation.
4982 It returns a pointer to a buffer allocated with
4983 <function>malloc()
</function>, or
<symbol>NULL
</symbol> on error, and puts the size of
4984 the buffer in
<parameter>to_length
</parameter>. The result must be
4985 freed using
<xref linkend=
"libpq-PQfreemem"/> when it is no longer needed.
4989 This conversion is not exactly the inverse of
4990 <xref linkend=
"libpq-PQescapeBytea"/>, because the string is not expected
4991 to be
<quote>escaped
</quote> when received from
<xref linkend=
"libpq-PQgetvalue"/>.
4992 In particular this means there is no need for string quoting considerations,
4993 and so no need for a
<structname>PGconn
</structname> parameter.
5003 <sect1 id=
"libpq-async">
5004 <title>Asynchronous Command Processing
</title>
5006 <indexterm zone=
"libpq-async">
5007 <primary>nonblocking connection
</primary>
5011 The
<xref linkend=
"libpq-PQexec"/> function is adequate for submitting
5012 commands in normal, synchronous applications. It has a few
5013 deficiencies, however, that can be of importance to some users:
5018 <xref linkend=
"libpq-PQexec"/> waits for the command to be completed.
5019 The application might have other work to do (such as maintaining a
5020 user interface), in which case it won't want to block waiting for
5027 Since the execution of the client application is suspended while it
5028 waits for the result, it is hard for the application to decide that
5029 it would like to try to cancel the ongoing command. (It can be done
5030 from a signal handler, but not otherwise.)
5036 <xref linkend=
"libpq-PQexec"/> can return only one
5037 <structname>PGresult
</structname> structure. If the submitted command
5038 string contains multiple
<acronym>SQL
</acronym> commands, all but
5039 the last
<structname>PGresult
</structname> are discarded by
5040 <xref linkend=
"libpq-PQexec"/>.
5046 <xref linkend=
"libpq-PQexec"/> always collects the command's entire result,
5047 buffering it in a single
<structname>PGresult
</structname>. While
5048 this simplifies error-handling logic for the application, it can be
5049 impractical for results containing many rows.
5056 Applications that do not like these limitations can instead use the
5057 underlying functions that
<xref linkend=
"libpq-PQexec"/> is built from:
5058 <xref linkend=
"libpq-PQsendQuery"/> and
<xref linkend=
"libpq-PQgetResult"/>.
5060 <xref linkend=
"libpq-PQsendQueryParams"/>,
5061 <xref linkend=
"libpq-PQsendPrepare"/>,
5062 <xref linkend=
"libpq-PQsendQueryPrepared"/>,
5063 <xref linkend=
"libpq-PQsendDescribePrepared"/>,
5064 <xref linkend=
"libpq-PQsendDescribePortal"/>,
5065 <xref linkend=
"libpq-PQsendClosePrepared"/>, and
5066 <xref linkend=
"libpq-PQsendClosePortal"/>,
5067 which can be used with
<xref linkend=
"libpq-PQgetResult"/> to duplicate
5068 the functionality of
5069 <xref linkend=
"libpq-PQexecParams"/>,
5070 <xref linkend=
"libpq-PQprepare"/>,
5071 <xref linkend=
"libpq-PQexecPrepared"/>,
5072 <xref linkend=
"libpq-PQdescribePrepared"/>,
5073 <xref linkend=
"libpq-PQdescribePortal"/>
5074 <xref linkend=
"libpq-PQclosePrepared"/>, and
5075 <xref linkend=
"libpq-PQclosePortal"/>
5079 <varlistentry id=
"libpq-PQsendQuery">
5080 <term><function>PQsendQuery
</function><indexterm><primary>PQsendQuery
</primary></indexterm></term>
5084 Submits a command to the server without waiting for the result(s).
5085 1 is returned if the command was successfully dispatched and
0 if
5086 not (in which case, use
<xref linkend=
"libpq-PQerrorMessage"/> to get more
5087 information about the failure).
5089 int PQsendQuery(PGconn *conn, const char *command);
5092 After successfully calling
<xref linkend=
"libpq-PQsendQuery"/>, call
5093 <xref linkend=
"libpq-PQgetResult"/> one or more times to obtain the
5094 results.
<xref linkend=
"libpq-PQsendQuery"/> cannot be called again
5095 (on the same connection) until
<xref linkend=
"libpq-PQgetResult"/>
5096 has returned a null pointer, indicating that the command is done.
5100 In pipeline mode, this function is disallowed.
5105 <varlistentry id=
"libpq-PQsendQueryParams">
5106 <term><function>PQsendQueryParams
</function><indexterm><primary>PQsendQueryParams
</primary></indexterm></term>
5110 Submits a command and separate parameters to the server without
5111 waiting for the result(s).
5113 int PQsendQueryParams(PGconn *conn,
5114 const char *command,
5116 const Oid *paramTypes,
5117 const char * const *paramValues,
5118 const int *paramLengths,
5119 const int *paramFormats,
5123 This is equivalent to
<xref linkend=
"libpq-PQsendQuery"/> except that
5124 query parameters can be specified separately from the query string.
5125 The function's parameters are handled identically to
5126 <xref linkend=
"libpq-PQexecParams"/>. Like
5127 <xref linkend=
"libpq-PQexecParams"/>, it allows only one command in the
5133 <varlistentry id=
"libpq-PQsendPrepare">
5134 <term><function>PQsendPrepare
</function><indexterm><primary>PQsendPrepare
</primary></indexterm></term>
5138 Sends a request to create a prepared statement with the given
5139 parameters, without waiting for completion.
5141 int PQsendPrepare(PGconn *conn,
5142 const char *stmtName,
5145 const Oid *paramTypes);
5148 This is an asynchronous version of
<xref linkend=
"libpq-PQprepare"/>: it
5149 returns
1 if it was able to dispatch the request, and
0 if not.
5150 After a successful call, call
<xref linkend=
"libpq-PQgetResult"/> to
5151 determine whether the server successfully created the prepared
5152 statement. The function's parameters are handled identically to
5153 <xref linkend=
"libpq-PQprepare"/>.
5158 <varlistentry id=
"libpq-PQsendQueryPrepared">
5159 <term><function>PQsendQueryPrepared
</function><indexterm><primary>PQsendQueryPrepared
</primary></indexterm></term>
5163 Sends a request to execute a prepared statement with given
5164 parameters, without waiting for the result(s).
5166 int PQsendQueryPrepared(PGconn *conn,
5167 const char *stmtName,
5169 const char * const *paramValues,
5170 const int *paramLengths,
5171 const int *paramFormats,
5175 This is similar to
<xref linkend=
"libpq-PQsendQueryParams"/>, but
5176 the command to be executed is specified by naming a
5177 previously-prepared statement, instead of giving a query string.
5178 The function's parameters are handled identically to
5179 <xref linkend=
"libpq-PQexecPrepared"/>.
5184 <varlistentry id=
"libpq-PQsendDescribePrepared">
5185 <term><function>PQsendDescribePrepared
</function><indexterm><primary>PQsendDescribePrepared
</primary></indexterm></term>
5189 Submits a request to obtain information about the specified
5190 prepared statement, without waiting for completion.
5192 int PQsendDescribePrepared(PGconn *conn, const char *stmtName);
5195 This is an asynchronous version of
<xref linkend=
"libpq-PQdescribePrepared"/>:
5196 it returns
1 if it was able to dispatch the request, and
0 if not.
5197 After a successful call, call
<xref linkend=
"libpq-PQgetResult"/> to
5198 obtain the results. The function's parameters are handled
5199 identically to
<xref linkend=
"libpq-PQdescribePrepared"/>.
5204 <varlistentry id=
"libpq-PQsendDescribePortal">
5205 <term><function>PQsendDescribePortal
</function><indexterm><primary>PQsendDescribePortal
</primary></indexterm></term>
5209 Submits a request to obtain information about the specified
5210 portal, without waiting for completion.
5212 int PQsendDescribePortal(PGconn *conn, const char *portalName);
5215 This is an asynchronous version of
<xref linkend=
"libpq-PQdescribePortal"/>:
5216 it returns
1 if it was able to dispatch the request, and
0 if not.
5217 After a successful call, call
<xref linkend=
"libpq-PQgetResult"/> to
5218 obtain the results. The function's parameters are handled
5219 identically to
<xref linkend=
"libpq-PQdescribePortal"/>.
5224 <varlistentry id=
"libpq-PQsendClosePrepared">
5225 <term><function>PQsendClosePrepared
</function><indexterm><primary>PQsendClosePrepared
</primary></indexterm></term>
5229 Submits a request to close the specified prepared statement, without
5230 waiting for completion.
5232 int PQsendClosePrepared(PGconn *conn, const char *stmtName);
5235 This is an asynchronous version of
<xref linkend=
"libpq-PQclosePrepared"/>:
5236 it returns
1 if it was able to dispatch the request, and
0 if not.
5237 After a successful call, call
<xref linkend=
"libpq-PQgetResult"/> to
5238 obtain the results. The function's parameters are handled
5239 identically to
<xref linkend=
"libpq-PQclosePrepared"/>.
5244 <varlistentry id=
"libpq-PQsendClosePortal">
5245 <term><function>PQsendClosePortal
</function><indexterm><primary>PQsendClosePortal
</primary></indexterm></term>
5249 Submits a request to close specified portal, without waiting for
5252 int PQsendClosePortal(PGconn *conn, const char *portalName);
5255 This is an asynchronous version of
<xref linkend=
"libpq-PQclosePortal"/>:
5256 it returns
1 if it was able to dispatch the request, and
0 if not.
5257 After a successful call, call
<xref linkend=
"libpq-PQgetResult"/> to
5258 obtain the results. The function's parameters are handled
5259 identically to
<xref linkend=
"libpq-PQclosePortal"/>.
5264 <varlistentry id=
"libpq-PQgetResult">
5265 <term><function>PQgetResult
</function><indexterm><primary>PQgetResult
</primary></indexterm></term>
5269 Waits for the next result from a prior
5270 <xref linkend=
"libpq-PQsendQuery"/>,
5271 <xref linkend=
"libpq-PQsendQueryParams"/>,
5272 <xref linkend=
"libpq-PQsendPrepare"/>,
5273 <xref linkend=
"libpq-PQsendQueryPrepared"/>,
5274 <xref linkend=
"libpq-PQsendDescribePrepared"/>,
5275 <xref linkend=
"libpq-PQsendDescribePortal"/>,
5276 <xref linkend=
"libpq-PQsendClosePrepared"/>,
5277 <xref linkend=
"libpq-PQsendClosePortal"/>,
5278 <xref linkend=
"libpq-PQsendPipelineSync"/>, or
5279 <xref linkend=
"libpq-PQpipelineSync"/>
5280 call, and returns it.
5281 A null pointer is returned when the command is complete and there
5282 will be no more results.
5284 PGresult *PQgetResult(PGconn *conn);
5289 <xref linkend=
"libpq-PQgetResult"/> must be called repeatedly until
5290 it returns a null pointer, indicating that the command is done.
5291 (If called when no command is active,
5292 <xref linkend=
"libpq-PQgetResult"/> will just return a null pointer
5293 at once.) Each non-null result from
5294 <xref linkend=
"libpq-PQgetResult"/> should be processed using the
5295 same
<structname>PGresult
</structname> accessor functions previously
5296 described. Don't forget to free each result object with
5297 <xref linkend=
"libpq-PQclear"/> when done with it. Note that
5298 <xref linkend=
"libpq-PQgetResult"/> will block only if a command is
5299 active and the necessary response data has not yet been read by
5300 <xref linkend=
"libpq-PQconsumeInput"/>.
5304 In pipeline mode,
<function>PQgetResult
</function> will return normally
5305 unless an error occurs; for any subsequent query sent after the one
5306 that caused the error until (and excluding) the next synchronization point,
5307 a special result of type
<literal>PGRES_PIPELINE_ABORTED
</literal> will
5308 be returned, and a null pointer will be returned after it.
5309 When the pipeline synchronization point is reached, a result of type
5310 <literal>PGRES_PIPELINE_SYNC
</literal> will be returned.
5311 The result of the next query after the synchronization point follows
5312 immediately (that is, no null pointer is returned after
5313 the synchronization point.)
5318 Even when
<xref linkend=
"libpq-PQresultStatus"/> indicates a fatal
5319 error,
<xref linkend=
"libpq-PQgetResult"/> should be called until it
5320 returns a null pointer, to allow
<application>libpq
</application> to
5321 process the error information completely.
5330 Using
<xref linkend=
"libpq-PQsendQuery"/> and
5331 <xref linkend=
"libpq-PQgetResult"/> solves one of
5332 <xref linkend=
"libpq-PQexec"/>'s problems: If a command string contains
5333 multiple
<acronym>SQL
</acronym> commands, the results of those commands
5334 can be obtained individually. (This allows a simple form of overlapped
5335 processing, by the way: the client can be handling the results of one
5336 command while the server is still working on later queries in the same
5341 Another frequently-desired feature that can be obtained with
5342 <xref linkend=
"libpq-PQsendQuery"/> and
<xref linkend=
"libpq-PQgetResult"/>
5343 is retrieving large query results a limited number of rows at a time.
5345 in
<xref linkend=
"libpq-single-row-mode"/>.
5349 By itself, calling
<xref linkend=
"libpq-PQgetResult"/>
5350 will still cause the client to block until the server completes the
5351 next
<acronym>SQL
</acronym> command. This can be avoided by proper
5352 use of two more functions:
5355 <varlistentry id=
"libpq-PQconsumeInput">
5356 <term><function>PQconsumeInput
</function><indexterm><primary>PQconsumeInput
</primary></indexterm>
5361 If input is available from the server, consume it.
5363 int PQconsumeInput(PGconn *conn);
5368 <xref linkend=
"libpq-PQconsumeInput"/> normally returns
1 indicating
5369 <quote>no error
</quote>, but returns
0 if there was some kind of
5370 trouble (in which case
<xref linkend=
"libpq-PQerrorMessage"/> can be
5371 consulted). Note that the result does not say whether any input
5372 data was actually collected. After calling
5373 <xref linkend=
"libpq-PQconsumeInput"/>, the application can check
5374 <xref linkend=
"libpq-PQisBusy"/> and/or
5375 <function>PQnotifies
</function> to see if their state has changed.
5379 <xref linkend=
"libpq-PQconsumeInput"/> can be called even if the
5380 application is not prepared to deal with a result or notification
5381 just yet. The function will read available data and save it in
5382 a buffer, thereby causing a
<function>select()
</function>
5383 read-ready indication to go away. The application can thus use
5384 <xref linkend=
"libpq-PQconsumeInput"/> to clear the
5385 <function>select()
</function> condition immediately, and then
5386 examine the results at leisure.
5391 <varlistentry id=
"libpq-PQisBusy">
5392 <term><function>PQisBusy
</function><indexterm><primary>PQisBusy
</primary></indexterm></term>
5396 Returns
1 if a command is busy, that is,
5397 <xref linkend=
"libpq-PQgetResult"/> would block waiting for input.
5398 A
0 return indicates that
<xref linkend=
"libpq-PQgetResult"/> can be
5399 called with assurance of not blocking.
5401 int PQisBusy(PGconn *conn);
5406 <xref linkend=
"libpq-PQisBusy"/> will not itself attempt to read data
5407 from the server; therefore
<xref linkend=
"libpq-PQconsumeInput"/>
5408 must be invoked first, or the busy state will never end.
5416 A typical application using these functions will have a main loop that
5417 uses
<function>select()
</function> or
<function>poll()
</function> to wait for
5418 all the conditions that it must respond to. One of the conditions
5419 will be input available from the server, which in terms of
5420 <function>select()
</function> means readable data on the file
5421 descriptor identified by
<xref linkend=
"libpq-PQsocket"/>. When the main
5422 loop detects input ready, it should call
5423 <xref linkend=
"libpq-PQconsumeInput"/> to read the input. It can then
5424 call
<xref linkend=
"libpq-PQisBusy"/>, followed by
5425 <xref linkend=
"libpq-PQgetResult"/> if
<xref linkend=
"libpq-PQisBusy"/>
5426 returns false (
0). It can also call
<function>PQnotifies
</function>
5427 to detect
<command>NOTIFY
</command> messages (see
<xref
5428 linkend=
"libpq-notify"/>).
5433 <xref linkend=
"libpq-PQsendQuery"/>/
<xref linkend=
"libpq-PQgetResult"/>
5434 can also attempt to cancel a command that is still being processed
5435 by the server; see
<xref linkend=
"libpq-cancel"/>. But regardless of
5436 the return value of
<xref linkend=
"libpq-PQcancelBlocking"/>, the application
5437 must continue with the normal result-reading sequence using
5438 <xref linkend=
"libpq-PQgetResult"/>. A successful cancellation will
5439 simply cause the command to terminate sooner than it would have
5444 By using the functions described above, it is possible to avoid
5445 blocking while waiting for input from the database server. However,
5446 it is still possible that the application will block waiting to send
5447 output to the server. This is relatively uncommon but can happen if
5448 very long SQL commands or data values are sent. (It is much more
5449 probable if the application sends data via
<command>COPY IN
</command>,
5450 however.) To prevent this possibility and achieve completely
5451 nonblocking database operation, the following additional functions
5455 <varlistentry id=
"libpq-PQsetnonblocking">
5456 <term><function>PQsetnonblocking
</function><indexterm><primary>PQsetnonblocking
</primary></indexterm></term>
5460 Sets the nonblocking status of the connection.
5462 int PQsetnonblocking(PGconn *conn, int arg);
5467 Sets the state of the connection to nonblocking if
5468 <parameter>arg
</parameter> is
1, or blocking if
5469 <parameter>arg
</parameter> is
0. Returns
0 if OK, -
1 if error.
5473 In the nonblocking state, successful calls to
5474 <xref linkend=
"libpq-PQsendQuery"/>,
<xref linkend=
"libpq-PQputline"/>,
5475 <xref linkend=
"libpq-PQputnbytes"/>,
<xref linkend=
"libpq-PQputCopyData"/>,
5476 and
<xref linkend=
"libpq-PQendcopy"/> will not block; their changes
5477 are stored in the local output buffer until they are flushed.
5478 Unsuccessful calls will return an error and must be retried.
5482 Note that
<xref linkend=
"libpq-PQexec"/> does not honor nonblocking
5483 mode; if it is called, it will act in blocking fashion anyway.
5488 <varlistentry id=
"libpq-PQisnonblocking">
5489 <term><function>PQisnonblocking
</function><indexterm><primary>PQisnonblocking
</primary></indexterm></term>
5493 Returns the blocking status of the database connection.
5495 int PQisnonblocking(const PGconn *conn);
5500 Returns
1 if the connection is set to nonblocking mode and
0 if
5506 <varlistentry id=
"libpq-PQflush">
5507 <term><function>PQflush
</function><indexterm><primary>PQflush
</primary></indexterm></term>
5511 Attempts to flush any queued output data to the server. Returns
5512 0 if successful (or if the send queue is empty), -
1 if it failed
5513 for some reason, or
1 if it was unable to send all the data in
5514 the send queue yet (this case can only occur if the connection
5517 int PQflush(PGconn *conn);
5526 After sending any command or data on a nonblocking connection, call
5527 <xref linkend=
"libpq-PQflush"/>. If it returns
1, wait for the socket
5528 to become read- or write-ready. If it becomes write-ready, call
5529 <xref linkend=
"libpq-PQflush"/> again. If it becomes read-ready, call
5530 <xref linkend=
"libpq-PQconsumeInput"/>, then call
5531 <xref linkend=
"libpq-PQflush"/> again. Repeat until
5532 <xref linkend=
"libpq-PQflush"/> returns
0. (It is necessary to check for
5533 read-ready and drain the input with
<xref linkend=
"libpq-PQconsumeInput"/>,
5534 because the server can block trying to send us data, e.g., NOTICE
5535 messages, and won't read our data until we read its.) Once
5536 <xref linkend=
"libpq-PQflush"/> returns
0, wait for the socket to be
5537 read-ready and then read the response as described above.
5542 <sect1 id=
"libpq-pipeline-mode">
5543 <title>Pipeline Mode
</title>
5545 <indexterm zone=
"libpq-pipeline-mode">
5546 <primary>libpq
</primary>
5547 <secondary>pipeline mode
</secondary>
5550 <indexterm zone=
"libpq-pipeline-mode">
5551 <primary>pipelining
</primary>
5552 <secondary>in libpq
</secondary>
5555 <indexterm zone=
"libpq-pipeline-mode">
5556 <primary>batch mode
</primary>
5557 <secondary>in libpq
</secondary>
5561 <application>libpq
</application> pipeline mode allows applications to
5562 send a query without having to read the result of the previously
5563 sent query. Taking advantage of the pipeline mode, a client will wait
5564 less for the server, since multiple queries/results can be
5565 sent/received in a single network transaction.
5569 While pipeline mode provides a significant performance boost, writing
5570 clients using the pipeline mode is more complex because it involves
5571 managing a queue of pending queries and finding which result
5572 corresponds to which query in the queue.
5576 Pipeline mode also generally consumes more memory on both the client and server,
5577 though careful and aggressive management of the send/receive queue can mitigate
5578 this. This applies whether or not the connection is in blocking or non-blocking
5583 While
<application>libpq
</application>'s pipeline API was introduced in
5584 <productname>PostgreSQL
</productname> 14, it is a client-side feature
5585 which doesn't require special server support and works on any server
5586 that supports the v3 extended query protocol. For more information see
5587 <xref linkend=
"protocol-flow-pipelining"/>.
5590 <sect2 id=
"libpq-pipeline-using">
5591 <title>Using Pipeline Mode
</title>
5594 To issue pipelines, the application must switch the connection
5596 which is done with
<xref linkend=
"libpq-PQenterPipelineMode"/>.
5597 <xref linkend=
"libpq-PQpipelineStatus"/> can be used
5598 to test whether pipeline mode is active.
5599 In pipeline mode, only
<link linkend=
"libpq-async">asynchronous operations
</link>
5600 that utilize the extended query protocol
5601 are permitted, command strings containing multiple SQL commands are
5602 disallowed, and so is
<literal>COPY
</literal>.
5603 Using synchronous command execution functions
5604 such as
<function>PQfn
</function>,
5605 <function>PQexec
</function>,
5606 <function>PQexecParams
</function>,
5607 <function>PQprepare
</function>,
5608 <function>PQexecPrepared
</function>,
5609 <function>PQdescribePrepared
</function>,
5610 <function>PQdescribePortal
</function>,
5611 <function>PQclosePrepared
</function>,
5612 <function>PQclosePortal
</function>,
5613 is an error condition.
5614 <function>PQsendQuery
</function> is
5615 also disallowed, because it uses the simple query protocol.
5616 Once all dispatched commands have had their results processed, and
5617 the end pipeline result has been consumed, the application may return
5618 to non-pipelined mode with
<xref linkend=
"libpq-PQexitPipelineMode"/>.
5623 It is best to use pipeline mode with
<application>libpq
</application> in
5624 <link linkend=
"libpq-PQsetnonblocking">non-blocking mode
</link>. If used
5625 in blocking mode it is possible for a client/server deadlock to occur.
5628 The client will block trying to send queries to the server, but the
5629 server will block trying to send results to the client from queries
5630 it has already processed. This only occurs when the client sends
5631 enough queries to fill both its output buffer and the server's receive
5632 buffer before it switches to processing input from the server,
5633 but it's hard to predict exactly when that will happen.
5639 <sect3 id=
"libpq-pipeline-sending">
5640 <title>Issuing Queries
</title>
5643 After entering pipeline mode, the application dispatches requests using
5644 <xref linkend=
"libpq-PQsendQueryParams"/>
5645 or its prepared-query sibling
5646 <xref linkend=
"libpq-PQsendQueryPrepared"/>.
5647 These requests are queued on the client-side until flushed to the server;
5648 this occurs when
<xref linkend=
"libpq-PQpipelineSync"/> is used to
5649 establish a synchronization point in the pipeline,
5650 or when
<xref linkend=
"libpq-PQflush"/> is called.
5651 The functions
<xref linkend=
"libpq-PQsendPrepare"/>,
5652 <xref linkend=
"libpq-PQsendDescribePrepared"/>,
5653 <xref linkend=
"libpq-PQsendDescribePortal"/>,
5654 <xref linkend=
"libpq-PQsendClosePrepared"/>, and
5655 <xref linkend=
"libpq-PQsendClosePortal"/> also work in pipeline mode.
5656 Result processing is described below.
5660 The server executes statements, and returns results, in the order the
5661 client sends them. The server will begin executing the commands in the
5662 pipeline immediately, not waiting for the end of the pipeline.
5663 Note that results are buffered on the server side; the server flushes
5664 that buffer when a synchronization point is established with either
5665 <function>PQpipelineSync
</function> or
5666 <function>PQsendPipelineSync
</function>, or when
5667 <function>PQsendFlushRequest
</function> is called.
5668 If any statement encounters an error, the server aborts the current
5669 transaction and does not execute any subsequent command in the queue
5670 until the next synchronization point;
5671 a
<literal>PGRES_PIPELINE_ABORTED
</literal> result is produced for
5673 (This remains true even if the commands in the pipeline would rollback
5675 Query processing resumes after the synchronization point.
5679 It's fine for one operation to depend on the results of a
5680 prior one; for example, one query may define a table that the next
5681 query in the same pipeline uses. Similarly, an application may
5682 create a named prepared statement and execute it with later
5683 statements in the same pipeline.
5687 <sect3 id=
"libpq-pipeline-results">
5688 <title>Processing Results
</title>
5691 To process the result of one query in a pipeline, the application calls
5692 <function>PQgetResult
</function> repeatedly and handles each result
5693 until
<function>PQgetResult
</function> returns null.
5694 The result from the next query in the pipeline may then be retrieved using
5695 <function>PQgetResult
</function> again and the cycle repeated.
5696 The application handles individual statement results as normal.
5697 When the results of all the queries in the pipeline have been
5698 returned,
<function>PQgetResult
</function> returns a result
5699 containing the status value
<literal>PGRES_PIPELINE_SYNC
</literal>
5703 The client may choose to defer result processing until the complete
5704 pipeline has been sent, or interleave that with sending further
5705 queries in the pipeline; see
<xref linkend=
"libpq-pipeline-interleave"/>.
5709 <function>PQgetResult
</function> behaves the same as for normal
5710 asynchronous processing except that it may contain the new
5711 <type>PGresult
</type> types
<literal>PGRES_PIPELINE_SYNC
</literal>
5712 and
<literal>PGRES_PIPELINE_ABORTED
</literal>.
5713 <literal>PGRES_PIPELINE_SYNC
</literal> is reported exactly once for each
5714 <function>PQpipelineSync
</function> or
5715 <function>PQsendPipelineSync
</function> at the corresponding point
5717 <literal>PGRES_PIPELINE_ABORTED
</literal> is emitted in place of a normal
5718 query result for the first error and all subsequent results
5719 until the next
<literal>PGRES_PIPELINE_SYNC
</literal>;
5720 see
<xref linkend=
"libpq-pipeline-errors"/>.
5724 <function>PQisBusy
</function>,
<function>PQconsumeInput
</function>, etc
5725 operate as normal when processing pipeline results. In particular,
5726 a call to
<function>PQisBusy
</function> in the middle of a pipeline
5727 returns
0 if the results for all the queries issued so far have been
5732 <application>libpq
</application> does not provide any information to the
5733 application about the query currently being processed (except that
5734 <function>PQgetResult
</function> returns null to indicate that we start
5735 returning the results of next query). The application must keep track
5736 of the order in which it sent queries, to associate them with their
5737 corresponding results.
5738 Applications will typically use a state machine or a FIFO queue for this.
5743 <sect3 id=
"libpq-pipeline-errors">
5744 <title>Error Handling
</title>
5747 From the client's perspective, after
<function>PQresultStatus
</function>
5748 returns
<literal>PGRES_FATAL_ERROR
</literal>,
5749 the pipeline is flagged as aborted.
5750 <function>PQresultStatus
</function> will report a
5751 <literal>PGRES_PIPELINE_ABORTED
</literal> result for each remaining queued
5752 operation in an aborted pipeline. The result for
5753 <function>PQpipelineSync
</function> or
5754 <function>PQsendPipelineSync
</function> is reported as
5755 <literal>PGRES_PIPELINE_SYNC
</literal> to signal the end of the aborted pipeline
5756 and resumption of normal result processing.
5760 The client
<emphasis>must
</emphasis> process results with
5761 <function>PQgetResult
</function> during error recovery.
5765 If the pipeline used an implicit transaction, then operations that have
5766 already executed are rolled back and operations that were queued to follow
5767 the failed operation are skipped entirely. The same behavior holds if the
5768 pipeline starts and commits a single explicit transaction (i.e. the first
5769 statement is
<literal>BEGIN
</literal> and the last is
5770 <literal>COMMIT
</literal>) except that the session remains in an aborted
5771 transaction state at the end of the pipeline. If a pipeline contains
5772 <emphasis>multiple explicit transactions
</emphasis>, all transactions that
5773 committed prior to the error remain committed, the currently in-progress
5774 transaction is aborted, and all subsequent operations are skipped completely,
5775 including subsequent transactions. If a pipeline synchronization point
5776 occurs with an explicit transaction block in aborted state, the next pipeline
5777 will become aborted immediately unless the next command puts the transaction
5778 in normal mode with
<command>ROLLBACK
</command>.
5783 The client must not assume that work is committed when it
5784 <emphasis>sends
</emphasis> a
<literal>COMMIT
</literal> — only when the
5785 corresponding result is received to confirm the commit is complete.
5786 Because errors arrive asynchronously, the application needs to be able to
5787 restart from the last
<emphasis>received
</emphasis> committed change and
5788 resend work done after that point if something goes wrong.
5793 <sect3 id=
"libpq-pipeline-interleave">
5794 <title>Interleaving Result Processing and Query Dispatch
</title>
5797 To avoid deadlocks on large pipelines the client should be structured
5798 around a non-blocking event loop using operating system facilities
5799 such as
<function>select
</function>,
<function>poll
</function>,
5800 <function>WaitForMultipleObjectEx
</function>, etc.
5804 The client application should generally maintain a queue of work
5805 remaining to be dispatched and a queue of work that has been dispatched
5806 but not yet had its results processed. When the socket is writable
5807 it should dispatch more work. When the socket is readable it should
5808 read results and process them, matching them up to the next entry in
5809 its corresponding results queue. Based on available memory, results from the
5810 socket should be read frequently: there's no need to wait until the
5811 pipeline end to read the results. Pipelines should be scoped to logical
5812 units of work, usually (but not necessarily) one transaction per pipeline.
5813 There's no need to exit pipeline mode and re-enter it between pipelines,
5814 or to wait for one pipeline to finish before sending the next.
5818 An example using
<function>select()
</function> and a simple state
5819 machine to track sent and received work is in
5820 <filename>src/test/modules/libpq_pipeline/libpq_pipeline.c
</filename>
5821 in the PostgreSQL source distribution.
5826 <sect2 id=
"libpq-pipeline-functions">
5827 <title>Functions Associated with Pipeline Mode
</title>
5831 <varlistentry id=
"libpq-PQpipelineStatus">
5832 <term><function>PQpipelineStatus
</function><indexterm><primary>PQpipelineStatus
</primary></indexterm></term>
5836 Returns the current pipeline mode status of the
5837 <application>libpq
</application> connection.
5839 PGpipelineStatus PQpipelineStatus(const PGconn *conn);
5844 <function>PQpipelineStatus
</function> can return one of the following values:
5849 <literal>PQ_PIPELINE_ON
</literal>
5853 The
<application>libpq
</application> connection is in
5861 <literal>PQ_PIPELINE_OFF
</literal>
5865 The
<application>libpq
</application> connection is
5866 <emphasis>not
</emphasis> in pipeline mode.
5873 <literal>PQ_PIPELINE_ABORTED
</literal>
5877 The
<application>libpq
</application> connection is in pipeline
5878 mode and an error occurred while processing the current pipeline.
5879 The aborted flag is cleared when
<function>PQgetResult
</function>
5880 returns a result of type
<literal>PGRES_PIPELINE_SYNC
</literal>.
5890 <varlistentry id=
"libpq-PQenterPipelineMode">
5891 <term><function>PQenterPipelineMode
</function><indexterm><primary>PQenterPipelineMode
</primary></indexterm></term>
5895 Causes a connection to enter pipeline mode if it is currently idle or
5896 already in pipeline mode.
5899 int PQenterPipelineMode(PGconn *conn);
5904 Returns
1 for success.
5905 Returns
0 and has no effect if the connection is not currently
5906 idle, i.e., it has a result ready, or it is waiting for more
5907 input from the server, etc.
5908 This function does not actually send anything to the server,
5909 it just changes the
<application>libpq
</application> connection
5915 <varlistentry id=
"libpq-PQexitPipelineMode">
5916 <term><function>PQexitPipelineMode
</function><indexterm><primary>PQexitPipelineMode
</primary></indexterm></term>
5920 Causes a connection to exit pipeline mode if it is currently in pipeline mode
5921 with an empty queue and no pending results.
5923 int PQexitPipelineMode(PGconn *conn);
5927 Returns
1 for success. Returns
1 and takes no action if not in
5928 pipeline mode. If the current statement isn't finished processing,
5929 or
<function>PQgetResult
</function> has not been called to collect
5930 results from all previously sent query, returns
0 (in which case,
5931 use
<xref linkend=
"libpq-PQerrorMessage"/> to get more information
5937 <varlistentry id=
"libpq-PQpipelineSync">
5938 <term><function>PQpipelineSync
</function><indexterm><primary>PQpipelineSync
</primary></indexterm></term>
5942 Marks a synchronization point in a pipeline by sending a
5943 <link linkend=
"protocol-flow-ext-query">sync message
</link>
5944 and flushing the send buffer. This serves as
5945 the delimiter of an implicit transaction and an error recovery
5946 point; see
<xref linkend=
"libpq-pipeline-errors"/>.
5949 int PQpipelineSync(PGconn *conn);
5953 Returns
1 for success. Returns
0 if the connection is not in
5954 pipeline mode or sending a
5955 <link linkend=
"protocol-flow-ext-query">sync message
</link>
5961 <varlistentry id=
"libpq-PQsendPipelineSync">
5962 <term><function>PQsendPipelineSync
</function><indexterm><primary>PQsendPipelineSync
</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 without flushing the send buffer. This serves as
5969 the delimiter of an implicit transaction and an error recovery
5970 point; see
<xref linkend=
"libpq-pipeline-errors"/>.
5973 int PQsendPipelineSync(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>
5981 Note that the message is not itself flushed to the server automatically;
5982 use
<function>PQflush
</function> if necessary.
5987 <varlistentry id=
"libpq-PQsendFlushRequest">
5988 <term><function>PQsendFlushRequest
</function><indexterm><primary>PQsendFlushRequest
</primary></indexterm></term>
5992 Sends a request for the server to flush its output buffer.
5994 int PQsendFlushRequest(PGconn *conn);
5999 Returns
1 for success. Returns
0 on any failure.
6002 The server flushes its output buffer automatically as a result of
6003 <function>PQpipelineSync
</function> being called, or
6004 on any request when not in pipeline mode; this function is useful
6005 to cause the server to flush its output buffer in pipeline mode
6006 without establishing a synchronization point.
6007 Note that the request is not itself flushed to the server automatically;
6008 use
<function>PQflush
</function> if necessary.
6015 <sect2 id=
"libpq-pipeline-tips">
6016 <title>When to Use Pipeline Mode
</title>
6019 Much like asynchronous query mode, there is no meaningful performance
6020 overhead when using pipeline mode. It increases client application complexity,
6021 and extra caution is required to prevent client/server deadlocks, but
6022 pipeline mode can offer considerable performance improvements, in exchange for
6023 increased memory usage from leaving state around longer.
6027 Pipeline mode is most useful when the server is distant, i.e., network latency
6028 (
<quote>ping time
</quote>) is high, and also when many small operations
6029 are being performed in rapid succession. There is usually less benefit
6030 in using pipelined commands when each query takes many multiples of the client/server
6031 round-trip time to execute. A
100-statement operation run on a server
6032 300 ms round-trip-time away would take
30 seconds in network latency alone
6033 without pipelining; with pipelining it may spend as little as
0.3 s waiting for
6034 results from the server.
6038 Use pipelined commands when your application does lots of small
6039 <literal>INSERT
</literal>,
<literal>UPDATE
</literal> and
6040 <literal>DELETE
</literal> operations that can't easily be transformed
6041 into operations on sets, or into a
<literal>COPY
</literal> operation.
6045 Pipeline mode is not useful when information from one operation is required by
6046 the client to produce the next operation. In such cases, the client
6047 would have to introduce a synchronization point and wait for a full client/server
6048 round-trip to get the results it needs. However, it's often possible to
6049 adjust the client design to exchange the required information server-side.
6050 Read-modify-write cycles are especially good candidates; for example:
6053 SELECT x FROM mytable WHERE id =
42 FOR UPDATE;
6055 -- client adds
1 to x:
6056 UPDATE mytable SET x =
3 WHERE id =
42;
6059 could be much more efficiently done with:
6061 UPDATE mytable SET x = x +
1 WHERE id =
42;
6066 Pipelining is less useful, and more complex, when a single pipeline contains
6067 multiple transactions (see
<xref linkend=
"libpq-pipeline-errors"/>).
6072 <!-- keep this not-too-apropos sect1 ID for stability of doc URLs -->
6073 <sect1 id=
"libpq-single-row-mode">
6074 <title>Retrieving Query Results in Chunks
</title>
6076 <indexterm zone=
"libpq-single-row-mode">
6077 <primary>libpq
</primary>
6078 <secondary>single-row mode
</secondary>
6081 <indexterm zone=
"libpq-single-row-mode">
6082 <primary>libpq
</primary>
6083 <secondary>chunked mode
</secondary>
6087 Ordinarily,
<application>libpq
</application> collects an SQL command's
6088 entire result and returns it to the application as a single
6089 <structname>PGresult
</structname>. This can be unworkable for commands
6090 that return a large number of rows. For such cases, applications can use
6091 <xref linkend=
"libpq-PQsendQuery"/> and
<xref linkend=
"libpq-PQgetResult"/> in
6092 <firstterm>single-row mode
</firstterm> or
<firstterm>chunked
6093 mode
</firstterm>. In these modes, result row(s) are returned to the
6094 application as they are received from the server, one at a time for
6095 single-row mode or in groups for chunked mode.
6099 To enter one of these modes, call
<xref linkend=
"libpq-PQsetSingleRowMode"/>
6100 or
<xref linkend=
"libpq-PQsetChunkedRowsMode"/>
6101 immediately after a successful call of
<xref linkend=
"libpq-PQsendQuery"/>
6102 (or a sibling function). This mode selection is effective only for the
6103 currently executing query. Then call
<xref linkend=
"libpq-PQgetResult"/>
6104 repeatedly, until it returns null, as documented in
<xref
6105 linkend=
"libpq-async"/>. If the query returns any rows, they are returned
6106 as one or more
<structname>PGresult
</structname> objects, which look like
6107 normal query results except for having status code
6108 <literal>PGRES_SINGLE_TUPLE
</literal> for single-row mode or
6109 <literal>PGRES_TUPLES_CHUNK
</literal> for chunked mode, instead of
6110 <literal>PGRES_TUPLES_OK
</literal>. There is exactly one result row in
6111 each
<literal>PGRES_SINGLE_TUPLE
</literal> object, while
6112 a
<literal>PGRES_TUPLES_CHUNK
</literal> object contains at least one
6113 row but not more than the specified number of rows per chunk.
6114 After the last row, or immediately if
6115 the query returns zero rows, a zero-row object with status
6116 <literal>PGRES_TUPLES_OK
</literal> is returned; this is the signal that no
6117 more rows will arrive. (But note that it is still necessary to continue
6118 calling
<xref linkend=
"libpq-PQgetResult"/> until it returns null.) All of
6119 these
<structname>PGresult
</structname> objects will contain the same row
6120 description data (column names, types, etc.) that an ordinary
6121 <structname>PGresult
</structname> object for the query would have.
6122 Each object should be freed with
<xref linkend=
"libpq-PQclear"/> as usual.
6126 When using pipeline mode, single-row or chunked mode needs to be
6127 activated for each query in the pipeline before retrieving results for
6128 that query with
<function>PQgetResult
</function>.
6129 See
<xref linkend=
"libpq-pipeline-mode"/> for more information.
6134 <varlistentry id=
"libpq-PQsetSingleRowMode">
6135 <term><function>PQsetSingleRowMode
</function><indexterm><primary>PQsetSingleRowMode
</primary></indexterm></term>
6139 Select single-row mode for the currently-executing query.
6142 int PQsetSingleRowMode(PGconn *conn);
6147 This function can only be called immediately after
6148 <xref linkend=
"libpq-PQsendQuery"/> or one of its sibling functions,
6149 before any other operation on the connection such as
6150 <xref linkend=
"libpq-PQconsumeInput"/> or
6151 <xref linkend=
"libpq-PQgetResult"/>. If called at the correct time,
6152 the function activates single-row mode for the current query and
6153 returns
1. Otherwise the mode stays unchanged and the function
6154 returns
0. In any case, the mode reverts to normal after
6155 completion of the current query.
6160 <varlistentry id=
"libpq-PQsetChunkedRowsMode">
6161 <term><function>PQsetChunkedRowsMode
</function><indexterm><primary>PQsetChunkedRowsMode
</primary></indexterm></term>
6165 Select chunked mode for the currently-executing query.
6168 int PQsetChunkedRowsMode(PGconn *conn, int chunkSize);
6173 This function is similar to
6174 <xref linkend=
"libpq-PQsetSingleRowMode"/>, except that it
6175 specifies retrieval of up to
<replaceable>chunkSize
</replaceable> rows
6176 per
<structname>PGresult
</structname>, not necessarily just one row.
6177 This function can only be called immediately after
6178 <xref linkend=
"libpq-PQsendQuery"/> or one of its sibling functions,
6179 before any other operation on the connection such as
6180 <xref linkend=
"libpq-PQconsumeInput"/> or
6181 <xref linkend=
"libpq-PQgetResult"/>. If called at the correct time,
6182 the function activates chunked mode for the current query and
6183 returns
1. Otherwise the mode stays unchanged and the function
6184 returns
0. In any case, the mode reverts to normal after
6185 completion of the current query.
6194 While processing a query, the server may return some rows and then
6195 encounter an error, causing the query to be aborted. Ordinarily,
6196 <application>libpq
</application> discards any such rows and reports only the
6197 error. But in single-row or chunked mode, some rows may have already
6198 been returned to the application. Hence, the application will see some
6199 <literal>PGRES_SINGLE_TUPLE
</literal> or
<literal>PGRES_TUPLES_CHUNK
</literal>
6200 <structname>PGresult
</structname>
6201 objects followed by a
<literal>PGRES_FATAL_ERROR
</literal> object. For
6202 proper transactional behavior, the application must be designed to
6203 discard or undo whatever has been done with the previously-processed
6204 rows, if the query ultimately fails.
6210 <sect1 id=
"libpq-cancel">
6211 <title>Canceling Queries in Progress
</title>
6213 <indexterm zone=
"libpq-cancel">
6214 <primary>canceling SQL queries
</primary>
6216 <indexterm zone=
"libpq-cancel">
6217 <primary>query cancellation
</primary>
6220 <sect2 id=
"libpq-cancel-functions">
6221 <title>Functions for Sending Cancel Requests
</title>
6223 <varlistentry id=
"libpq-PQcancelCreate">
6224 <term><function>PQcancelCreate
</function><indexterm><primary>PQcancelCreate
</primary></indexterm></term>
6228 Prepares a connection over which a cancel request can be sent.
6230 PGcancelConn *PQcancelCreate(PGconn *conn);
6235 <xref linkend=
"libpq-PQcancelCreate"/> creates a
6236 <structname>PGcancelConn
</structname><indexterm><primary>PGcancelConn
</primary></indexterm>
6237 object, but it won't instantly start sending a cancel request over this
6238 connection. A cancel request can be sent over this connection in a
6239 blocking manner using
<xref linkend=
"libpq-PQcancelBlocking"/> and in a
6240 non-blocking manner using
<xref linkend=
"libpq-PQcancelStart"/>.
6241 The return value can be passed to
<xref linkend=
"libpq-PQcancelStatus"/>
6242 to check if the
<structname>PGcancelConn
</structname> object was
6243 created successfully. The
<structname>PGcancelConn
</structname> object
6244 is an opaque structure that is not meant to be accessed directly by the
6245 application. This
<structname>PGcancelConn
</structname> object can be
6246 used to cancel the query that's running on the original connection in a
6251 Many connection parameters of the original client will be reused when
6252 setting up the connection for the cancel request. Importantly, if the
6253 original connection requires encryption of the connection and/or
6254 verification of the target host (using
<literal>sslmode
</literal> or
6255 <literal>gssencmode
</literal>), then the connection for the cancel
6256 request is made with these same requirements. Any connection options
6257 that are only used during authentication or after authentication of the
6258 client are ignored though, because cancellation requests do not require
6259 authentication and the connection is closed right after the cancellation
6260 request is submitted.
6264 Note that when
<function>PQcancelCreate
</function> returns a non-null
6265 pointer, you must call
<xref linkend=
"libpq-PQcancelFinish"/> when you
6266 are finished with it, in order to dispose of the structure and any
6267 associated memory blocks. This must be done even if the cancel request
6268 failed or was abandoned.
6273 <varlistentry id=
"libpq-PQcancelBlocking">
6274 <term><function>PQcancelBlocking
</function><indexterm><primary>PQcancelBlocking
</primary></indexterm></term>
6278 Requests that the server abandons processing of the current command
6279 in a blocking manner.
6281 int PQcancelBlocking(PGcancelConn *cancelConn);
6286 The request is made over the given
<structname>PGcancelConn
</structname>,
6287 which needs to be created with
<xref linkend=
"libpq-PQcancelCreate"/>.
6288 The return value of
<xref linkend=
"libpq-PQcancelBlocking"/>
6289 is
1 if the cancel request was successfully
6290 dispatched and
0 if not. If it was unsuccessful, the error message can be
6291 retrieved using
<xref linkend=
"libpq-PQcancelErrorMessage"/>.
6295 Successful dispatch of the cancellation is no guarantee that the request
6296 will have any effect, however. If the cancellation is effective, the
6297 command being canceled will terminate early and return an error result.
6298 If the cancellation fails (say, because the server was already done
6299 processing the command), then there will be no visible result at all.
6305 <varlistentry id=
"libpq-PQcancelStart">
6306 <term><function>PQcancelStart
</function><indexterm><primary>PQcancelStart
</primary></indexterm></term>
6307 <term><function>PQcancelPoll
</function><indexterm><primary>PQcancelPoll
</primary></indexterm></term>
6311 Requests that the server abandons processing of the current command
6312 in a non-blocking manner.
6314 int PQcancelStart(PGcancelConn *cancelConn);
6316 PostgresPollingStatusType PQcancelPoll(PGcancelConn *cancelConn);
6321 The request is made over the given
<structname>PGcancelConn
</structname>,
6322 which needs to be created with
<xref linkend=
"libpq-PQcancelCreate"/>.
6323 The return value of
<xref linkend=
"libpq-PQcancelStart"/>
6324 is
1 if the cancellation request could be started and
0 if not.
6325 If it was unsuccessful, the error message can be
6326 retrieved using
<xref linkend=
"libpq-PQcancelErrorMessage"/>.
6330 If
<function>PQcancelStart
</function> succeeds, the next stage
6331 is to poll
<application>libpq
</application> so that it can proceed with
6332 the cancel connection sequence.
6333 Use
<xref linkend=
"libpq-PQcancelSocket"/> to obtain the descriptor of the
6334 socket underlying the database connection.
6335 (Caution: do not assume that the socket remains the same
6336 across
<function>PQcancelPoll
</function> calls.)
6337 Loop thus: If
<function>PQcancelPoll(cancelConn)
</function> last returned
6338 <symbol>PGRES_POLLING_READING
</symbol>, wait until the socket is ready to
6339 read (as indicated by
<function>select()
</function>,
6340 <function>poll()
</function>, or similar system function).
6341 Then call
<function>PQcancelPoll(cancelConn)
</function> again.
6342 Conversely, if
<function>PQcancelPoll(cancelConn)
</function> last returned
6343 <symbol>PGRES_POLLING_WRITING
</symbol>, wait until the socket is ready
6344 to write, then call
<function>PQcancelPoll(cancelConn)
</function> again.
6345 On the first iteration, i.e., if you have yet to call
6346 <function>PQcancelPoll(cancelConn)
</function>, behave as if it last returned
6347 <symbol>PGRES_POLLING_WRITING
</symbol>. Continue this loop until
6348 <function>PQcancelPoll(cancelConn)
</function> returns
6349 <symbol>PGRES_POLLING_FAILED
</symbol>, indicating the connection procedure
6350 has failed, or
<symbol>PGRES_POLLING_OK
</symbol>, indicating cancel
6351 request was successfully dispatched.
6355 Successful dispatch of the cancellation is no guarantee that the request
6356 will have any effect, however. If the cancellation is effective, the
6357 command being canceled will terminate early and return an error result.
6358 If the cancellation fails (say, because the server was already done
6359 processing the command), then there will be no visible result at all.
6363 At any time during connection, the status of the connection can be
6364 checked by calling
<xref linkend=
"libpq-PQcancelStatus"/>.
6365 If this call returns
<symbol>CONNECTION_BAD
</symbol>, then
6366 the cancel procedure has failed; if the call returns
6367 <function>CONNECTION_OK
</function>, then cancel request was
6368 successfully dispatched.
6369 Both of these states are equally detectable from the return value of
6370 <function>PQcancelPoll
</function>, described above.
6371 Other states might also occur during (and only during) an asynchronous
6372 connection procedure.
6373 These indicate the current stage of the connection procedure and might
6374 be useful to provide feedback to the user for example.
6378 <varlistentry id=
"libpq-cancel-connection-allocated">
6379 <term><symbol>CONNECTION_ALLOCATED
</symbol></term>
6382 Waiting for a call to
<xref linkend=
"libpq-PQcancelStart"/> or
6383 <xref linkend=
"libpq-PQcancelBlocking"/>, to actually open the
6384 socket. This is the connection state right after
6385 calling
<xref linkend=
"libpq-PQcancelCreate"/>
6386 or
<xref linkend=
"libpq-PQcancelReset"/>. No connection to the
6387 server has been initiated yet at this point. To actually start
6388 sending the cancel request use
<xref linkend=
"libpq-PQcancelStart"/> or
6389 <xref linkend=
"libpq-PQcancelBlocking"/>.
6394 <varlistentry id=
"libpq-cancel-connection-started">
6395 <term><symbol>CONNECTION_STARTED
</symbol></term>
6398 Waiting for connection to be made.
6403 <varlistentry id=
"libpq-cancel-connection-made">
6404 <term><symbol>CONNECTION_MADE
</symbol></term>
6407 Connection OK; waiting to send.
6412 <varlistentry id=
"libpq-cancel-connection-awaiting-response">
6413 <term><symbol>CONNECTION_AWAITING_RESPONSE
</symbol></term>
6416 Waiting for a response from the server.
6421 <varlistentry id=
"libpq-cancel-connection-ssl-startup">
6422 <term><symbol>CONNECTION_SSL_STARTUP
</symbol></term>
6425 Negotiating SSL encryption.
6430 <varlistentry id=
"libpq-cancel-connection-gss-startup">
6431 <term><symbol>CONNECTION_GSS_STARTUP
</symbol></term>
6434 Negotiating GSS encryption.
6440 Note that, although these constants will remain (in order to maintain
6441 compatibility), an application should never rely upon these occurring in a
6442 particular order, or at all, or on the status always being one of these
6443 documented values. An application might do something like this:
6445 switch(PQcancelStatus(conn))
6447 case CONNECTION_STARTED:
6448 feedback =
"Connecting...";
6451 case CONNECTION_MADE:
6452 feedback =
"Connected to server...";
6458 feedback =
"Connecting...";
6464 The
<literal>connect_timeout
</literal> connection parameter is ignored
6465 when using
<function>PQcancelPoll
</function>; it is the application's
6466 responsibility to decide whether an excessive amount of time has elapsed.
6467 Otherwise,
<function>PQcancelStart
</function> followed by a
6468 <function>PQcancelPoll
</function> loop is equivalent to
6469 <xref linkend=
"libpq-PQcancelBlocking"/>.
6475 <varlistentry id=
"libpq-PQcancelStatus">
6476 <term><function>PQcancelStatus
</function><indexterm><primary>PQcancelStatus
</primary></indexterm></term>
6480 Returns the status of the cancel connection.
6482 ConnStatusType PQcancelStatus(const PGcancelConn *cancelConn);
6487 The status can be one of a number of values. However, only three of
6488 these are seen outside of an asynchronous cancel procedure:
6489 <literal>CONNECTION_ALLOCATED
</literal>,
6490 <literal>CONNECTION_OK
</literal> and
6491 <literal>CONNECTION_BAD
</literal>. The initial state of a
6492 <function>PGcancelConn
</function> that's successfully created using
6493 <xref linkend=
"libpq-PQcancelCreate"/> is
<literal>CONNECTION_ALLOCATED
</literal>.
6494 A cancel request that was successfully dispatched
6495 has the status
<literal>CONNECTION_OK
</literal>. A failed
6496 cancel attempt is signaled by status
6497 <literal>CONNECTION_BAD
</literal>. An OK status will
6498 remain so until
<xref linkend=
"libpq-PQcancelFinish"/> or
6499 <xref linkend=
"libpq-PQcancelReset"/> is called.
6503 See the entry for
<xref linkend=
"libpq-PQcancelStart"/> with regards
6504 to other status codes that might be returned.
6508 Successful dispatch of the cancellation is no guarantee that the request
6509 will have any effect, however. If the cancellation is effective, the
6510 command being canceled will terminate early and return an error result.
6511 If the cancellation fails (say, because the server was already done
6512 processing the command), then there will be no visible result at all.
6518 <varlistentry id=
"libpq-PQcancelSocket">
6519 <term><function>PQcancelSocket
</function><indexterm><primary>PQcancelSocket
</primary></indexterm></term>
6523 Obtains the file descriptor number of the cancel connection socket to
6526 int PQcancelSocket(const PGcancelConn *cancelConn);
6531 A valid descriptor will be greater than or equal to
0;
6532 a result of -
1 indicates that no server connection is currently open.
6533 This might change as a result of calling any of the functions
6534 in this section on the
<structname>PGcancelConn
</structname>
6535 (except for
<xref linkend=
"libpq-PQcancelErrorMessage"/> and
6536 <function>PQcancelSocket
</function> itself).
6541 <varlistentry id=
"libpq-PQcancelErrorMessage">
6543 <function>PQcancelErrorMessage
</function><indexterm><primary>PQcancelErrorMessage
</primary></indexterm>
6544 <indexterm><primary>error message
</primary><secondary>in
<structname>PGcancelConn
</structname></secondary></indexterm>
6549 Returns the error message most recently generated by an
6550 operation on the cancel connection.
6552 char *PQcancelErrorMessage(const PGcancelConn *cancelconn);
6557 Nearly all
<application>libpq
</application> functions that take a
6558 <structname>PGcancelConn
</structname> will set a message for
6559 <xref linkend=
"libpq-PQcancelErrorMessage"/> if they fail.
6560 Note that by
<application>libpq
</application> convention,
6561 a nonempty
<xref linkend=
"libpq-PQcancelErrorMessage"/> result
6562 can consist of multiple lines, and will include a trailing newline.
6563 The caller should not free the result directly.
6564 It will be freed when the associated
6565 <structname>PGcancelConn
</structname> handle is passed to
6566 <xref linkend=
"libpq-PQcancelFinish"/>. The result string should not be
6567 expected to remain the same across operations on the
6568 <literal>PGcancelConn
</literal> structure.
6573 <varlistentry id=
"libpq-PQcancelFinish">
6574 <term><function>PQcancelFinish
</function><indexterm><primary>PQcancelFinish
</primary></indexterm></term>
6577 Closes the cancel connection (if it did not finish sending the
6578 cancel request yet). Also frees memory used by the
6579 <structname>PGcancelConn
</structname> object.
6581 void PQcancelFinish(PGcancelConn *cancelConn);
6586 Note that even if the cancel attempt fails (as
6587 indicated by
<xref linkend=
"libpq-PQcancelStatus"/>), the
6588 application should call
<xref linkend=
"libpq-PQcancelFinish"/>
6589 to free the memory used by the
<structname>PGcancelConn
</structname>
6591 The
<structname>PGcancelConn
</structname> pointer must not be used
6592 again after
<xref linkend=
"libpq-PQcancelFinish"/> has been called.
6597 <varlistentry id=
"libpq-PQcancelReset">
6598 <term><function>PQcancelReset
</function><indexterm><primary>PQcancelReset
</primary></indexterm></term>
6601 Resets the
<symbol>PGcancelConn
</symbol> so it can be reused for a new
6604 void PQcancelReset(PGcancelConn *cancelConn);
6609 If the
<symbol>PGcancelConn
</symbol> is currently used to send a cancel
6610 request, then this connection is closed. It will then prepare the
6611 <symbol>PGcancelConn
</symbol> object such that it can be used to send a
6616 This can be used to create one
<structname>PGcancelConn
</structname>
6617 for a
<structname>PGconn
</structname> and reuse it multiple times
6618 throughout the lifetime of the original
<structname>PGconn
</structname>.
6625 <sect2 id=
"libpq-cancel-deprecated">
6626 <title>Obsolete Functions for Sending Cancel Requests
</title>
6629 These functions represent older methods of sending cancel requests.
6630 Although they still work, they are deprecated due to not sending the cancel
6631 requests in an encrypted manner, even when the original connection
6632 specified
<literal>sslmode
</literal> or
<literal>gssencmode
</literal> to
6633 require encryption. Thus these older methods are heavily discouraged from
6634 being used in new code, and it is recommended to change existing code to
6635 use the new functions instead.
6639 <varlistentry id=
"libpq-PQgetCancel">
6640 <term><function>PQgetCancel
</function><indexterm><primary>PQgetCancel
</primary></indexterm></term>
6644 Creates a data structure containing the information needed to cancel
6645 a command using
<xref linkend=
"libpq-PQcancel"/>.
6647 PGcancel *PQgetCancel(PGconn *conn);
6652 <xref linkend=
"libpq-PQgetCancel"/> creates a
6653 <structname>PGcancel
</structname><indexterm><primary>PGcancel
</primary></indexterm>
6654 object given a
<structname>PGconn
</structname> connection object.
6655 It will return
<symbol>NULL
</symbol> if the given
<parameter>conn
</parameter>
6656 is
<symbol>NULL
</symbol> or an invalid connection.
6657 The
<structname>PGcancel
</structname> object is an opaque
6658 structure that is not meant to be accessed directly by the
6659 application; it can only be passed to
<xref linkend=
"libpq-PQcancel"/>
6660 or
<xref linkend=
"libpq-PQfreeCancel"/>.
6665 <varlistentry id=
"libpq-PQfreeCancel">
6666 <term><function>PQfreeCancel
</function><indexterm><primary>PQfreeCancel
</primary></indexterm></term>
6670 Frees a data structure created by
<xref linkend=
"libpq-PQgetCancel"/>.
6672 void PQfreeCancel(PGcancel *cancel);
6677 <xref linkend=
"libpq-PQfreeCancel"/> frees a data object previously created
6678 by
<xref linkend=
"libpq-PQgetCancel"/>.
6683 <varlistentry id=
"libpq-PQcancel">
6684 <term><function>PQcancel
</function><indexterm><primary>PQcancel
</primary></indexterm></term>
6688 <xref linkend=
"libpq-PQcancel"/> is a deprecated and insecure
6689 variant of
<xref linkend=
"libpq-PQcancelBlocking"/>, but one that can be
6690 used safely from within a signal handler.
6692 int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize);
6697 <xref linkend=
"libpq-PQcancel"/> only exists because of backwards
6698 compatibility reasons.
<xref linkend=
"libpq-PQcancelBlocking"/> should be
6699 used instead. The only benefit that
<xref linkend=
"libpq-PQcancel"/> has
6700 is that it can be safely invoked from a signal handler, if the
6701 <parameter>errbuf
</parameter> is a local variable in the signal handler.
6702 However, this is generally not considered a big enough benefit to be
6703 worth the security issues that this function has.
6707 The
<structname>PGcancel
</structname> object is read-only as far as
6708 <xref linkend=
"libpq-PQcancel"/> is concerned, so it can also be invoked
6709 from a thread that is separate from the one manipulating the
6710 <structname>PGconn
</structname> object.
6714 The return value of
<xref linkend=
"libpq-PQcancel"/> is
1 if the
6715 cancel request was successfully dispatched and
0 if not.
6716 If not,
<parameter>errbuf
</parameter> is filled with an explanatory
6718 <parameter>errbuf
</parameter> must be a char array of size
6719 <parameter>errbufsize
</parameter> (the recommended size is
256 bytes).
6726 <varlistentry id=
"libpq-PQrequestCancel">
6727 <term><function>PQrequestCancel
</function><indexterm><primary>PQrequestCancel
</primary></indexterm></term>
6731 <xref linkend=
"libpq-PQrequestCancel"/> is a deprecated and insecure
6732 variant of
<xref linkend=
"libpq-PQcancelBlocking"/>.
6734 int PQrequestCancel(PGconn *conn);
6739 <xref linkend=
"libpq-PQrequestCancel"/> only exists because of backwards
6740 compatibility reasons.
<xref linkend=
"libpq-PQcancelBlocking"/> should be
6741 used instead. There is no benefit to using
6742 <xref linkend=
"libpq-PQrequestCancel"/> over
6743 <xref linkend=
"libpq-PQcancelBlocking"/>.
6747 Requests that the server abandon processing of the current
6748 command. It operates directly on the
6749 <structname>PGconn
</structname> object, and in case of failure stores the
6750 error message in the
<structname>PGconn
</structname> object (whence it can
6751 be retrieved by
<xref linkend=
"libpq-PQerrorMessage"/>). Although
6752 the functionality is the same, this approach is not safe within
6753 multiple-thread programs or signal handlers, since it is possible
6754 that overwriting the
<structname>PGconn
</structname>'s error message will
6755 mess up the operation currently in progress on the connection.
6763 <sect1 id=
"libpq-fastpath">
6764 <title>The Fast-Path Interface
</title>
6766 <indexterm zone=
"libpq-fastpath">
6767 <primary>fast path
</primary>
6771 <productname>PostgreSQL
</productname> provides a fast-path interface
6772 to send simple function calls to the server.
6777 This interface is somewhat obsolete, as one can achieve similar
6778 performance and greater functionality by setting up a prepared
6779 statement to define the function call. Then, executing the statement
6780 with binary transmission of parameters and results substitutes for a
6781 fast-path function call.
6786 The function
<function id=
"libpq-PQfn">PQfn
</function><indexterm><primary>PQfn
</primary></indexterm>
6787 requests execution of a server function via the fast-path interface:
6789 PGresult *PQfn(PGconn *conn,
6794 const PQArgBlock *args,
6811 The
<parameter>fnid
</parameter> argument is the OID of the function to be
6812 executed.
<parameter>args
</parameter> and
<parameter>nargs
</parameter> define the
6813 parameters to be passed to the function; they must match the declared
6814 function argument list. When the
<parameter>isint
</parameter> field of a
6815 parameter structure is true, the
<parameter>u.integer
</parameter> value is sent
6816 to the server as an integer of the indicated length (this must be
6817 2 or
4 bytes); proper byte-swapping occurs. When
<parameter>isint
</parameter>
6818 is false, the indicated number of bytes at
<parameter>*u.ptr
</parameter> are
6819 sent with no processing; the data must be in the format expected by
6820 the server for binary transmission of the function's argument data
6821 type. (The declaration of
<parameter>u.ptr
</parameter> as being of
6822 type
<type>int *
</type> is historical; it would be better to consider
6823 it
<type>void *
</type>.)
6824 <parameter>result_buf
</parameter> points to the buffer in which to place
6825 the function's return value. The caller must have allocated sufficient
6826 space to store the return value. (There is no check!) The actual result
6827 length in bytes will be returned in the integer pointed to by
6828 <parameter>result_len
</parameter>. If a
2- or
4-byte integer result
6829 is expected, set
<parameter>result_is_int
</parameter> to
1, otherwise
6830 set it to
0. Setting
<parameter>result_is_int
</parameter> to
1 causes
6831 <application>libpq
</application> to byte-swap the value if necessary, so that it
6832 is delivered as a proper
<type>int
</type> value for the client machine;
6833 note that a
4-byte integer is delivered into
<parameter>*result_buf
</parameter>
6834 for either allowed result size.
6835 When
<parameter>result_is_int
</parameter> is
0, the binary-format byte string
6836 sent by the server is returned unmodified. (In this case it's better
6837 to consider
<parameter>result_buf
</parameter> as being of
6838 type
<type>void *
</type>.)
6842 <function>PQfn
</function> always returns a valid
6843 <structname>PGresult
</structname> pointer, with
6844 status
<literal>PGRES_COMMAND_OK
</literal> for success
6845 or
<literal>PGRES_FATAL_ERROR
</literal> if some problem was encountered.
6846 The result status should be
6847 checked before the result is used. The caller is responsible for
6848 freeing the
<structname>PGresult
</structname> with
6849 <xref linkend=
"libpq-PQclear"/> when it is no longer needed.
6853 To pass a NULL argument to the function, set
6854 the
<parameter>len
</parameter> field of that parameter structure
6855 to
<literal>-
1</literal>; the
<parameter>isint
</parameter>
6856 and
<parameter>u
</parameter> fields are then irrelevant.
6860 If the function returns NULL,
<parameter>*result_len
</parameter> is set
6861 to
<literal>-
1</literal>, and
<parameter>*result_buf
</parameter> is not
6866 Note that it is not possible to handle set-valued results when using
6867 this interface. Also, the function must be a plain function, not an
6868 aggregate, window function, or procedure.
6873 <sect1 id=
"libpq-notify">
6874 <title>Asynchronous Notification
</title>
6876 <indexterm zone=
"libpq-notify">
6877 <primary>NOTIFY
</primary>
6878 <secondary>in libpq
</secondary>
6882 <productname>PostgreSQL
</productname> offers asynchronous notification
6883 via the
<command>LISTEN
</command> and
<command>NOTIFY
</command>
6884 commands. A client session registers its interest in a particular
6885 notification channel with the
<command>LISTEN
</command> command (and
6886 can stop listening with the
<command>UNLISTEN
</command> command). All
6887 sessions listening on a particular channel will be notified
6888 asynchronously when a
<command>NOTIFY
</command> command with that
6889 channel name is executed by any session. A
<quote>payload
</quote> string can
6890 be passed to communicate additional data to the listeners.
6894 <application>libpq
</application> applications submit
6895 <command>LISTEN
</command>,
<command>UNLISTEN
</command>,
6896 and
<command>NOTIFY
</command> commands as
6897 ordinary SQL commands. The arrival of
<command>NOTIFY
</command>
6898 messages can subsequently be detected by calling
6899 <function id=
"libpq-PQnotifies">PQnotifies
</function>.
<indexterm><primary>PQnotifies
</primary></indexterm>
6903 The function
<function>PQnotifies
</function> returns the next notification
6904 from a list of unhandled notification messages received from the server.
6905 It returns a null pointer if there are no pending notifications. Once a
6906 notification is returned from
<function>PQnotifies
</function>, it is considered
6907 handled and will be removed from the list of notifications.
6910 PGnotify *PQnotifies(PGconn *conn);
6912 typedef struct pgNotify
6914 char *relname; /* notification channel name */
6915 int be_pid; /* process ID of notifying server process */
6916 char *extra; /* notification payload string */
6920 After processing a
<structname>PGnotify
</structname> object returned
6921 by
<function>PQnotifies
</function>, be sure to free it with
6922 <xref linkend=
"libpq-PQfreemem"/>. It is sufficient to free the
6923 <structname>PGnotify
</structname> pointer; the
6924 <structfield>relname
</structfield> and
<structfield>extra
</structfield>
6925 fields do not represent separate allocations. (The names of these fields
6926 are historical; in particular, channel names need not have anything to
6927 do with relation names.)
6931 <xref linkend=
"libpq-example-2"/> gives a sample program that illustrates
6932 the use of asynchronous notification.
6936 <function>PQnotifies
</function> does not actually read data from the
6937 server; it just returns messages previously absorbed by another
6938 <application>libpq
</application> function. In ancient releases of
6939 <application>libpq
</application>, the only way to ensure timely receipt
6940 of
<command>NOTIFY
</command> messages was to constantly submit commands, even
6941 empty ones, and then check
<function>PQnotifies
</function> after each
6942 <xref linkend=
"libpq-PQexec"/>. While this still works, it is deprecated
6943 as a waste of processing power.
6947 A better way to check for
<command>NOTIFY
</command> messages when you have no
6948 useful commands to execute is to call
6949 <xref linkend=
"libpq-PQconsumeInput"/>, then check
6950 <function>PQnotifies
</function>. You can use
6951 <function>select()
</function> to wait for data to arrive from the
6952 server, thereby using no
<acronym>CPU
</acronym> power unless there is
6953 something to do. (See
<xref linkend=
"libpq-PQsocket"/> to obtain the file
6954 descriptor number to use with
<function>select()
</function>.) Note that
6955 this will work OK whether you submit commands with
6956 <xref linkend=
"libpq-PQsendQuery"/>/
<xref linkend=
"libpq-PQgetResult"/> or
6957 simply use
<xref linkend=
"libpq-PQexec"/>. You should, however, remember
6958 to check
<function>PQnotifies
</function> after each
6959 <xref linkend=
"libpq-PQgetResult"/> or
<xref linkend=
"libpq-PQexec"/>, to
6960 see if any notifications came in during the processing of the command.
6965 <sect1 id=
"libpq-copy">
6966 <title>Functions Associated with the
<command>COPY
</command> Command
</title>
6968 <indexterm zone=
"libpq-copy">
6969 <primary>COPY
</primary>
6970 <secondary>with libpq
</secondary>
6974 The
<command>COPY
</command> command in
6975 <productname>PostgreSQL
</productname> has options to read from or write
6976 to the network connection used by
<application>libpq
</application>.
6977 The functions described in this section allow applications to take
6978 advantage of this capability by supplying or consuming copied data.
6982 The overall process is that the application first issues the SQL
6983 <command>COPY
</command> command via
<xref linkend=
"libpq-PQexec"/> or one
6984 of the equivalent functions. The response to this (if there is no
6985 error in the command) will be a
<structname>PGresult
</structname> object bearing
6986 a status code of
<literal>PGRES_COPY_OUT
</literal> or
6987 <literal>PGRES_COPY_IN
</literal> (depending on the specified copy
6988 direction). The application should then use the functions of this
6989 section to receive or transmit data rows. When the data transfer is
6990 complete, another
<structname>PGresult
</structname> object is returned to indicate
6991 success or failure of the transfer. Its status will be
6992 <literal>PGRES_COMMAND_OK
</literal> for success or
6993 <literal>PGRES_FATAL_ERROR
</literal> if some problem was encountered.
6994 At this point further SQL commands can be issued via
6995 <xref linkend=
"libpq-PQexec"/>. (It is not possible to execute other SQL
6996 commands using the same connection while the
<command>COPY
</command>
6997 operation is in progress.)
7001 If a
<command>COPY
</command> command is issued via
7002 <xref linkend=
"libpq-PQexec"/> in a string that could contain additional
7003 commands, the application must continue fetching results via
7004 <xref linkend=
"libpq-PQgetResult"/> after completing the
<command>COPY
</command>
7005 sequence. Only when
<xref linkend=
"libpq-PQgetResult"/> returns
7006 <symbol>NULL
</symbol> is it certain that the
<xref linkend=
"libpq-PQexec"/>
7007 command string is done and it is safe to issue more commands.
7011 The functions of this section should be executed only after obtaining
7012 a result status of
<literal>PGRES_COPY_OUT
</literal> or
7013 <literal>PGRES_COPY_IN
</literal> from
<xref linkend=
"libpq-PQexec"/> or
7014 <xref linkend=
"libpq-PQgetResult"/>.
7018 A
<structname>PGresult
</structname> object bearing one of these status values
7019 carries some additional data about the
<command>COPY
</command> operation
7020 that is starting. This additional data is available using functions
7021 that are also used in connection with query results:
7024 <varlistentry id=
"libpq-PQnfields-1">
7025 <term><function>PQnfields
</function><indexterm
7026 ><primary>PQnfields
</primary><secondary>with COPY
</secondary></indexterm></term>
7030 Returns the number of columns (fields) to be copied.
7035 <varlistentry id=
"libpq-PQbinaryTuples-1">
7036 <term><function>PQbinaryTuples
</function><indexterm
7037 ><primary>PQbinaryTuples
</primary><secondary>with COPY
</secondary></indexterm></term>
7041 0 indicates the overall copy format is textual (rows separated by
7042 newlines, columns separated by separator characters, etc.).
1
7043 indicates the overall copy format is binary. See
<xref
7044 linkend=
"sql-copy"/> for more information.
7049 <varlistentry id=
"libpq-PQfformat-1">
7050 <term><function>PQfformat
</function><indexterm
7051 ><primary>PQfformat
</primary><secondary>with COPY
</secondary></indexterm></term>
7055 Returns the format code (
0 for text,
1 for binary) associated with
7056 each column of the copy operation. The per-column format codes
7057 will always be zero when the overall copy format is textual, but
7058 the binary format can support both text and binary columns.
7059 (However, as of the current implementation of
<command>COPY
</command>,
7060 only binary columns appear in a binary copy; so the per-column
7061 formats always match the overall format at present.)
7068 <sect2 id=
"libpq-copy-send">
7069 <title>Functions for Sending
<command>COPY
</command> Data
</title>
7072 These functions are used to send data during
<literal>COPY FROM
7073 STDIN
</literal>. They will fail if called when the connection is not in
7074 <literal>COPY_IN
</literal> state.
7078 <varlistentry id=
"libpq-PQputCopyData">
7079 <term><function>PQputCopyData
</function><indexterm><primary>PQputCopyData
</primary></indexterm></term>
7083 Sends data to the server during
<literal>COPY_IN
</literal> state.
7085 int PQputCopyData(PGconn *conn,
7092 Transmits the
<command>COPY
</command> data in the specified
7093 <parameter>buffer
</parameter>, of length
<parameter>nbytes
</parameter>, to the server.
7094 The result is
1 if the data was queued, zero if it was not queued
7095 because of full buffers (this will only happen in nonblocking mode),
7096 or -
1 if an error occurred.
7097 (Use
<xref linkend=
"libpq-PQerrorMessage"/> to retrieve details if
7098 the return value is -
1. If the value is zero, wait for write-ready
7103 The application can divide the
<command>COPY
</command> data stream
7104 into buffer loads of any convenient size. Buffer-load boundaries
7105 have no semantic significance when sending. The contents of the
7106 data stream must match the data format expected by the
7107 <command>COPY
</command> command; see
<xref linkend=
"sql-copy"/> for details.
7112 <varlistentry id=
"libpq-PQputCopyEnd">
7113 <term><function>PQputCopyEnd
</function><indexterm><primary>PQputCopyEnd
</primary></indexterm></term>
7117 Sends end-of-data indication to the server during
<literal>COPY_IN
</literal> state.
7119 int PQputCopyEnd(PGconn *conn,
7120 const char *errormsg);
7125 Ends the
<literal>COPY_IN
</literal> operation successfully if
7126 <parameter>errormsg
</parameter> is
<symbol>NULL
</symbol>. If
7127 <parameter>errormsg
</parameter> is not
<symbol>NULL
</symbol> then the
7128 <command>COPY
</command> is forced to fail, with the string pointed to by
7129 <parameter>errormsg
</parameter> used as the error message. (One should not
7130 assume that this exact error message will come back from the server,
7131 however, as the server might have already failed the
7132 <command>COPY
</command> for its own reasons.)
7136 The result is
1 if the termination message was sent; or in
7137 nonblocking mode, this may only indicate that the termination
7138 message was successfully queued. (In nonblocking mode, to be
7139 certain that the data has been sent, you should next wait for
7140 write-ready and call
<xref linkend=
"libpq-PQflush"/>, repeating until it
7141 returns zero.) Zero indicates that the function could not queue
7142 the termination message because of full buffers; this will only
7143 happen in nonblocking mode. (In this case, wait for
7144 write-ready and try the
<xref linkend=
"libpq-PQputCopyEnd"/> call
7145 again.) If a hard error occurs, -
1 is returned; you can use
7146 <xref linkend=
"libpq-PQerrorMessage"/> to retrieve details.
7150 After successfully calling
<xref linkend=
"libpq-PQputCopyEnd"/>, call
7151 <xref linkend=
"libpq-PQgetResult"/> to obtain the final result status of the
7152 <command>COPY
</command> command. One can wait for this result to be
7153 available in the usual way. Then return to normal operation.
7161 <sect2 id=
"libpq-copy-receive">
7162 <title>Functions for Receiving
<command>COPY
</command> Data
</title>
7165 These functions are used to receive data during
<literal>COPY TO
7166 STDOUT
</literal>. They will fail if called when the connection is not in
7167 <literal>COPY_OUT
</literal> state.
7171 <varlistentry id=
"libpq-PQgetCopyData">
7172 <term><function>PQgetCopyData
</function><indexterm><primary>PQgetCopyData
</primary></indexterm></term>
7176 Receives data from the server during
<literal>COPY_OUT
</literal> state.
7178 int PQgetCopyData(PGconn *conn,
7185 Attempts to obtain another row of data from the server during a
7186 <command>COPY
</command>. Data is always returned one data row at
7187 a time; if only a partial row is available, it is not returned.
7188 Successful return of a data row involves allocating a chunk of
7189 memory to hold the data. The
<parameter>buffer
</parameter> parameter must
7190 be non-
<symbol>NULL
</symbol>.
<parameter>*buffer
</parameter> is set to
7191 point to the allocated memory, or to
<symbol>NULL
</symbol> in cases
7192 where no buffer is returned. A non-
<symbol>NULL
</symbol> result
7193 buffer should be freed using
<xref linkend=
"libpq-PQfreemem"/> when no longer
7198 When a row is successfully returned, the return value is the number
7199 of data bytes in the row (this will always be greater than zero).
7200 The returned string is always null-terminated, though this is
7201 probably only useful for textual
<command>COPY
</command>. A result
7202 of zero indicates that the
<command>COPY
</command> is still in
7203 progress, but no row is yet available (this is only possible when
7204 <parameter>async
</parameter> is true). A result of -
1 indicates that the
7205 <command>COPY
</command> is done. A result of -
2 indicates that an
7206 error occurred (consult
<xref linkend=
"libpq-PQerrorMessage"/> for the reason).
7210 When
<parameter>async
</parameter> is true (not zero),
7211 <xref linkend=
"libpq-PQgetCopyData"/> will not block waiting for input; it
7212 will return zero if the
<command>COPY
</command> is still in progress
7213 but no complete row is available. (In this case wait for read-ready
7214 and then call
<xref linkend=
"libpq-PQconsumeInput"/> before calling
7215 <xref linkend=
"libpq-PQgetCopyData"/> again.) When
<parameter>async
</parameter> is
7216 false (zero),
<xref linkend=
"libpq-PQgetCopyData"/> will block until data is
7217 available or the operation completes.
7221 After
<xref linkend=
"libpq-PQgetCopyData"/> returns -
1, call
7222 <xref linkend=
"libpq-PQgetResult"/> to obtain the final result status of the
7223 <command>COPY
</command> command. One can wait for this result to be
7224 available in the usual way. Then return to normal operation.
7232 <sect2 id=
"libpq-copy-deprecated">
7233 <title>Obsolete Functions for
<command>COPY
</command></title>
7236 These functions represent older methods of handling
<command>COPY
</command>.
7237 Although they still work, they are deprecated due to poor error handling,
7238 inconvenient methods of detecting end-of-data, and lack of support for binary
7239 or nonblocking transfers.
7243 <varlistentry id=
"libpq-PQgetline">
7244 <term><function>PQgetline
</function><indexterm><primary>PQgetline
</primary></indexterm></term>
7248 Reads a newline-terminated line of characters (transmitted
7249 by the server) into a buffer string of size
<parameter>length
</parameter>.
7251 int PQgetline(PGconn *conn,
7258 This function copies up to
<parameter>length
</parameter>-
1 characters into
7259 the buffer and converts the terminating newline into a zero byte.
7260 <xref linkend=
"libpq-PQgetline"/> returns
<symbol>EOF
</symbol> at the
7261 end of input,
0 if the entire line has been read, and
1 if the
7262 buffer is full but the terminating newline has not yet been read.
7265 Note that the application must check to see if a new line consists
7266 of the two characters
<literal>\.
</literal>, which indicates
7267 that the server has finished sending the results of the
7268 <command>COPY
</command> command. If the application might receive
7269 lines that are more than
<parameter>length
</parameter>-
1 characters long,
7270 care is needed to be sure it recognizes the
<literal>\.
</literal>
7271 line correctly (and does not, for example, mistake the end of a
7272 long data line for a terminator line).
7277 <varlistentry id=
"libpq-PQgetlineAsync">
7278 <term><function>PQgetlineAsync
</function><indexterm><primary>PQgetlineAsync
</primary></indexterm></term>
7282 Reads a row of
<command>COPY
</command> data (transmitted by the
7283 server) into a buffer without blocking.
7285 int PQgetlineAsync(PGconn *conn,
7292 This function is similar to
<xref linkend=
"libpq-PQgetline"/>, but it can be used
7294 that must read
<command>COPY
</command> data asynchronously, that is, without blocking.
7295 Having issued the
<command>COPY
</command> command and gotten a
<literal>PGRES_COPY_OUT
</literal>
7297 application should call
<xref linkend=
"libpq-PQconsumeInput"/> and
7298 <xref linkend=
"libpq-PQgetlineAsync"/> until the
7299 end-of-data signal is detected.
7302 Unlike
<xref linkend=
"libpq-PQgetline"/>, this function takes
7303 responsibility for detecting end-of-data.
7307 On each call,
<xref linkend=
"libpq-PQgetlineAsync"/> will return data if a
7308 complete data row is available in
<application>libpq
</application>'s input buffer.
7309 Otherwise, no data is returned until the rest of the row arrives.
7310 The function returns -
1 if the end-of-copy-data marker has been recognized,
7311 or
0 if no data is available, or a positive number giving the number of
7312 bytes of data returned. If -
1 is returned, the caller must next call
7313 <xref linkend=
"libpq-PQendcopy"/>, and then return to normal processing.
7317 The data returned will not extend beyond a data-row boundary. If possible
7318 a whole row will be returned at one time. But if the buffer offered by
7319 the caller is too small to hold a row sent by the server, then a partial
7320 data row will be returned. With textual data this can be detected by testing
7321 whether the last returned byte is
<literal>\n
</literal> or not. (In a binary
7322 <command>COPY
</command>, actual parsing of the
<command>COPY
</command> data format will be needed to make the
7323 equivalent determination.)
7324 The returned string is not null-terminated. (If you want to add a
7325 terminating null, be sure to pass a
<parameter>bufsize
</parameter> one smaller
7326 than the room actually available.)
7331 <varlistentry id=
"libpq-PQputline">
7332 <term><function>PQputline
</function><indexterm><primary>PQputline
</primary></indexterm></term>
7336 Sends a null-terminated string to the server. Returns
0 if
7337 OK and
<symbol>EOF
</symbol> if unable to send the string.
7339 int PQputline(PGconn *conn,
7340 const char *string);
7345 The
<command>COPY
</command> data stream sent by a series of calls
7346 to
<xref linkend=
"libpq-PQputline"/> has the same format as that
7347 returned by
<xref linkend=
"libpq-PQgetlineAsync"/>, except that
7348 applications are not obliged to send exactly one data row per
7349 <xref linkend=
"libpq-PQputline"/> call; it is okay to send a partial
7350 line or multiple lines per call.
7355 Before
<productname>PostgreSQL
</productname> protocol
3.0, it was necessary
7356 for the application to explicitly send the two characters
7357 <literal>\.
</literal> as a final line to indicate to the server that it had
7358 finished sending
<command>COPY
</command> data. While this still works, it is deprecated and the
7359 special meaning of
<literal>\.
</literal> can be expected to be removed in a
7360 future release. It is sufficient to call
<xref linkend=
"libpq-PQendcopy"/> after
7361 having sent the actual data.
7367 <varlistentry id=
"libpq-PQputnbytes">
7368 <term><function>PQputnbytes
</function><indexterm><primary>PQputnbytes
</primary></indexterm></term>
7372 Sends a non-null-terminated string to the server. Returns
7373 0 if OK and
<symbol>EOF
</symbol> if unable to send the string.
7375 int PQputnbytes(PGconn *conn,
7382 This is exactly like
<xref linkend=
"libpq-PQputline"/>, except that the data
7383 buffer need not be null-terminated since the number of bytes to send is
7384 specified directly. Use this procedure when sending binary data.
7389 <varlistentry id=
"libpq-PQendcopy">
7390 <term><function>PQendcopy
</function><indexterm><primary>PQendcopy
</primary></indexterm></term>
7394 Synchronizes with the server.
7396 int PQendcopy(PGconn *conn);
7398 This function waits until the server has finished the copying.
7399 It should either be issued when the last string has been sent
7400 to the server using
<xref linkend=
"libpq-PQputline"/> or when the
7401 last string has been received from the server using
7402 <function>PQgetline
</function>. It must be issued or the server
7403 will get
<quote>out of sync
</quote> with the client. Upon return
7404 from this function, the server is ready to receive the next SQL
7405 command. The return value is
0 on successful completion,
7406 nonzero otherwise. (Use
<xref linkend=
"libpq-PQerrorMessage"/> to
7407 retrieve details if the return value is nonzero.)
7411 When using
<xref linkend=
"libpq-PQgetResult"/>, the application should
7412 respond to a
<literal>PGRES_COPY_OUT
</literal> result by executing
7413 <xref linkend=
"libpq-PQgetline"/> repeatedly, followed by
7414 <xref linkend=
"libpq-PQendcopy"/> after the terminator line is seen.
7415 It should then return to the
<xref linkend=
"libpq-PQgetResult"/> loop
7416 until
<xref linkend=
"libpq-PQgetResult"/> returns a null pointer.
7417 Similarly a
<literal>PGRES_COPY_IN
</literal> result is processed
7418 by a series of
<xref linkend=
"libpq-PQputline"/> calls followed by
7419 <xref linkend=
"libpq-PQendcopy"/>, then return to the
7420 <xref linkend=
"libpq-PQgetResult"/> loop. This arrangement will
7421 ensure that a
<command>COPY
</command> command embedded in a series
7422 of
<acronym>SQL
</acronym> commands will be executed correctly.
7426 Older applications are likely to submit a
<command>COPY
</command>
7427 via
<xref linkend=
"libpq-PQexec"/> and assume that the transaction
7428 is done after
<xref linkend=
"libpq-PQendcopy"/>. This will work
7429 correctly only if the
<command>COPY
</command> is the only
7430 <acronym>SQL
</acronym> command in the command string.
7440 <sect1 id=
"libpq-control">
7441 <title>Control Functions
</title>
7444 These functions control miscellaneous details of
<application>libpq
</application>'s
7449 <varlistentry id=
"libpq-PQclientEncoding">
7450 <term><function>PQclientEncoding
</function><indexterm><primary>PQclientEncoding
</primary></indexterm></term>
7454 Returns the client encoding.
7456 int PQclientEncoding(const PGconn *
<replaceable>conn
</replaceable>);
7459 Note that it returns the encoding ID, not a symbolic string
7460 such as
<literal>EUC_JP
</literal>. If unsuccessful, it returns -
1.
7461 To convert an encoding ID to an encoding name, you
7465 char *pg_encoding_to_char(int
<replaceable>encoding_id
</replaceable>);
7471 <varlistentry id=
"libpq-PQsetClientEncoding">
7472 <term><function>PQsetClientEncoding
</function><indexterm><primary>PQsetClientEncoding
</primary></indexterm></term>
7476 Sets the client encoding.
7478 int PQsetClientEncoding(PGconn *
<replaceable>conn
</replaceable>, const char *
<replaceable>encoding
</replaceable>);
7481 <replaceable>conn
</replaceable> is a connection to the server,
7482 and
<replaceable>encoding
</replaceable> is the encoding you want to
7483 use. If the function successfully sets the encoding, it returns
0,
7484 otherwise -
1. The current encoding for this connection can be
7485 determined by using
<xref linkend=
"libpq-PQclientEncoding"/>.
7490 <varlistentry id=
"libpq-PQsetErrorVerbosity">
7491 <term><function>PQsetErrorVerbosity
</function><indexterm><primary>PQsetErrorVerbosity
</primary></indexterm></term>
7495 Determines the verbosity of messages returned by
7496 <xref linkend=
"libpq-PQerrorMessage"/> and
<xref linkend=
"libpq-PQresultErrorMessage"/>.
7506 PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity);
7509 <xref linkend=
"libpq-PQsetErrorVerbosity"/> sets the verbosity mode,
7510 returning the connection's previous setting.
7511 In
<firstterm>TERSE
</firstterm> mode, returned messages include
7512 severity, primary text, and position only; this will normally fit on a
7513 single line. The
<firstterm>DEFAULT
</firstterm> mode produces messages
7514 that include the above plus any detail, hint, or context fields (these
7515 might span multiple lines). The
<firstterm>VERBOSE
</firstterm> mode
7516 includes all available fields. The
<firstterm>SQLSTATE
</firstterm>
7517 mode includes only the error severity and the
<symbol>SQLSTATE
</symbol>
7518 error code, if one is available (if not, the output is like
7519 <firstterm>TERSE
</firstterm> mode).
7523 Changing the verbosity setting does not affect the messages available
7524 from already-existing
<structname>PGresult
</structname> objects, only
7525 subsequently-created ones.
7526 (But see
<xref linkend=
"libpq-PQresultVerboseErrorMessage"/> if you
7527 want to print a previous error with a different verbosity.)
7532 <varlistentry id=
"libpq-PQsetErrorContextVisibility">
7533 <term><function>PQsetErrorContextVisibility
</function><indexterm><primary>PQsetErrorContextVisibility
</primary></indexterm></term>
7537 Determines the handling of
<literal>CONTEXT
</literal> fields in messages
7538 returned by
<xref linkend=
"libpq-PQerrorMessage"/>
7539 and
<xref linkend=
"libpq-PQresultErrorMessage"/>.
7543 PQSHOW_CONTEXT_NEVER,
7544 PQSHOW_CONTEXT_ERRORS,
7545 PQSHOW_CONTEXT_ALWAYS
7546 } PGContextVisibility;
7548 PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context);
7551 <xref linkend=
"libpq-PQsetErrorContextVisibility"/> sets the context display mode,
7552 returning the connection's previous setting. This mode controls
7553 whether the
<literal>CONTEXT
</literal> field is included in messages.
7554 The
<firstterm>NEVER
</firstterm> mode
7555 never includes
<literal>CONTEXT
</literal>, while
<firstterm>ALWAYS
</firstterm> always
7556 includes it if available. In
<firstterm>ERRORS
</firstterm> mode (the
7557 default),
<literal>CONTEXT
</literal> fields are included only in error
7558 messages, not in notices and warnings.
7559 (However, if the verbosity setting is
<firstterm>TERSE
</firstterm>
7560 or
<firstterm>SQLSTATE
</firstterm>,
<literal>CONTEXT
</literal> fields
7561 are omitted regardless of the context display mode.)
7565 Changing this mode does not
7566 affect the messages available from
7567 already-existing
<structname>PGresult
</structname> objects, only
7568 subsequently-created ones.
7569 (But see
<xref linkend=
"libpq-PQresultVerboseErrorMessage"/> if you
7570 want to print a previous error with a different display mode.)
7575 <varlistentry id=
"libpq-PQtrace">
7576 <term><function>PQtrace
</function><indexterm><primary>PQtrace
</primary></indexterm></term>
7580 Enables tracing of the client/server communication to a debugging file
7583 void PQtrace(PGconn *conn, FILE *stream);
7588 Each line consists of: an optional timestamp, a direction indicator
7589 (
<literal>F
</literal> for messages from client to server
7590 or
<literal>B
</literal> for messages from server to client),
7591 message length, message type, and message contents.
7592 Non-message contents fields (timestamp, direction, length and message type)
7593 are separated by a tab. Message contents are separated by a space.
7594 Protocol strings are enclosed in double quotes, while strings used as data
7595 values are enclosed in single quotes. Non-printable chars are printed as
7596 hexadecimal escapes.
7597 Further message-type-specific detail can be found in
7598 <xref linkend=
"protocol-message-formats"/>.
7603 On Windows, if the
<application>libpq
</application> library and an application are
7604 compiled with different flags, this function call will crash the
7605 application because the internal representation of the
<literal>FILE
</literal>
7606 pointers differ. Specifically, multithreaded/single-threaded,
7607 release/debug, and static/dynamic flags should be the same for the
7608 library and all applications using that library.
7615 <varlistentry id=
"libpq-PQsetTraceFlags">
7616 <term><function>PQsetTraceFlags
</function><indexterm><primary>PQsetTraceFlags
</primary></indexterm></term>
7620 Controls the tracing behavior of client/server communication.
7622 void PQsetTraceFlags(PGconn *conn, int flags);
7627 <literal>flags
</literal> contains flag bits describing the operating mode
7629 If
<literal>flags
</literal> contains
<literal>PQTRACE_SUPPRESS_TIMESTAMPS
</literal>,
7630 then the timestamp is not included when printing each message.
7631 If
<literal>flags
</literal> contains
<literal>PQTRACE_REGRESS_MODE
</literal>,
7632 then some fields are redacted when printing each message, such as object
7633 OIDs, to make the output more convenient to use in testing frameworks.
7634 This function must be called after calling
<function>PQtrace
</function>.
7640 <varlistentry id=
"libpq-PQuntrace">
7641 <term><function>PQuntrace
</function><indexterm><primary>PQuntrace
</primary></indexterm></term>
7645 Disables tracing started by
<xref linkend=
"libpq-PQtrace"/>.
7647 void PQuntrace(PGconn *conn);
7656 <sect1 id=
"libpq-misc">
7657 <title>Miscellaneous Functions
</title>
7660 As always, there are some functions that just don't fit anywhere.
7664 <varlistentry id=
"libpq-PQfreemem">
7665 <term><function>PQfreemem
</function><indexterm><primary>PQfreemem
</primary></indexterm></term>
7669 Frees memory allocated by
<application>libpq
</application>.
7671 void PQfreemem(void *ptr);
7676 Frees memory allocated by
<application>libpq
</application>, particularly
7677 <xref linkend=
"libpq-PQescapeByteaConn"/>,
7678 <xref linkend=
"libpq-PQescapeBytea"/>,
7679 <xref linkend=
"libpq-PQunescapeBytea"/>,
7680 and
<function>PQnotifies
</function>.
7681 It is particularly important that this function, rather than
7682 <function>free()
</function>, be used on Microsoft Windows. This is because
7683 allocating memory in a DLL and releasing it in the application works
7684 only if multithreaded/single-threaded, release/debug, and static/dynamic
7685 flags are the same for the DLL and the application. On non-Microsoft
7686 Windows platforms, this function is the same as the standard library
7687 function
<function>free()
</function>.
7692 <varlistentry id=
"libpq-PQconninfoFree">
7693 <term><function>PQconninfoFree
</function><indexterm><primary>PQconninfoFree
</primary></indexterm></term>
7697 Frees the data structures allocated by
7698 <xref linkend=
"libpq-PQconndefaults"/> or
<xref linkend=
"libpq-PQconninfoParse"/>.
7700 void PQconninfoFree(PQconninfoOption *connOptions);
7702 If the argument is a
<symbol>NULL
</symbol> pointer, no operation is
7707 A simple
<xref linkend=
"libpq-PQfreemem"/> will not do for this, since
7708 the array contains references to subsidiary strings.
7713 <varlistentry id=
"libpq-PQencryptPasswordConn">
7714 <term><function>PQencryptPasswordConn
</function><indexterm><primary>PQencryptPasswordConn
</primary></indexterm></term>
7718 Prepares the encrypted form of a
<productname>PostgreSQL
</productname> password.
7720 char *PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm);
7722 This function is intended to be used by client applications that
7723 wish to send commands like
<literal>ALTER USER joe PASSWORD
7724 'pwd'
</literal>. It is good practice not to send the original cleartext
7725 password in such a command, because it might be exposed in command
7726 logs, activity displays, and so on. Instead, use this function to
7727 convert the password to encrypted form before it is sent.
7731 The
<parameter>passwd
</parameter> and
<parameter>user
</parameter> arguments
7732 are the cleartext password, and the SQL name of the user it is for.
7733 <parameter>algorithm
</parameter> specifies the encryption algorithm
7734 to use to encrypt the password. Currently supported algorithms are
7735 <literal>md5
</literal> and
<literal>scram-sha-
256</literal> (
<literal>on
</literal> and
7736 <literal>off
</literal> are also accepted as aliases for
<literal>md5
</literal>, for
7737 compatibility with older server versions). Note that support for
7738 <literal>scram-sha-
256</literal> was introduced in
<productname>PostgreSQL
</productname>
7739 version
10, and will not work correctly with older server versions. If
7740 <parameter>algorithm
</parameter> is
<symbol>NULL
</symbol>, this function will query
7741 the server for the current value of the
7742 <xref linkend=
"guc-password-encryption"/> setting. That can block, and
7743 will fail if the current transaction is aborted, or if the connection
7744 is busy executing another query. If you wish to use the default
7745 algorithm for the server but want to avoid blocking, query
7746 <varname>password_encryption
</varname> yourself before calling
7747 <xref linkend=
"libpq-PQencryptPasswordConn"/>, and pass that value as the
7748 <parameter>algorithm
</parameter>.
7752 The return value is a string allocated by
<function>malloc
</function>.
7753 The caller can assume the string doesn't contain any special characters
7754 that would require escaping. Use
<xref linkend=
"libpq-PQfreemem"/> to free the
7755 result when done with it. On error, returns
<symbol>NULL
</symbol>, and
7756 a suitable message is stored in the connection object.
7762 <varlistentry id=
"libpq-PQchangePassword">
7763 <term><function>PQchangePassword
</function><indexterm><primary>PQchangePassword
</primary></indexterm></term>
7767 Changes a
<productname>PostgreSQL
</productname> password.
7769 PGresult *PQchangePassword(PGconn *conn, const char *user, const char *passwd);
7771 This function uses
<function>PQencryptPasswordConn
</function>
7772 to build and execute the command
<literal>ALTER USER ... PASSWORD
7773 '...'
</literal>, thereby changing the user's password. It exists for
7774 the same reason as
<function>PQencryptPasswordConn
</function>, but
7775 is more convenient as it both builds and runs the command for you.
7776 <xref linkend=
"libpq-PQencryptPasswordConn"/> is passed a
7777 <symbol>NULL
</symbol> for the algorithm argument, hence encryption is
7778 done according to the server's
<xref linkend=
"guc-password-encryption"/>
7783 The
<parameter>user
</parameter> and
<parameter>passwd
</parameter> arguments
7784 are the SQL name of the target user, and the new cleartext password.
7788 Returns a
<structname>PGresult
</structname> pointer representing
7789 the result of the
<literal>ALTER USER
</literal> command, or
7790 a null pointer if the routine failed before issuing any command.
7791 The
<xref linkend=
"libpq-PQresultStatus"/> function should be called
7792 to check the return value for any errors (including the value of a null
7793 pointer, in which case it will return
7794 <symbol>PGRES_FATAL_ERROR
</symbol>). Use
7795 <xref linkend=
"libpq-PQerrorMessage"/> to get more information about
7801 <varlistentry id=
"libpq-PQencryptPassword">
7802 <term><function>PQencryptPassword
</function><indexterm><primary>PQencryptPassword
</primary></indexterm></term>
7806 Prepares the md5-encrypted form of a
<productname>PostgreSQL
</productname> password.
7808 char *PQencryptPassword(const char *passwd, const char *user);
7810 <xref linkend=
"libpq-PQencryptPassword"/> is an older, deprecated version of
7811 <xref linkend=
"libpq-PQencryptPasswordConn"/>. The difference is that
7812 <xref linkend=
"libpq-PQencryptPassword"/> does not
7813 require a connection object, and
<literal>md5
</literal> is always used as the
7814 encryption algorithm.
7819 <varlistentry id=
"libpq-PQmakeEmptyPGresult">
7820 <term><function>PQmakeEmptyPGresult
</function><indexterm><primary>PQmakeEmptyPGresult
</primary></indexterm></term>
7824 Constructs an empty
<structname>PGresult
</structname> object with the given status.
7826 PGresult *PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status);
7831 This is
<application>libpq
</application>'s internal function to allocate and
7832 initialize an empty
<structname>PGresult
</structname> object. This
7833 function returns
<symbol>NULL
</symbol> if memory could not be allocated. It is
7834 exported because some applications find it useful to generate result
7835 objects (particularly objects with error status) themselves. If
7836 <parameter>conn
</parameter> is not null and
<parameter>status
</parameter>
7837 indicates an error, the current error message of the specified
7838 connection is copied into the
<structname>PGresult
</structname>.
7839 Also, if
<parameter>conn
</parameter> is not null, any event procedures
7840 registered in the connection are copied into the
7841 <structname>PGresult
</structname>. (They do not get
7842 <literal>PGEVT_RESULTCREATE
</literal> calls, but see
7843 <xref linkend=
"libpq-PQfireResultCreateEvents"/>.)
7844 Note that
<xref linkend=
"libpq-PQclear"/> should eventually be called
7845 on the object, just as with a
<structname>PGresult
</structname>
7846 returned by
<application>libpq
</application> itself.
7851 <varlistentry id=
"libpq-PQfireResultCreateEvents">
7852 <term><function>PQfireResultCreateEvents
</function><indexterm><primary>PQfireResultCreateEvents
</primary></indexterm></term>
7855 Fires a
<literal>PGEVT_RESULTCREATE
</literal> event (see
<xref
7856 linkend=
"libpq-events"/>) for each event procedure registered in the
7857 <structname>PGresult
</structname> object. Returns non-zero for success,
7858 zero if any event procedure fails.
7861 int PQfireResultCreateEvents(PGconn *conn, PGresult *res);
7866 The
<literal>conn
</literal> argument is passed through to event procedures
7867 but not used directly. It can be
<symbol>NULL
</symbol> if the event
7868 procedures won't use it.
7872 Event procedures that have already received a
7873 <literal>PGEVT_RESULTCREATE
</literal> or
<literal>PGEVT_RESULTCOPY
</literal> event
7874 for this object are not fired again.
7878 The main reason that this function is separate from
7879 <xref linkend=
"libpq-PQmakeEmptyPGresult"/> is that it is often appropriate
7880 to create a
<structname>PGresult
</structname> and fill it with data
7881 before invoking the event procedures.
7886 <varlistentry id=
"libpq-PQcopyResult">
7887 <term><function>PQcopyResult
</function><indexterm><primary>PQcopyResult
</primary></indexterm></term>
7891 Makes a copy of a
<structname>PGresult
</structname> object. The copy is
7892 not linked to the source result in any way and
7893 <xref linkend=
"libpq-PQclear"/> must be called when the copy is no longer
7894 needed. If the function fails,
<symbol>NULL
</symbol> is returned.
7897 PGresult *PQcopyResult(const PGresult *src, int flags);
7902 This is not intended to make an exact copy. The returned result is
7903 always put into
<literal>PGRES_TUPLES_OK
</literal> status, and does not
7904 copy any error message in the source. (It does copy the command status
7905 string, however.) The
<parameter>flags
</parameter> argument determines
7906 what else is copied. It is a bitwise OR of several flags.
7907 <literal>PG_COPYRES_ATTRS
</literal> specifies copying the source
7908 result's attributes (column definitions).
7909 <literal>PG_COPYRES_TUPLES
</literal> specifies copying the source
7910 result's tuples. (This implies copying the attributes, too.)
7911 <literal>PG_COPYRES_NOTICEHOOKS
</literal> specifies
7912 copying the source result's notify hooks.
7913 <literal>PG_COPYRES_EVENTS
</literal> specifies copying the source
7914 result's events. (But any instance data associated with the source
7916 The event procedures receive
<literal>PGEVT_RESULTCOPY
</literal> events.
7921 <varlistentry id=
"libpq-PQsetResultAttrs">
7922 <term><function>PQsetResultAttrs
</function><indexterm><primary>PQsetResultAttrs
</primary></indexterm></term>
7926 Sets the attributes of a
<structname>PGresult
</structname> object.
7928 int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs);
7933 The provided
<parameter>attDescs
</parameter> are copied into the result.
7934 If the
<parameter>attDescs
</parameter> pointer is
<symbol>NULL
</symbol> or
7935 <parameter>numAttributes
</parameter> is less than one, the request is
7936 ignored and the function succeeds. If
<parameter>res
</parameter>
7937 already contains attributes, the function will fail. If the function
7938 fails, the return value is zero. If the function succeeds, the return
7944 <varlistentry id=
"libpq-PQsetvalue">
7945 <term><function>PQsetvalue
</function><indexterm><primary>PQsetvalue
</primary></indexterm></term>
7949 Sets a tuple field value of a
<structname>PGresult
</structname> object.
7951 int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len);
7956 The function will automatically grow the result's internal tuples array
7957 as needed. However, the
<parameter>tup_num
</parameter> argument must be
7958 less than or equal to
<xref linkend=
"libpq-PQntuples"/>, meaning this
7959 function can only grow the tuples array one tuple at a time. But any
7960 field of any existing tuple can be modified in any order. If a value at
7961 <parameter>field_num
</parameter> already exists, it will be overwritten.
7962 If
<parameter>len
</parameter> is -
1 or
7963 <parameter>value
</parameter> is
<symbol>NULL
</symbol>, the field value
7964 will be set to an SQL null value. The
7965 <parameter>value
</parameter> is copied into the result's private storage,
7966 thus is no longer needed after the function
7967 returns. If the function fails, the return value is zero. If the
7968 function succeeds, the return value is non-zero.
7973 <varlistentry id=
"libpq-PQresultAlloc">
7974 <term><function>PQresultAlloc
</function><indexterm><primary>PQresultAlloc
</primary></indexterm></term>
7978 Allocate subsidiary storage for a
<structname>PGresult
</structname> object.
7980 void *PQresultAlloc(PGresult *res, size_t nBytes);
7985 Any memory allocated with this function will be freed when
7986 <parameter>res
</parameter> is cleared. If the function fails,
7987 the return value is
<symbol>NULL
</symbol>. The result is
7988 guaranteed to be adequately aligned for any type of data,
7989 just as for
<function>malloc
</function>.
7994 <varlistentry id=
"libpq-PQresultMemorySize">
7995 <term><function>PQresultMemorySize
</function><indexterm><primary>PQresultMemorySize
</primary></indexterm></term>
7999 Retrieves the number of bytes allocated for
8000 a
<structname>PGresult
</structname> object.
8002 size_t PQresultMemorySize(const PGresult *res);
8007 This value is the sum of all
<function>malloc
</function> requests
8008 associated with the
<structname>PGresult
</structname> object, that is,
8009 all the memory that will be freed by
<xref linkend=
"libpq-PQclear"/>.
8010 This information can be useful for managing memory consumption.
8015 <varlistentry id=
"libpq-PQlibVersion">
8016 <term><function>PQlibVersion
</function><indexterm
8017 ><primary>PQlibVersion
</primary><seealso>PQserverVersion
</seealso></indexterm></term>
8021 Return the version of
<productname>libpq
</productname> that is being used.
8023 int PQlibVersion(void);
8028 The result of this function can be used to determine, at
8029 run time, whether specific functionality is available in the currently
8030 loaded version of libpq. The function can be used, for example,
8031 to determine which connection options are available in
8032 <xref linkend=
"libpq-PQconnectdb"/>.
8036 The result is formed by multiplying the library's major version
8037 number by
10000 and adding the minor version number. For example,
8038 version
10.1 will be returned as
100001, and version
11.0 will be
8043 Prior to major version
10,
<productname>PostgreSQL
</productname> used
8044 three-part version numbers in which the first two parts together
8045 represented the major version. For those
8046 versions,
<xref linkend=
"libpq-PQlibVersion"/> uses two digits for each
8047 part; for example version
9.1.5 will be returned as
90105, and
8048 version
9.2.0 will be returned as
90200.
8052 Therefore, for purposes of determining feature compatibility,
8053 applications should divide the result of
<xref linkend=
"libpq-PQlibVersion"/>
8054 by
100 not
10000 to determine a logical major version number.
8055 In all release series, only the last two digits differ between
8056 minor releases (bug-fix releases).
8061 This function appeared in
<productname>PostgreSQL
</productname> version
9.1, so
8062 it cannot be used to detect required functionality in earlier
8063 versions, since calling it will create a link dependency
8064 on version
9.1 or later.
8070 <varlistentry id=
"libpq-PQgetCurrentTimeUSec">
8071 <term><function>PQgetCurrentTimeUSec
</function><indexterm><primary>PQgetCurrentTimeUSec
</primary></indexterm></term>
8075 Retrieves the current time, expressed as the number of microseconds
8076 since the Unix epoch (that is,
<type>time_t
</type> times
1 million).
8078 pg_usec_time_t PQgetCurrentTimeUSec(void);
8083 This is primarily useful for calculating timeout values to use with
8084 <xref linkend=
"libpq-PQsocketPoll"/>.
8093 <sect1 id=
"libpq-notice-processing">
8094 <title>Notice Processing
</title>
8096 <indexterm zone=
"libpq-notice-processing">
8097 <primary>notice processing
</primary>
8098 <secondary>in libpq
</secondary>
8102 Notice and warning messages generated by the server are not returned
8103 by the query execution functions, since they do not imply failure of
8104 the query. Instead they are passed to a notice handling function, and
8105 execution continues normally after the handler returns. The default
8106 notice handling function prints the message on
8107 <filename>stderr
</filename>, but the application can override this
8108 behavior by supplying its own handling function.
8112 For historical reasons, there are two levels of notice handling, called
8113 the notice receiver and notice processor. The default behavior is for
8114 the notice receiver to format the notice and pass a string to the notice
8115 processor for printing. However, an application that chooses to provide
8116 its own notice receiver will typically ignore the notice processor
8117 layer and just do all the work in the notice receiver.
8121 The function
<function id=
"libpq-PQsetNoticeReceiver">PQsetNoticeReceiver
</function>
8122 <indexterm><primary>notice receiver
</primary></indexterm>
8123 <indexterm><primary>PQsetNoticeReceiver
</primary></indexterm> sets or
8124 examines the current notice receiver for a connection object.
8125 Similarly,
<function id=
"libpq-PQsetNoticeProcessor">PQsetNoticeProcessor
</function>
8126 <indexterm><primary>notice processor
</primary></indexterm>
8127 <indexterm><primary>PQsetNoticeProcessor
</primary></indexterm> sets or
8128 examines the current notice processor.
8131 typedef void (*PQnoticeReceiver) (void *arg, const PGresult *res);
8134 PQsetNoticeReceiver(PGconn *conn,
8135 PQnoticeReceiver proc,
8138 typedef void (*PQnoticeProcessor) (void *arg, const char *message);
8141 PQsetNoticeProcessor(PGconn *conn,
8142 PQnoticeProcessor proc,
8146 Each of these functions returns the previous notice receiver or
8147 processor function pointer, and sets the new value. If you supply a
8148 null function pointer, no action is taken, but the current pointer is
8153 When a notice or warning message is received from the server, or
8154 generated internally by
<application>libpq
</application>, the notice
8155 receiver function is called. It is passed the message in the form of
8156 a
<symbol>PGRES_NONFATAL_ERROR
</symbol>
8157 <structname>PGresult
</structname>. (This allows the receiver to extract
8158 individual fields using
<xref linkend=
"libpq-PQresultErrorField"/>, or obtain a
8159 complete preformatted message using
<xref linkend=
"libpq-PQresultErrorMessage"/>
8160 or
<xref linkend=
"libpq-PQresultVerboseErrorMessage"/>.) The same
8161 void pointer passed to
<function>PQsetNoticeReceiver
</function> is also
8162 passed. (This pointer can be used to access application-specific state
8167 The default notice receiver simply extracts the message (using
8168 <xref linkend=
"libpq-PQresultErrorMessage"/>) and passes it to the notice
8173 The notice processor is responsible for handling a notice or warning
8174 message given in text form. It is passed the string text of the message
8175 (including a trailing newline), plus a void pointer that is the same
8176 one passed to
<function>PQsetNoticeProcessor
</function>. (This pointer
8177 can be used to access application-specific state if needed.)
8181 The default notice processor is simply:
8184 defaultNoticeProcessor(void *arg, const char *message)
8186 fprintf(stderr,
"%s", message);
8192 Once you have set a notice receiver or processor, you should expect
8193 that that function could be called as long as either the
8194 <structname>PGconn
</structname> object or
<structname>PGresult
</structname> objects made
8195 from it exist. At creation of a
<structname>PGresult
</structname>, the
8196 <structname>PGconn
</structname>'s current notice handling pointers are copied
8197 into the
<structname>PGresult
</structname> for possible use by functions like
8198 <xref linkend=
"libpq-PQgetvalue"/>.
8203 <sect1 id=
"libpq-events">
8204 <title>Event System
</title>
8207 <application>libpq
</application>'s event system is designed to notify
8208 registered event handlers about interesting
8209 <application>libpq
</application> events, such as the creation or
8210 destruction of
<structname>PGconn
</structname> and
8211 <structname>PGresult
</structname> objects. A principal use case is that
8212 this allows applications to associate their own data with a
8213 <structname>PGconn
</structname> or
<structname>PGresult
</structname>
8214 and ensure that that data is freed at an appropriate time.
8218 Each registered event handler is associated with two pieces of data,
8219 known to
<application>libpq
</application> only as opaque
<literal>void *
</literal>
8220 pointers. There is a
<firstterm>pass-through
</firstterm> pointer that is provided
8221 by the application when the event handler is registered with a
8222 <structname>PGconn
</structname>. The pass-through pointer never changes for the
8223 life of the
<structname>PGconn
</structname> and all
<structname>PGresult
</structname>s
8224 generated from it; so if used, it must point to long-lived data.
8225 In addition there is an
<firstterm>instance data
</firstterm> pointer, which starts
8226 out
<symbol>NULL
</symbol> in every
<structname>PGconn
</structname> and
<structname>PGresult
</structname>.
8227 This pointer can be manipulated using the
8228 <xref linkend=
"libpq-PQinstanceData"/>,
8229 <xref linkend=
"libpq-PQsetInstanceData"/>,
8230 <xref linkend=
"libpq-PQresultInstanceData"/> and
8231 <xref linkend=
"libpq-PQresultSetInstanceData"/> functions. Note that
8232 unlike the pass-through pointer, instance data of a
<structname>PGconn
</structname>
8233 is not automatically inherited by
<structname>PGresult
</structname>s created from
8234 it.
<application>libpq
</application> does not know what pass-through
8235 and instance data pointers point to (if anything) and will never attempt
8236 to free them
— that is the responsibility of the event handler.
8239 <sect2 id=
"libpq-events-types">
8240 <title>Event Types
</title>
8243 The enum
<literal>PGEventId
</literal> names the types of events handled by
8244 the event system. All its values have names beginning with
8245 <literal>PGEVT
</literal>. For each event type, there is a corresponding
8246 event info structure that carries the parameters passed to the event
8247 handlers. The event types are:
8251 <varlistentry id=
"libpq-pgevt-register">
8252 <term><literal>PGEVT_REGISTER
</literal></term>
8255 The register event occurs when
<xref linkend=
"libpq-PQregisterEventProc"/>
8256 is called. It is the ideal time to initialize any
8257 <literal>instanceData
</literal> an event procedure may need. Only one
8258 register event will be fired per event handler per connection. If the
8259 event procedure fails (returns zero), the registration is canceled.
8268 When a
<literal>PGEVT_REGISTER
</literal> event is received, the
8269 <parameter>evtInfo
</parameter> pointer should be cast to a
8270 <structname>PGEventRegister *
</structname>. This structure contains a
8271 <structname>PGconn
</structname> that should be in the
8272 <literal>CONNECTION_OK
</literal> status; guaranteed if one calls
8273 <xref linkend=
"libpq-PQregisterEventProc"/> right after obtaining a good
8274 <structname>PGconn
</structname>. When returning a failure code, all
8275 cleanup must be performed as no
<literal>PGEVT_CONNDESTROY
</literal>
8281 <varlistentry id=
"libpq-pgevt-connreset">
8282 <term><literal>PGEVT_CONNRESET
</literal></term>
8285 The connection reset event is fired on completion of
8286 <xref linkend=
"libpq-PQreset"/> or
<function>PQresetPoll
</function>. In
8287 both cases, the event is only fired if the reset was successful.
8288 The return value of the event procedure is ignored
8289 in
<productname>PostgreSQL
</productname> v15 and later.
8290 With earlier versions, however, it's important to return success
8291 (nonzero) or the connection will be aborted.
8300 When a
<literal>PGEVT_CONNRESET
</literal> event is received, the
8301 <parameter>evtInfo
</parameter> pointer should be cast to a
8302 <structname>PGEventConnReset *
</structname>. Although the contained
8303 <structname>PGconn
</structname> was just reset, all event data remains
8304 unchanged. This event should be used to reset/reload/requery any
8305 associated
<literal>instanceData
</literal>. Note that even if the
8306 event procedure fails to process
<literal>PGEVT_CONNRESET
</literal>, it will
8307 still receive a
<literal>PGEVT_CONNDESTROY
</literal> event when the connection
8313 <varlistentry id=
"libpq-pgevt-conndestroy">
8314 <term><literal>PGEVT_CONNDESTROY
</literal></term>
8317 The connection destroy event is fired in response to
8318 <xref linkend=
"libpq-PQfinish"/>. It is the event procedure's
8319 responsibility to properly clean up its event data as libpq has no
8320 ability to manage this memory. Failure to clean up will lead
8327 } PGEventConnDestroy;
8330 When a
<literal>PGEVT_CONNDESTROY
</literal> event is received, the
8331 <parameter>evtInfo
</parameter> pointer should be cast to a
8332 <structname>PGEventConnDestroy *
</structname>. This event is fired
8333 prior to
<xref linkend=
"libpq-PQfinish"/> performing any other cleanup.
8334 The return value of the event procedure is ignored since there is no
8335 way of indicating a failure from
<xref linkend=
"libpq-PQfinish"/>. Also,
8336 an event procedure failure should not abort the process of cleaning up
8342 <varlistentry id=
"libpq-pgevt-resultcreate">
8343 <term><literal>PGEVT_RESULTCREATE
</literal></term>
8346 The result creation event is fired in response to any query execution
8347 function that generates a result, including
8348 <xref linkend=
"libpq-PQgetResult"/>. This event will only be fired after
8349 the result has been created successfully.
8356 } PGEventResultCreate;
8359 When a
<literal>PGEVT_RESULTCREATE
</literal> event is received, the
8360 <parameter>evtInfo
</parameter> pointer should be cast to a
8361 <structname>PGEventResultCreate *
</structname>. The
8362 <parameter>conn
</parameter> is the connection used to generate the
8363 result. This is the ideal place to initialize any
8364 <literal>instanceData
</literal> that needs to be associated with the
8365 result. If an event procedure fails (returns zero), that event
8366 procedure will be ignored for the remaining lifetime of the result;
8367 that is, it will not receive
<literal>PGEVT_RESULTCOPY
</literal>
8368 or
<literal>PGEVT_RESULTDESTROY
</literal> events for this result or
8369 results copied from it.
8374 <varlistentry id=
"libpq-pgevt-resultcopy">
8375 <term><literal>PGEVT_RESULTCOPY
</literal></term>
8378 The result copy event is fired in response to
8379 <xref linkend=
"libpq-PQcopyResult"/>. This event will only be fired after
8380 the copy is complete. Only event procedures that have
8381 successfully handled the
<literal>PGEVT_RESULTCREATE
</literal>
8382 or
<literal>PGEVT_RESULTCOPY
</literal> event for the source result
8383 will receive
<literal>PGEVT_RESULTCOPY
</literal> events.
8388 const PGresult *src;
8390 } PGEventResultCopy;
8393 When a
<literal>PGEVT_RESULTCOPY
</literal> event is received, the
8394 <parameter>evtInfo
</parameter> pointer should be cast to a
8395 <structname>PGEventResultCopy *
</structname>. The
8396 <parameter>src
</parameter> result is what was copied while the
8397 <parameter>dest
</parameter> result is the copy destination. This event
8398 can be used to provide a deep copy of
<literal>instanceData
</literal>,
8399 since
<literal>PQcopyResult
</literal> cannot do that. If an event
8400 procedure fails (returns zero), that event procedure will be
8401 ignored for the remaining lifetime of the new result; that is, it
8402 will not receive
<literal>PGEVT_RESULTCOPY
</literal>
8403 or
<literal>PGEVT_RESULTDESTROY
</literal> events for that result or
8404 results copied from it.
8409 <varlistentry id=
"libpq-pgevt-resultdestroy">
8410 <term><literal>PGEVT_RESULTDESTROY
</literal></term>
8413 The result destroy event is fired in response to a
8414 <xref linkend=
"libpq-PQclear"/>. It is the event procedure's
8415 responsibility to properly clean up its event data as libpq has no
8416 ability to manage this memory. Failure to clean up will lead
8423 } PGEventResultDestroy;
8426 When a
<literal>PGEVT_RESULTDESTROY
</literal> event is received, the
8427 <parameter>evtInfo
</parameter> pointer should be cast to a
8428 <structname>PGEventResultDestroy *
</structname>. This event is fired
8429 prior to
<xref linkend=
"libpq-PQclear"/> performing any other cleanup.
8430 The return value of the event procedure is ignored since there is no
8431 way of indicating a failure from
<xref linkend=
"libpq-PQclear"/>. Also,
8432 an event procedure failure should not abort the process of cleaning up
8440 <sect2 id=
"libpq-events-proc">
8441 <title>Event Callback Procedure
</title>
8444 <varlistentry id=
"libpq-PGEventProc">
8445 <term><literal>PGEventProc
</literal><indexterm><primary>PGEventProc
</primary></indexterm></term>
8449 <literal>PGEventProc
</literal> is a typedef for a pointer to an
8450 event procedure, that is, the user callback function that receives
8451 events from libpq. The signature of an event procedure must be
8454 int eventproc(PGEventId evtId, void *evtInfo, void *passThrough)
8457 The
<parameter>evtId
</parameter> parameter indicates which
8458 <literal>PGEVT
</literal> event occurred. The
8459 <parameter>evtInfo
</parameter> pointer must be cast to the appropriate
8460 structure type to obtain further information about the event.
8461 The
<parameter>passThrough
</parameter> parameter is the pointer
8462 provided to
<xref linkend=
"libpq-PQregisterEventProc"/> when the event
8463 procedure was registered. The function should return a non-zero value
8464 if it succeeds and zero if it fails.
8468 A particular event procedure can be registered only once in any
8469 <structname>PGconn
</structname>. This is because the address of the procedure
8470 is used as a lookup key to identify the associated instance data.
8475 On Windows, functions can have two different addresses: one visible
8476 from outside a DLL and another visible from inside the DLL. One
8477 should be careful that only one of these addresses is used with
8478 <application>libpq
</application>'s event-procedure functions, else confusion will
8479 result. The simplest rule for writing code that will work is to
8480 ensure that event procedures are declared
<literal>static
</literal>. If the
8481 procedure's address must be available outside its own source file,
8482 expose a separate function to return the address.
8490 <sect2 id=
"libpq-events-funcs">
8491 <title>Event Support Functions
</title>
8494 <varlistentry id=
"libpq-PQregisterEventProc">
8495 <term><function>PQregisterEventProc
</function><indexterm><primary>PQregisterEventProc
</primary></indexterm></term>
8499 Registers an event callback procedure with libpq.
8502 int PQregisterEventProc(PGconn *conn, PGEventProc proc,
8503 const char *name, void *passThrough);
8508 An event procedure must be registered once on each
8509 <structname>PGconn
</structname> you want to receive events about. There is no
8510 limit, other than memory, on the number of event procedures that
8511 can be registered with a connection. The function returns a non-zero
8512 value if it succeeds and zero if it fails.
8516 The
<parameter>proc
</parameter> argument will be called when a libpq
8517 event is fired. Its memory address is also used to lookup
8518 <literal>instanceData
</literal>. The
<parameter>name
</parameter>
8519 argument is used to refer to the event procedure in error messages.
8520 This value cannot be
<symbol>NULL
</symbol> or a zero-length string. The name string is
8521 copied into the
<structname>PGconn
</structname>, so what is passed need not be
8522 long-lived. The
<parameter>passThrough
</parameter> pointer is passed
8523 to the
<parameter>proc
</parameter> whenever an event occurs. This
8524 argument can be
<symbol>NULL
</symbol>.
8529 <varlistentry id=
"libpq-PQsetInstanceData">
8530 <term><function>PQsetInstanceData
</function><indexterm><primary>PQsetInstanceData
</primary></indexterm></term>
8533 Sets the connection
<parameter>conn
</parameter>'s
<literal>instanceData
</literal>
8534 for procedure
<parameter>proc
</parameter> to
<parameter>data
</parameter>. This
8535 returns non-zero for success and zero for failure. (Failure is
8536 only possible if
<parameter>proc
</parameter> has not been properly
8537 registered in
<parameter>conn
</parameter>.)
8540 int PQsetInstanceData(PGconn *conn, PGEventProc proc, void *data);
8546 <varlistentry id=
"libpq-PQinstanceData">
8547 <term><function>PQinstanceData
</function><indexterm><primary>PQinstanceData
</primary></indexterm></term>
8551 connection
<parameter>conn
</parameter>'s
<literal>instanceData
</literal>
8552 associated with procedure
<parameter>proc
</parameter>,
8553 or
<symbol>NULL
</symbol> if there is none.
8556 void *PQinstanceData(const PGconn *conn, PGEventProc proc);
8562 <varlistentry id=
"libpq-PQresultSetInstanceData">
8563 <term><function>PQresultSetInstanceData
</function><indexterm><primary>PQresultSetInstanceData
</primary></indexterm></term>
8566 Sets the result's
<literal>instanceData
</literal>
8567 for
<parameter>proc
</parameter> to
<parameter>data
</parameter>. This returns
8568 non-zero for success and zero for failure. (Failure is only
8569 possible if
<parameter>proc
</parameter> has not been properly registered
8573 int PQresultSetInstanceData(PGresult *res, PGEventProc proc, void *data);
8578 Beware that any storage represented by
<parameter>data
</parameter>
8579 will not be accounted for by
<xref linkend=
"libpq-PQresultMemorySize"/>,
8580 unless it is allocated using
<xref linkend=
"libpq-PQresultAlloc"/>.
8581 (Doing so is recommendable because it eliminates the need to free
8582 such storage explicitly when the result is destroyed.)
8587 <varlistentry id=
"libpq-PQresultInstanceData">
8588 <term><function>PQresultInstanceData
</function><indexterm><primary>PQresultInstanceData
</primary></indexterm></term>
8591 Returns the result's
<literal>instanceData
</literal> associated with
<parameter>proc
</parameter>, or
<symbol>NULL
</symbol>
8595 void *PQresultInstanceData(const PGresult *res, PGEventProc proc);
8603 <sect2 id=
"libpq-events-example">
8604 <title>Event Example
</title>
8607 Here is a skeleton example of managing private data associated with
8608 libpq connections and results.
8613 /* required header for libpq events (note: includes libpq-fe.h) */
8614 #include
<libpq-events.h
>
8616 /* The instanceData */
8624 static int myEventProc(PGEventId evtId, void *evtInfo, void *passThrough);
8632 PQconnectdb(
"dbname=postgres options=-csearch_path=");
8634 if (PQstatus(conn) != CONNECTION_OK)
8636 /* PQerrorMessage's result includes a trailing newline */
8637 fprintf(stderr,
"%s", PQerrorMessage(conn));
8642 /* called once on any connection that should receive events.
8643 * Sends a PGEVT_REGISTER to myEventProc.
8645 if (!PQregisterEventProc(conn, myEventProc,
"mydata_proc", NULL))
8647 fprintf(stderr,
"Cannot register PGEventProc\n");
8652 /* conn instanceData is available */
8653 data = PQinstanceData(conn, myEventProc);
8655 /* Sends a PGEVT_RESULTCREATE to myEventProc */
8656 res = PQexec(conn,
"SELECT 1 + 1");
8658 /* result instanceData is available */
8659 data = PQresultInstanceData(res, myEventProc);
8661 /* If PG_COPYRES_EVENTS is used, sends a PGEVT_RESULTCOPY to myEventProc */
8662 res_copy = PQcopyResult(res, PG_COPYRES_TUPLES | PG_COPYRES_EVENTS);
8664 /* result instanceData is available if PG_COPYRES_EVENTS was
8665 * used during the PQcopyResult call.
8667 data = PQresultInstanceData(res_copy, myEventProc);
8669 /* Both clears send a PGEVT_RESULTDESTROY to myEventProc */
8673 /* Sends a PGEVT_CONNDESTROY to myEventProc */
8680 myEventProc(PGEventId evtId, void *evtInfo, void *passThrough)
8684 case PGEVT_REGISTER:
8686 PGEventRegister *e = (PGEventRegister *)evtInfo;
8687 mydata *data = get_mydata(e-
>conn);
8689 /* associate app specific data with connection */
8690 PQsetInstanceData(e-
>conn, myEventProc, data);
8694 case PGEVT_CONNRESET:
8696 PGEventConnReset *e = (PGEventConnReset *)evtInfo;
8697 mydata *data = PQinstanceData(e-
>conn, myEventProc);
8700 memset(data,
0, sizeof(mydata));
8704 case PGEVT_CONNDESTROY:
8706 PGEventConnDestroy *e = (PGEventConnDestroy *)evtInfo;
8707 mydata *data = PQinstanceData(e-
>conn, myEventProc);
8709 /* free instance data because the conn is being destroyed */
8715 case PGEVT_RESULTCREATE:
8717 PGEventResultCreate *e = (PGEventResultCreate *)evtInfo;
8718 mydata *conn_data = PQinstanceData(e-
>conn, myEventProc);
8719 mydata *res_data = dup_mydata(conn_data);
8721 /* associate app specific data with result (copy it from conn) */
8722 PQresultSetInstanceData(e-
>result, myEventProc, res_data);
8726 case PGEVT_RESULTCOPY:
8728 PGEventResultCopy *e = (PGEventResultCopy *)evtInfo;
8729 mydata *src_data = PQresultInstanceData(e-
>src, myEventProc);
8730 mydata *dest_data = dup_mydata(src_data);
8732 /* associate app specific data with result (copy it from a result) */
8733 PQresultSetInstanceData(e-
>dest, myEventProc, dest_data);
8737 case PGEVT_RESULTDESTROY:
8739 PGEventResultDestroy *e = (PGEventResultDestroy *)evtInfo;
8740 mydata *data = PQresultInstanceData(e-
>result, myEventProc);
8742 /* free instance data because the result is being destroyed */
8748 /* unknown event ID, just return true. */
8753 return true; /* event processing succeeded */
8760 <sect1 id=
"libpq-envars">
8761 <title>Environment Variables
</title>
8763 <indexterm zone=
"libpq-envars">
8764 <primary>environment variable
</primary>
8768 The following environment variables can be used to select default
8769 connection parameter values, which will be used by
8770 <xref linkend=
"libpq-PQconnectdb"/>,
<xref linkend=
"libpq-PQsetdbLogin"/> and
8771 <xref linkend=
"libpq-PQsetdb"/> if no value is directly specified by the calling
8772 code. These are useful to avoid hard-coding database connection
8773 information into simple client applications, for example.
8779 <primary><envar>PGHOST
</envar></primary>
8781 <envar>PGHOST
</envar> behaves the same as the
<xref
8782 linkend=
"libpq-connect-host"/> connection parameter.
8789 <primary><envar>PGSSLNEGOTIATION
</envar></primary>
8791 <envar>PGSSLNEGOTIATION
</envar> behaves the same as the
<xref
8792 linkend=
"libpq-connect-sslnegotiation"/> connection parameter.
8799 <primary><envar>PGHOSTADDR
</envar></primary>
8801 <envar>PGHOSTADDR
</envar> behaves the same as the
<xref
8802 linkend=
"libpq-connect-hostaddr"/> connection parameter.
8803 This can be set instead of or in addition to
<envar>PGHOST
</envar>
8804 to avoid DNS lookup overhead.
8811 <primary><envar>PGPORT
</envar></primary>
8813 <envar>PGPORT
</envar> behaves the same as the
<xref
8814 linkend=
"libpq-connect-port"/> connection parameter.
8821 <primary><envar>PGDATABASE
</envar></primary>
8823 <envar>PGDATABASE
</envar> behaves the same as the
<xref
8824 linkend=
"libpq-connect-dbname"/> connection parameter.
8831 <primary><envar>PGUSER
</envar></primary>
8833 <envar>PGUSER
</envar> behaves the same as the
<xref
8834 linkend=
"libpq-connect-user"/> connection parameter.
8841 <primary><envar>PGPASSWORD
</envar></primary>
8843 <envar>PGPASSWORD
</envar> behaves the same as the
<xref
8844 linkend=
"libpq-connect-password"/> connection parameter.
8845 Use of this environment variable
8846 is not recommended for security reasons, as some operating systems
8847 allow non-root users to see process environment variables via
8848 <application>ps
</application>; instead consider using a password file
8849 (see
<xref linkend=
"libpq-pgpass"/>).
8856 <primary><envar>PGPASSFILE
</envar></primary>
8858 <envar>PGPASSFILE
</envar> behaves the same as the
<xref
8859 linkend=
"libpq-connect-passfile"/> connection parameter.
8866 <primary><envar>PGREQUIREAUTH
</envar></primary>
8868 <envar>PGREQUIREAUTH
</envar> behaves the same as the
<xref
8869 linkend=
"libpq-connect-require-auth"/> connection parameter.
8876 <primary><envar>PGCHANNELBINDING
</envar></primary>
8878 <envar>PGCHANNELBINDING
</envar> behaves the same as the
<xref
8879 linkend=
"libpq-connect-channel-binding"/> connection parameter.
8886 <primary><envar>PGSERVICE
</envar></primary>
8888 <envar>PGSERVICE
</envar> behaves the same as the
<xref
8889 linkend=
"libpq-connect-service"/> connection parameter.
8896 <primary><envar>PGSERVICEFILE
</envar></primary>
8898 <envar>PGSERVICEFILE
</envar> specifies the name of the per-user
8899 connection service file
8900 (see
<xref linkend=
"libpq-pgservice"/>).
8901 Defaults to
<filename>~/.pg_service.conf
</filename>, or
8902 <filename>%APPDATA%\postgresql\.pg_service.conf
</filename> on
8910 <primary><envar>PGOPTIONS
</envar></primary>
8912 <envar>PGOPTIONS
</envar> behaves the same as the
<xref
8913 linkend=
"libpq-connect-options"/> connection parameter.
8920 <primary><envar>PGAPPNAME
</envar></primary>
8922 <envar>PGAPPNAME
</envar> behaves the same as the
<xref
8923 linkend=
"libpq-connect-application-name"/> connection parameter.
8930 <primary><envar>PGSSLMODE
</envar></primary>
8932 <envar>PGSSLMODE
</envar> behaves the same as the
<xref
8933 linkend=
"libpq-connect-sslmode"/> connection parameter.
8940 <primary><envar>PGREQUIRESSL
</envar></primary>
8942 <envar>PGREQUIRESSL
</envar> behaves the same as the
<xref
8943 linkend=
"libpq-connect-requiressl"/> connection parameter.
8944 This environment variable is deprecated in favor of the
8945 <envar>PGSSLMODE
</envar> variable; setting both variables suppresses the
8953 <primary><envar>PGSSLCOMPRESSION
</envar></primary>
8955 <envar>PGSSLCOMPRESSION
</envar> behaves the same as the
<xref
8956 linkend=
"libpq-connect-sslcompression"/> connection parameter.
8963 <primary><envar>PGSSLCERT
</envar></primary>
8965 <envar>PGSSLCERT
</envar> behaves the same as the
<xref
8966 linkend=
"libpq-connect-sslcert"/> connection parameter.
8973 <primary><envar>PGSSLKEY
</envar></primary>
8975 <envar>PGSSLKEY
</envar> behaves the same as the
<xref
8976 linkend=
"libpq-connect-sslkey"/> connection parameter.
8983 <primary><envar>PGSSLCERTMODE
</envar></primary>
8985 <envar>PGSSLCERTMODE
</envar> behaves the same as the
<xref
8986 linkend=
"libpq-connect-sslcertmode"/> connection parameter.
8993 <primary><envar>PGSSLROOTCERT
</envar></primary>
8995 <envar>PGSSLROOTCERT
</envar> behaves the same as the
<xref
8996 linkend=
"libpq-connect-sslrootcert"/> connection parameter.
9003 <primary><envar>PGSSLCRL
</envar></primary>
9005 <envar>PGSSLCRL
</envar> behaves the same as the
<xref
9006 linkend=
"libpq-connect-sslcrl"/> connection parameter.
9013 <primary><envar>PGSSLCRLDIR
</envar></primary>
9015 <envar>PGSSLCRLDIR
</envar> behaves the same as the
<xref
9016 linkend=
"libpq-connect-sslcrldir"/> connection parameter.
9023 <primary><envar>PGSSLSNI
</envar></primary>
9025 <envar>PGSSLSNI
</envar> behaves the same as the
<xref
9026 linkend=
"libpq-connect-sslsni"/> connection parameter.
9033 <primary><envar>PGREQUIREPEER
</envar></primary>
9035 <envar>PGREQUIREPEER
</envar> behaves the same as the
<xref
9036 linkend=
"libpq-connect-requirepeer"/> connection parameter.
9043 <primary><envar>PGSSLMINPROTOCOLVERSION
</envar></primary>
9045 <envar>PGSSLMINPROTOCOLVERSION
</envar> behaves the same as the
<xref
9046 linkend=
"libpq-connect-ssl-min-protocol-version"/> connection parameter.
9053 <primary><envar>PGSSLMAXPROTOCOLVERSION
</envar></primary>
9055 <envar>PGSSLMAXPROTOCOLVERSION
</envar> behaves the same as the
<xref
9056 linkend=
"libpq-connect-ssl-max-protocol-version"/> connection parameter.
9063 <primary><envar>PGGSSENCMODE
</envar></primary>
9065 <envar>PGGSSENCMODE
</envar> behaves the same as the
<xref
9066 linkend=
"libpq-connect-gssencmode"/> connection parameter.
9073 <primary><envar>PGKRBSRVNAME
</envar></primary>
9075 <envar>PGKRBSRVNAME
</envar> behaves the same as the
<xref
9076 linkend=
"libpq-connect-krbsrvname"/> connection parameter.
9083 <primary><envar>PGGSSLIB
</envar></primary>
9085 <envar>PGGSSLIB
</envar> behaves the same as the
<xref
9086 linkend=
"libpq-connect-gsslib"/> connection parameter.
9093 <primary><envar>PGGSSDELEGATION
</envar></primary>
9095 <envar>PGGSSDELEGATION
</envar> behaves the same as the
<xref
9096 linkend=
"libpq-connect-gssdelegation"/> connection parameter.
9103 <primary><envar>PGCONNECT_TIMEOUT
</envar></primary>
9105 <envar>PGCONNECT_TIMEOUT
</envar> behaves the same as the
<xref
9106 linkend=
"libpq-connect-connect-timeout"/> connection parameter.
9113 <primary><envar>PGCLIENTENCODING
</envar></primary>
9115 <envar>PGCLIENTENCODING
</envar> behaves the same as the
<xref
9116 linkend=
"libpq-connect-client-encoding"/> connection parameter.
9123 <primary><envar>PGTARGETSESSIONATTRS
</envar></primary>
9125 <envar>PGTARGETSESSIONATTRS
</envar> behaves the same as the
<xref
9126 linkend=
"libpq-connect-target-session-attrs"/> connection parameter.
9133 <primary><envar>PGLOADBALANCEHOSTS
</envar></primary>
9135 <envar>PGLOADBALANCEHOSTS
</envar> behaves the same as the
<xref
9136 linkend=
"libpq-connect-load-balance-hosts"/> connection parameter.
9143 The following environment variables can be used to specify default
9144 behavior for each
<productname>PostgreSQL
</productname> session. (See
9145 also the
<xref linkend=
"sql-alterrole"/>
9146 and
<xref linkend=
"sql-alterdatabase"/>
9147 commands for ways to set default behavior on a per-user or per-database
9154 <primary><envar>PGDATESTYLE
</envar></primary>
9156 <envar>PGDATESTYLE
</envar> sets the default style of date/time
9157 representation. (Equivalent to
<literal>SET datestyle TO
9165 <primary><envar>PGTZ
</envar></primary>
9167 <envar>PGTZ
</envar> sets the default time zone. (Equivalent to
9168 <literal>SET timezone TO ...
</literal>.)
9175 <primary><envar>PGGEQO
</envar></primary>
9177 <envar>PGGEQO
</envar> sets the default mode for the genetic query
9178 optimizer. (Equivalent to
<literal>SET geqo TO ...
</literal>.)
9183 Refer to the
<acronym>SQL
</acronym> command
<xref linkend=
"sql-set"/>
9184 for information on correct values for these
9185 environment variables.
9189 The following environment variables determine internal behavior of
9190 <application>libpq
</application>; they override compiled-in defaults.
9196 <primary><envar>PGSYSCONFDIR
</envar></primary>
9198 <envar>PGSYSCONFDIR
</envar> sets the directory containing the
9199 <filename>pg_service.conf
</filename> file and in a future version
9200 possibly other system-wide configuration files.
9207 <primary><envar>PGLOCALEDIR
</envar></primary>
9209 <envar>PGLOCALEDIR
</envar> sets the directory containing the
9210 <literal>locale
</literal> files for message localization.
9219 <sect1 id=
"libpq-pgpass">
9220 <title>The Password File
</title>
9222 <indexterm zone=
"libpq-pgpass">
9223 <primary>password file
</primary>
9225 <indexterm zone=
"libpq-pgpass">
9226 <primary>.pgpass
</primary>
9230 The file
<filename>.pgpass
</filename> in a user's home directory can
9231 contain passwords to
9232 be used if the connection requires a password (and no password has been
9233 specified otherwise). On Microsoft Windows the file is named
9234 <filename>%APPDATA%\postgresql\pgpass.conf
</filename> (where
9235 <filename>%APPDATA%
</filename> refers to the Application Data subdirectory in
9236 the user's profile).
9237 Alternatively, the password file to use can be specified
9238 using the connection parameter
<xref linkend=
"libpq-connect-passfile"/>
9239 or the environment variable
<envar>PGPASSFILE
</envar>.
9243 This file should contain lines of the following format:
9245 <replaceable>hostname
</replaceable>:
<replaceable>port
</replaceable>:
<replaceable>database
</replaceable>:
<replaceable>username
</replaceable>:
<replaceable>password
</replaceable>
9247 (You can add a reminder comment to the file by copying the line above and
9248 preceding it with
<literal>#
</literal>.)
9249 Each of the first four fields can be a literal value, or
9250 <literal>*
</literal>, which matches anything. The password field from
9251 the first line that matches the current connection parameters will be
9252 used. (Therefore, put more-specific entries first when you are using
9253 wildcards.) If an entry needs to contain
<literal>:
</literal> or
9254 <literal>\
</literal>, escape this character with
<literal>\
</literal>.
9255 The host name field is matched to the
<literal>host
</literal> connection
9256 parameter if that is specified, otherwise to
9257 the
<literal>hostaddr
</literal> parameter if that is specified; if neither
9258 are given then the host name
<literal>localhost
</literal> is searched for.
9259 The host name
<literal>localhost
</literal> is also searched for when
9260 the connection is a Unix-domain socket connection and
9261 the
<literal>host
</literal> parameter
9262 matches
<application>libpq
</application>'s default socket directory path.
9263 In a standby server, a database field of
<literal>replication
</literal>
9264 matches streaming replication connections made to the primary server.
9265 The database field is of limited usefulness otherwise, because users have
9266 the same password for all databases in the same cluster.
9270 On Unix systems, the permissions on a password file must
9271 disallow any access to world or group; achieve this by a command such as
9272 <command>chmod
0600 ~/.pgpass
</command>. If the permissions are less
9273 strict than this, the file will be ignored. On Microsoft Windows, it
9274 is assumed that the file is stored in a directory that is secure, so
9275 no special permissions check is made.
9280 <sect1 id=
"libpq-pgservice">
9281 <title>The Connection Service File
</title>
9283 <indexterm zone=
"libpq-pgservice">
9284 <primary>connection service file
</primary>
9286 <indexterm zone=
"libpq-pgservice">
9287 <primary>pg_service.conf
</primary>
9289 <indexterm zone=
"libpq-pgservice">
9290 <primary>.pg_service.conf
</primary>
9294 The connection service file allows libpq connection parameters to be
9295 associated with a single service name. That service name can then be
9296 specified in a libpq connection string, and the associated settings will be
9297 used. This allows connection parameters to be modified without requiring
9298 a recompile of the libpq-using application. The service name can also be
9299 specified using the
<envar>PGSERVICE
</envar> environment variable.
9303 Service names can be defined in either a per-user service file or a
9304 system-wide file. If the same service name exists in both the user
9305 and the system file, the user file takes precedence.
9306 By default, the per-user service file is named
9307 <filename>~/.pg_service.conf
</filename>.
9308 On Microsoft Windows, it is named
9309 <filename>%APPDATA%\postgresql\.pg_service.conf
</filename> (where
9310 <filename>%APPDATA%
</filename> refers to the Application Data subdirectory
9311 in the user's profile). A different file name can be specified by
9312 setting the environment variable
<envar>PGSERVICEFILE
</envar>.
9313 The system-wide file is named
<filename>pg_service.conf
</filename>.
9314 By default it is sought in the
<filename>etc
</filename> directory
9315 of the
<productname>PostgreSQL
</productname> installation
9316 (use
<literal>pg_config --sysconfdir
</literal> to identify this
9317 directory precisely). Another directory, but not a different file
9318 name, can be specified by setting the environment variable
9319 <envar>PGSYSCONFDIR
</envar>.
9323 Either service file uses an
<quote>INI file
</quote> format where the section
9324 name is the service name and the parameters are connection
9325 parameters; see
<xref linkend=
"libpq-paramkeywords"/> for a list. For
9334 An example file is provided in
9335 the
<productname>PostgreSQL
</productname> installation at
9336 <filename>share/pg_service.conf.sample
</filename>.
9340 Connection parameters obtained from a service file are combined with
9341 parameters obtained from other sources. A service file setting
9342 overrides the corresponding environment variable, and in turn can be
9343 overridden by a value given directly in the connection string.
9344 For example, using the above service file, a connection string
9345 <literal>service=mydb port=
5434</literal> will use
9346 host
<literal>somehost
</literal>, port
<literal>5434</literal>,
9347 user
<literal>admin
</literal>, and other parameters as set by
9348 environment variables or built-in defaults.
9353 <sect1 id=
"libpq-ldap">
9354 <title>LDAP Lookup of Connection Parameters
</title>
9356 <indexterm zone=
"libpq-ldap">
9357 <primary>LDAP connection parameter lookup
</primary>
9361 If
<application>libpq
</application> has been compiled with LDAP support (option
9362 <literal><option>--with-ldap
</option></literal> for
<command>configure
</command>)
9363 it is possible to retrieve connection options like
<literal>host
</literal>
9364 or
<literal>dbname
</literal> via LDAP from a central server.
9365 The advantage is that if the connection parameters for a database change,
9366 the connection information doesn't have to be updated on all client machines.
9370 LDAP connection parameter lookup uses the connection service file
9371 <filename>pg_service.conf
</filename> (see
<xref
9372 linkend=
"libpq-pgservice"/>). A line in a
9373 <filename>pg_service.conf
</filename> stanza that starts with
9374 <literal>ldap://
</literal> will be recognized as an LDAP URL and an
9375 LDAP query will be performed. The result must be a list of
9376 <literal>keyword = value
</literal> pairs which will be used to set
9377 connection options. The URL must conform to
9378 <ulink url=
"https://datatracker.ietf.org/doc/html/rfc1959">RFC
1959</ulink>
9381 ldap://[
<replaceable>hostname
</replaceable>[:
<replaceable>port
</replaceable>]]/
<replaceable>search_base
</replaceable>?
<replaceable>attribute
</replaceable>?
<replaceable>search_scope
</replaceable>?
<replaceable>filter
</replaceable>
9383 where
<replaceable>hostname
</replaceable> defaults to
9384 <literal>localhost
</literal> and
<replaceable>port
</replaceable>
9389 Processing of
<filename>pg_service.conf
</filename> is terminated after
9390 a successful LDAP lookup, but is continued if the LDAP server cannot
9391 be contacted. This is to provide a fallback with further LDAP URL
9392 lines that point to different LDAP servers, classical
<literal>keyword
9393 = value
</literal> pairs, or default connection options. If you would
9394 rather get an error message in this case, add a syntactically incorrect
9395 line after the LDAP URL.
9399 A sample LDAP entry that has been created with the LDIF file
9402 dn:cn=mydatabase,dc=mycompany,dc=com
9407 description:host=dbserver.mycompany.com
9408 description:port=
5439
9409 description:dbname=mydb
9410 description:user=mydb_user
9411 description:sslmode=require
9413 might be queried with the following LDAP URL:
9415 ldap://ldap.mycompany.com/dc=mycompany,dc=com?description?one?(cn=mydatabase)
9420 You can also mix regular service file entries with LDAP lookups.
9421 A complete example for a stanza in
<filename>pg_service.conf
</filename>
9424 # only host and port are stored in LDAP, specify dbname and user explicitly
9428 ldap://ldap.acme.com/cn=dbserver,cn=hosts?pgconnectinfo?base?(objectclass=*)
9435 <sect1 id=
"libpq-ssl">
9436 <title>SSL Support
</title>
9438 <indexterm zone=
"libpq-ssl">
9439 <primary>SSL
</primary>
9440 <secondary>TLS
</secondary>
9444 <productname>PostgreSQL
</productname> has native support for using
<acronym>SSL
</acronym>
9445 connections to encrypt client/server communications using
9446 <acronym>TLS
</acronym> protocols for increased security.
9447 See
<xref linkend=
"ssl-tcp"/> for details about the server-side
9448 <acronym>SSL
</acronym> functionality.
9452 <application>libpq
</application> reads the system-wide
9453 <productname>OpenSSL
</productname> configuration file. By default, this
9454 file is named
<filename>openssl.cnf
</filename> and is located in the
9455 directory reported by
<literal>openssl version -d
</literal>. This default
9456 can be overridden by setting environment variable
9457 <envar>OPENSSL_CONF
</envar> to the name of the desired configuration
9461 <sect2 id=
"libq-ssl-certificates">
9462 <title>Client Verification of Server Certificates
</title>
9465 By default,
<productname>PostgreSQL
</productname> will not perform any verification of
9466 the server certificate. This means that it is possible to spoof the server
9467 identity (for example by modifying a DNS record or by taking over the server
9468 IP address) without the client knowing. In order to prevent spoofing,
9469 the client must be able to verify the server's identity via a chain of
9470 trust. A chain of trust is established by placing a root (self-signed)
9471 certificate authority (
<acronym>CA
</acronym>) certificate on one
9472 computer and a leaf certificate
<emphasis>signed
</emphasis> by the
9473 root certificate on another computer. It is also possible to use an
9474 <quote>intermediate
</quote> certificate which is signed by the root
9475 certificate and signs leaf certificates.
9479 To allow the client to verify the identity of the server, place a root
9480 certificate on the client and a leaf certificate signed by the root
9481 certificate on the server. To allow the server to verify the identity
9482 of the client, place a root certificate on the server and a leaf
9483 certificate signed by the root certificate on the client. One or more
9484 intermediate certificates (usually stored with the leaf certificate)
9485 can also be used to link the leaf certificate to the root certificate.
9489 Once a chain of trust has been established, there are two ways for
9490 the client to validate the leaf certificate sent by the server.
9491 If the parameter
<literal>sslmode
</literal> is set to
<literal>verify-ca
</literal>,
9492 libpq will verify that the server is trustworthy by checking the
9493 certificate chain up to the root certificate stored on the client.
9494 If
<literal>sslmode
</literal> is set to
<literal>verify-full
</literal>,
9495 libpq will
<emphasis>also
</emphasis> verify that the server host
9496 name matches the name stored in the server certificate. The
9497 SSL connection will fail if the server certificate cannot be
9498 verified.
<literal>verify-full
</literal> is recommended in most
9499 security-sensitive environments.
9503 In
<literal>verify-full
</literal> mode, the host name is matched against the
9504 certificate's Subject Alternative Name attribute(s) (SAN), or against the
9505 Common Name attribute if no SAN of type
<literal>dNSName
</literal> is
9506 present. If the certificate's name attribute starts with an asterisk
9507 (
<literal>*
</literal>), the asterisk will be treated as
9508 a wildcard, which will match all characters
<emphasis>except
</emphasis> a dot
9509 (
<literal>.
</literal>). This means the certificate will not match subdomains.
9510 If the connection is made using an IP address instead of a host name, the
9511 IP address will be matched (without doing any DNS lookups) against SANs of
9512 type
<literal>iPAddress
</literal> or
<literal>dNSName
</literal>. If no
9513 <literal>iPAddress
</literal> SAN is present and no
9514 matching
<literal>dNSName
</literal> SAN is present, the host IP address is
9515 matched against the Common Name attribute.
9520 For backward compatibility with earlier versions of PostgreSQL, the host
9521 IP address is verified in a manner different
9522 from
<ulink url=
"https://datatracker.ietf.org/doc/html/rfc6125">RFC
6125</ulink>.
9523 The host IP address is always matched against
<literal>dNSName
</literal>
9524 SANs as well as
<literal>iPAddress
</literal> SANs, and can be matched
9525 against the Common Name attribute if no relevant SANs exist.
9530 To allow server certificate verification, one or more root certificates
9531 must be placed in the file
<filename>~/.postgresql/root.crt
</filename>
9532 in the user's home directory. (On Microsoft Windows the file is named
9533 <filename>%APPDATA%\postgresql\root.crt
</filename>.) Intermediate
9534 certificates should also be added to the file if they are needed to link
9535 the certificate chain sent by the server to the root certificates
9536 stored on the client.
9540 Certificate Revocation List (CRL) entries are also checked
9541 if the file
<filename>~/.postgresql/root.crl
</filename> exists
9542 (
<filename>%APPDATA%\postgresql\root.crl
</filename> on Microsoft
9547 The location of the root certificate file and the CRL can be changed by
9549 the connection parameters
<literal>sslrootcert
</literal> and
<literal>sslcrl
</literal>
9550 or the environment variables
<envar>PGSSLROOTCERT
</envar> and
<envar>PGSSLCRL
</envar>.
9551 <literal>sslcrldir
</literal> or the environment variable
<envar>PGSSLCRLDIR
</envar>
9552 can also be used to specify a directory containing CRL files.
9557 For backwards compatibility with earlier versions of PostgreSQL, if a
9558 root CA file exists, the behavior of
9559 <literal>sslmode
</literal>=
<literal>require
</literal> will be the same
9560 as that of
<literal>verify-ca
</literal>, meaning the server certificate
9561 is validated against the CA. Relying on this behavior is discouraged,
9562 and applications that need certificate validation should always use
9563 <literal>verify-ca
</literal> or
<literal>verify-full
</literal>.
9568 <sect2 id=
"libpq-ssl-clientcert">
9569 <title>Client Certificates
</title>
9572 If the server attempts to verify the identity of the
9573 client by requesting the client's leaf certificate,
9574 <application>libpq
</application> will send the certificate(s) stored in
9575 file
<filename>~/.postgresql/postgresql.crt
</filename> in the user's home
9576 directory. The certificates must chain to the root certificate trusted
9577 by the server. A matching
9578 private key file
<filename>~/.postgresql/postgresql.key
</filename> must also
9580 On Microsoft Windows these files are named
9581 <filename>%APPDATA%\postgresql\postgresql.crt
</filename> and
9582 <filename>%APPDATA%\postgresql\postgresql.key
</filename>.
9583 The location of the certificate and key files can be overridden by the
9584 connection parameters
<literal>sslcert
</literal>
9585 and
<literal>sslkey
</literal>, or by the
9586 environment variables
<envar>PGSSLCERT
</envar> and
<envar>PGSSLKEY
</envar>.
9590 On Unix systems, the permissions on the private key file must disallow
9591 any access to world or group; achieve this by a command such as
9592 <command>chmod
0600 ~/.postgresql/postgresql.key
</command>.
9593 Alternatively, the file can be owned by root and have group read access
9594 (that is,
<literal>0640</literal> permissions). That setup is intended
9595 for installations where certificate and key files are managed by the
9596 operating system. The user of
<application>libpq
</application> should
9597 then be made a member of the group that has access to those certificate
9598 and key files. (On Microsoft Windows, there is no file permissions
9599 check, since the
<filename>%APPDATA%\postgresql
</filename> directory is
9604 The first certificate in
<filename>postgresql.crt
</filename> must be the
9605 client's certificate because it must match the client's private key.
9606 <quote>Intermediate
</quote> certificates can be optionally appended
9607 to the file
— doing so avoids requiring storage of intermediate
9608 certificates on the server (
<xref linkend=
"guc-ssl-ca-file"/>).
9612 The certificate and key may be in PEM or ASN
.1 DER format.
9617 stored in cleartext or encrypted with a passphrase using any algorithm
9618 supported by
<productname>OpenSSL
</productname>, like AES-
128. If the key
9619 is stored encrypted, then the passphrase may be provided in the
9620 <xref linkend=
"libpq-connect-sslpassword"/> connection option. If an
9621 encrypted key is supplied and the
<literal>sslpassword
</literal> option
9622 is absent or blank, a password will be prompted for interactively by
9623 <productname>OpenSSL
</productname> with a
9624 <literal>Enter PEM pass phrase:
</literal> prompt if a TTY is available.
9625 Applications can override the client certificate prompt and the handling
9626 of the
<literal>sslpassword
</literal> parameter by supplying their own
9627 key password callback; see
9628 <xref linkend=
"libpq-pqsetsslkeypasshook-openssl"/>.
9632 For instructions on creating certificates, see
<xref
9633 linkend=
"ssl-certificate-creation"/>.
9637 <sect2 id=
"libpq-ssl-protection">
9638 <title>Protection Provided in Different Modes
</title>
9641 The different values for the
<literal>sslmode
</literal> parameter provide different
9642 levels of protection. SSL can provide
9643 protection against three types of attacks:
9647 <term>Eavesdropping
</term>
9649 <para>If a third party can examine the network traffic between the
9650 client and the server, it can read both connection information (including
9651 the user name and password) and the data that is passed.
<acronym>SSL
</acronym>
9652 uses encryption to prevent this.
9658 <term>Man-in-the-middle (
<acronym>MITM
</acronym>)
</term>
9660 <para>If a third party can modify the data while passing between the
9661 client and server, it can pretend to be the server and therefore see and
9662 modify data
<emphasis>even if it is encrypted
</emphasis>. The third party can then
9663 forward the connection information and data to the original server,
9664 making it impossible to detect this attack. Common vectors to do this
9665 include DNS poisoning and address hijacking, whereby the client is directed
9666 to a different server than intended. There are also several other
9667 attack methods that can accomplish this.
<acronym>SSL
</acronym> uses certificate
9668 verification to prevent this, by authenticating the server to the client.
9674 <term>Impersonation
</term>
9676 <para>If a third party can pretend to be an authorized client, it can
9677 simply access data it should not have access to. Typically this can
9678 happen through insecure password management.
<acronym>SSL
</acronym> uses
9679 client certificates to prevent this, by making sure that only holders
9680 of valid certificates can access the server.
9688 For a connection to be known SSL-secured, SSL usage must be configured
9689 on
<emphasis>both the client and the server
</emphasis> before the connection
9690 is made. If it is only configured on the server, the client may end up
9691 sending sensitive information (e.g., passwords) before
9692 it knows that the server requires high security. In libpq, secure
9693 connections can be ensured
9694 by setting the
<literal>sslmode
</literal> parameter to
<literal>verify-full
</literal> or
9695 <literal>verify-ca
</literal>, and providing the system with a root certificate to
9696 verify against. This is analogous to using an
<literal>https
</literal>
9697 <acronym>URL
</acronym> for encrypted web browsing.
9701 Once the server has been authenticated, the client can pass sensitive data.
9702 This means that up until this point, the client does not need to know if
9703 certificates will be used for authentication, making it safe to specify that
9704 only in the server configuration.
9708 All
<acronym>SSL
</acronym> options carry overhead in the form of encryption and
9709 key-exchange, so there is a trade-off that has to be made between performance
9710 and security.
<xref linkend=
"libpq-ssl-sslmode-statements"/>
9711 illustrates the risks the different
<literal>sslmode
</literal> values
9712 protect against, and what statement they make about security and overhead.
9715 <table id=
"libpq-ssl-sslmode-statements">
9716 <title>SSL Mode Descriptions
</title>
9718 <colspec colname=
"col1" colwidth=
"1*"/>
9719 <colspec colname=
"col2" colwidth=
"1*"/>
9720 <colspec colname=
"col3" colwidth=
"1*"/>
9721 <colspec colname=
"col4" colwidth=
"2*"/>
9724 <entry><literal>sslmode
</literal></entry>
9725 <entry>Eavesdropping protection
</entry>
9726 <entry><acronym>MITM
</acronym> protection
</entry>
9727 <entry>Statement
</entry>
9733 <entry><literal>disable
</literal></entry>
9736 <entry>I don't care about security, and I don't want to pay the overhead
9742 <entry><literal>allow
</literal></entry>
9743 <entry>Maybe
</entry>
9745 <entry>I don't care about security, but I will pay the overhead of
9746 encryption if the server insists on it.
9751 <entry><literal>prefer
</literal></entry>
9752 <entry>Maybe
</entry>
9754 <entry>I don't care about encryption, but I wish to pay the overhead of
9755 encryption if the server supports it.
9760 <entry><literal>require
</literal></entry>
9763 <entry>I want my data to be encrypted, and I accept the overhead. I trust
9764 that the network will make sure I always connect to the server I want.
9769 <entry><literal>verify-ca
</literal></entry>
9771 <entry>Depends on CA policy
</entry>
9772 <entry>I want my data encrypted, and I accept the overhead. I want to be
9773 sure that I connect to a server that I trust.
9778 <entry><literal>verify-full
</literal></entry>
9781 <entry>I want my data encrypted, and I accept the overhead. I want to be
9782 sure that I connect to a server I trust, and that it's the one I
9792 The difference between
<literal>verify-ca
</literal> and
<literal>verify-full
</literal>
9793 depends on the policy of the root
<acronym>CA
</acronym>. If a public
9794 <acronym>CA
</acronym> is used,
<literal>verify-ca
</literal> allows connections to a server
9795 that
<emphasis>somebody else
</emphasis> may have registered with the
<acronym>CA
</acronym>.
9796 In this case,
<literal>verify-full
</literal> should always be used. If
9797 a local
<acronym>CA
</acronym> is used, or even a self-signed certificate, using
9798 <literal>verify-ca
</literal> often provides enough protection.
9802 The default value for
<literal>sslmode
</literal> is
<literal>prefer
</literal>. As is shown
9803 in the table, this makes no sense from a security point of view, and it only
9804 promises performance overhead if possible. It is only provided as the default
9805 for backward compatibility, and is not recommended in secure deployments.
9810 <sect2 id=
"libpq-ssl-fileusage">
9811 <title>SSL Client File Usage
</title>
9814 <xref linkend=
"libpq-ssl-file-usage"/> summarizes the files that are
9815 relevant to the SSL setup on the client.
9818 <table id=
"libpq-ssl-file-usage">
9819 <title>Libpq/Client SSL File Usage
</title>
9824 <entry>Contents
</entry>
9825 <entry>Effect
</entry>
9832 <entry><filename>~/.postgresql/postgresql.crt
</filename></entry>
9833 <entry>client certificate
</entry>
9834 <entry>sent to server
</entry>
9838 <entry><filename>~/.postgresql/postgresql.key
</filename></entry>
9839 <entry>client private key
</entry>
9840 <entry>proves client certificate sent by owner; does not indicate
9841 certificate owner is trustworthy
</entry>
9845 <entry><filename>~/.postgresql/root.crt
</filename></entry>
9846 <entry>trusted certificate authorities
</entry>
9847 <entry>checks that server certificate is signed by a trusted certificate
9852 <entry><filename>~/.postgresql/root.crl
</filename></entry>
9853 <entry>certificates revoked by certificate authorities
</entry>
9854 <entry>server certificate must not be on this list
</entry>
9862 <sect2 id=
"libpq-ssl-initialize">
9863 <title>SSL Library Initialization
</title>
9866 If your application initializes
<literal>libssl
</literal> and/or
9867 <literal>libcrypto
</literal> libraries and
<application>libpq
</application>
9868 is built with
<acronym>SSL
</acronym> support, you should call
9869 <xref linkend=
"libpq-PQinitOpenSSL"/> to tell
<application>libpq
</application>
9870 that the
<literal>libssl
</literal> and/or
<literal>libcrypto
</literal> libraries
9871 have been initialized by your application, so that
9872 <application>libpq
</application> will not also initialize those libraries.
9873 However, this is unnecessary when using
<productname>OpenSSL
</productname>
9874 version
1.1.0 or later, as duplicate initializations are no longer problematic.
9879 <varlistentry id=
"libpq-PQinitOpenSSL">
9880 <term><function>PQinitOpenSSL
</function><indexterm><primary>PQinitOpenSSL
</primary></indexterm></term>
9884 Allows applications to select which security libraries to initialize.
9886 void PQinitOpenSSL(int do_ssl, int do_crypto);
9891 When
<parameter>do_ssl
</parameter> is non-zero,
<application>libpq
</application>
9892 will initialize the
<productname>OpenSSL
</productname> library before first
9893 opening a database connection. When
<parameter>do_crypto
</parameter> is
9894 non-zero, the
<literal>libcrypto
</literal> library will be initialized. By
9895 default (if
<xref linkend=
"libpq-PQinitOpenSSL"/> is not called), both libraries
9896 are initialized. When SSL support is not compiled in, this function is
9897 present but does nothing.
9901 If your application uses and initializes either
<productname>OpenSSL
</productname>
9902 or its underlying
<literal>libcrypto
</literal> library, you
<emphasis>must
</emphasis>
9903 call this function with zeroes for the appropriate parameter(s)
9904 before first opening a database connection. Also be sure that you
9905 have done that initialization before opening a database connection.
9910 <varlistentry id=
"libpq-PQinitSSL">
9911 <term><function>PQinitSSL
</function><indexterm><primary>PQinitSSL
</primary></indexterm></term><listitem>
9913 Allows applications to select which security libraries to initialize.
9915 void PQinitSSL(int do_ssl);
9920 This function is equivalent to
9921 <literal>PQinitOpenSSL(do_ssl, do_ssl)
</literal>.
9922 It is sufficient for applications that initialize both or neither
9923 of
<productname>OpenSSL
</productname> and
<literal>libcrypto
</literal>.
9927 <xref linkend=
"libpq-PQinitSSL"/> has been present since
9928 <productname>PostgreSQL
</productname> 8.0, while
<xref linkend=
"libpq-PQinitOpenSSL"/>
9929 was added in
<productname>PostgreSQL
</productname> 8.4, so
<xref linkend=
"libpq-PQinitSSL"/>
9930 might be preferable for applications that need to work with older
9931 versions of
<application>libpq
</application>.
9942 <sect1 id=
"libpq-threading">
9943 <title>Behavior in Threaded Programs
</title>
9945 <indexterm zone=
"libpq-threading">
9946 <primary>threads
</primary>
9947 <secondary>with libpq
</secondary>
9951 As of version
17,
<application>libpq
</application> is always reentrant and thread-safe.
9952 However, one restriction is that no two threads attempt to manipulate
9953 the same
<structname>PGconn
</structname> object at the same time. In particular,
9954 you cannot issue concurrent commands from different threads through
9955 the same connection object. (If you need to run concurrent commands,
9956 use multiple connections.)
9960 <structname>PGresult
</structname> objects are normally read-only after creation,
9961 and so can be passed around freely between threads. However, if you use
9962 any of the
<structname>PGresult
</structname>-modifying functions described in
9963 <xref linkend=
"libpq-misc"/> or
<xref linkend=
"libpq-events"/>, it's up
9964 to you to avoid concurrent operations on the same
<structname>PGresult
</structname>,
9969 In earlier versions,
<application>libpq
</application> could be compiled
9970 with or without thread support, depending on compiler options. This
9971 function allows the querying of
<application>libpq
</application>'s
9976 <varlistentry id=
"libpq-PQisthreadsafe">
9977 <term><function>PQisthreadsafe
</function><indexterm><primary>PQisthreadsafe
</primary></indexterm></term>
9981 Returns the thread safety status of the
9982 <application>libpq
</application> library.
9984 int PQisthreadsafe();
9989 Returns
1 if the
<application>libpq
</application> is thread-safe
9990 and
0 if it is not. Always returns
1 on version
17 and above.
9997 The deprecated functions
<xref linkend=
"libpq-PQrequestCancel"/> and
9998 <xref linkend=
"libpq-PQoidStatus"/> are not thread-safe and should not be
9999 used in multithread programs.
<xref linkend=
"libpq-PQrequestCancel"/>
10000 can be replaced by
<xref linkend=
"libpq-PQcancelBlocking"/>.
10001 <xref linkend=
"libpq-PQoidStatus"/> can be replaced by
10002 <xref linkend=
"libpq-PQoidValue"/>.
10006 If you are using Kerberos inside your application (in addition to inside
10007 <application>libpq
</application>), you will need to do locking around
10008 Kerberos calls because Kerberos functions are not thread-safe. See
10009 function
<function>PQregisterThreadLock
</function> in the
10010 <application>libpq
</application> source code for a way to do cooperative
10011 locking between
<application>libpq
</application> and your application.
10016 <sect1 id=
"libpq-build">
10017 <title>Building
<application>libpq
</application> Programs
</title>
10019 <indexterm zone=
"libpq-build">
10020 <primary>compiling
</primary>
10021 <secondary>libpq applications
</secondary>
10025 To build (i.e., compile and link) a program using
10026 <application>libpq
</application> you need to do all of the following
10032 Include the
<filename>libpq-fe.h
</filename> header file:
10034 #include
<libpq-fe.h
>
10036 If you failed to do that then you will normally get error messages
10037 from your compiler similar to:
10039 foo.c: In function `main':
10040 foo.c:
34: `PGconn' undeclared (first use in this function)
10041 foo.c:
35: `PGresult' undeclared (first use in this function)
10042 foo.c:
54: `CONNECTION_BAD' undeclared (first use in this function)
10043 foo.c:
68: `PGRES_COMMAND_OK' undeclared (first use in this function)
10044 foo.c:
95: `PGRES_TUPLES_OK' undeclared (first use in this function)
10051 Point your compiler to the directory where the
<productname>PostgreSQL
</productname> header
10052 files were installed, by supplying the
10053 <literal>-I
<replaceable>directory
</replaceable></literal> option
10054 to your compiler. (In some cases the compiler will look into
10055 the directory in question by default, so you can omit this
10056 option.) For instance, your compile command line could look
10059 cc -c -I/usr/local/pgsql/include testprog.c
10061 If you are using makefiles then add the option to the
10062 <varname>CPPFLAGS
</varname> variable:
10064 CPPFLAGS += -I/usr/local/pgsql/include
10069 If there is any chance that your program might be compiled by
10070 other users then you should not hardcode the directory location
10071 like that. Instead, you can run the utility
10072 <command>pg_config
</command><indexterm><primary>pg_config
</primary><secondary
10073 sortas=
"libpq">with libpq
</secondary></indexterm> to find out where the header
10074 files are on the local system:
10076 <prompt>$
</prompt> pg_config --includedir
10077 <computeroutput>/usr/local/include
</computeroutput>
10083 have
<command>pkg-config
</command><indexterm><primary>pkg-config
</primary><secondary sortas=
"libpq">with
10084 libpq
</secondary></indexterm> installed, you can run instead:
10086 <prompt>$
</prompt> pkg-config --cflags libpq
10087 <computeroutput>-I/usr/local/include
</computeroutput>
10089 Note that this will already include the
<option>-I
</option> in front of
10094 Failure to specify the correct option to the compiler will
10095 result in an error message such as:
10097 testlibpq.c:
8:
22: libpq-fe.h: No such file or directory
10104 When linking the final program, specify the option
10105 <literal>-lpq
</literal> so that the
<application>libpq
</application>
10106 library gets pulled in, as well as the option
10107 <literal>-L
<replaceable>directory
</replaceable></literal> to point
10108 the compiler to the directory where the
10109 <application>libpq
</application> library resides. (Again, the
10110 compiler will search some directories by default.) For maximum
10111 portability, put the
<option>-L
</option> option before the
10112 <option>-lpq
</option> option. For example:
10114 cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq
10119 You can find out the library directory using
10120 <command>pg_config
</command> as well:
10122 <prompt>$
</prompt> pg_config --libdir
10123 <computeroutput>/usr/local/pgsql/lib
</computeroutput>
10128 Or again use
<command>pkg-config
</command>:
10130 <prompt>$
</prompt> pkg-config --libs libpq
10131 <computeroutput>-L/usr/local/pgsql/lib -lpq
</computeroutput>
10133 Note again that this prints the full options, not only the path.
10137 Error messages that point to problems in this area could look like
10140 testlibpq.o: In function `main':
10141 testlibpq.o(.text+
0x60): undefined reference to `PQsetdbLogin'
10142 testlibpq.o(.text+
0x71): undefined reference to `PQstatus'
10143 testlibpq.o(.text+
0xa4): undefined reference to `PQerrorMessage'
10145 This means you forgot
<option>-lpq
</option>.
10147 /usr/bin/ld: cannot find -lpq
10149 This means you forgot the
<option>-L
</option> option or did not
10150 specify the right directory.
10159 <sect1 id=
"libpq-example">
10160 <title>Example Programs
</title>
10163 These examples and others can be found in the
10164 directory
<filename>src/test/examples
</filename> in the source code
10168 <example id=
"libpq-example-1">
10169 <title><application>libpq
</application> Example Program
1</title>
10174 * src/test/examples/testlibpq.c
10179 * Test the C version of libpq, the PostgreSQL frontend library.
10182 #include
<stdlib.h
>
10183 #include
"libpq-fe.h"
10186 exit_nicely(PGconn *conn)
10193 main(int argc, char **argv)
10195 const char *conninfo;
10203 * If the user supplies a parameter on the command line, use it as the
10204 * conninfo string; otherwise default to setting dbname=postgres and using
10205 * environment variables or defaults for all other connection parameters.
10208 conninfo = argv[
1];
10210 conninfo =
"dbname = postgres";
10212 /* Make a connection to the database */
10213 conn = PQconnectdb(conninfo);
10215 /* Check to see that the backend connection was successfully made */
10216 if (PQstatus(conn) != CONNECTION_OK)
10218 fprintf(stderr,
"%s", PQerrorMessage(conn));
10222 /* Set always-secure search path, so malicious users can't take control. */
10224 "SELECT pg_catalog.set_config('search_path', '', false)");
10225 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10227 fprintf(stderr,
"SET failed: %s", PQerrorMessage(conn));
10233 * Should PQclear PGresult whenever it is no longer needed to avoid memory
10239 * Our test case here involves using a cursor, for which we must be inside
10240 * a transaction block. We could do the whole thing with a single
10241 * PQexec() of
"select * from pg_database", but that's too trivial to make
10245 /* Start a transaction block */
10246 res = PQexec(conn,
"BEGIN");
10247 if (PQresultStatus(res) != PGRES_COMMAND_OK)
10249 fprintf(stderr,
"BEGIN command failed: %s", PQerrorMessage(conn));
10256 * Fetch rows from pg_database, the system catalog of databases
10258 res = PQexec(conn,
"DECLARE myportal CURSOR FOR select * from pg_database");
10259 if (PQresultStatus(res) != PGRES_COMMAND_OK)
10261 fprintf(stderr,
"DECLARE CURSOR failed: %s", PQerrorMessage(conn));
10267 res = PQexec(conn,
"FETCH ALL in myportal");
10268 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10270 fprintf(stderr,
"FETCH ALL failed: %s", PQerrorMessage(conn));
10275 /* first, print out the attribute names */
10276 nFields = PQnfields(res);
10277 for (i =
0; i < nFields; i++)
10278 printf(
"%-15s", PQfname(res, i));
10281 /* next, print out the rows */
10282 for (i =
0; i < PQntuples(res); i++)
10284 for (j =
0; j < nFields; j++)
10285 printf(
"%-15s", PQgetvalue(res, i, j));
10291 /* close the portal ... we don't bother to check for errors ... */
10292 res = PQexec(conn,
"CLOSE myportal");
10295 /* end the transaction */
10296 res = PQexec(conn,
"END");
10299 /* close the connection to the database and cleanup */
10308 <example id=
"libpq-example-2">
10309 <title><application>libpq
</application> Example Program
2</title>
10314 * src/test/examples/testlibpq2.c
10318 * Test of the asynchronous notification interface
10320 * Start this program, then from psql in another window do
10322 * Repeat four times to get this program to exit.
10324 * Or, if you want to get fancy, try this:
10325 * populate a database with the following commands
10326 * (provided in src/test/examples/testlibpq2.sql):
10328 * CREATE SCHEMA TESTLIBPQ2;
10329 * SET search_path = TESTLIBPQ2;
10330 * CREATE TABLE TBL1 (i int4);
10331 * CREATE TABLE TBL2 (i int4);
10332 * CREATE RULE r1 AS ON INSERT TO TBL1 DO
10333 * (INSERT INTO TBL2 VALUES (new.i); NOTIFY TBL2);
10335 * Start this program, then from psql do this four times:
10337 * INSERT INTO TESTLIBPQ2.TBL1 VALUES (
10);
10341 #include
<windows.h
>
10344 #include
<stdlib.h
>
10345 #include
<string.h
>
10347 #include
<sys/select.h
>
10348 #include
<sys/time.h
>
10349 #include
<sys/types.h
>
10351 #include
"libpq-fe.h"
10354 exit_nicely(PGconn *conn)
10361 main(int argc, char **argv)
10363 const char *conninfo;
10370 * If the user supplies a parameter on the command line, use it as the
10371 * conninfo string; otherwise default to setting dbname=postgres and using
10372 * environment variables or defaults for all other connection parameters.
10375 conninfo = argv[
1];
10377 conninfo =
"dbname = postgres";
10379 /* Make a connection to the database */
10380 conn = PQconnectdb(conninfo);
10382 /* Check to see that the backend connection was successfully made */
10383 if (PQstatus(conn) != CONNECTION_OK)
10385 fprintf(stderr,
"%s", PQerrorMessage(conn));
10389 /* Set always-secure search path, so malicious users can't take control. */
10391 "SELECT pg_catalog.set_config('search_path', '', false)");
10392 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10394 fprintf(stderr,
"SET failed: %s", PQerrorMessage(conn));
10400 * Should PQclear PGresult whenever it is no longer needed to avoid memory
10406 * Issue LISTEN command to enable notifications from the rule's NOTIFY.
10408 res = PQexec(conn,
"LISTEN TBL2");
10409 if (PQresultStatus(res) != PGRES_COMMAND_OK)
10411 fprintf(stderr,
"LISTEN command failed: %s", PQerrorMessage(conn));
10417 /* Quit after four notifies are received. */
10419 while (nnotifies <
4)
10422 * Sleep until something happens on the connection. We use select(
2)
10423 * to wait for input, but you could also use poll() or similar
10429 sock = PQsocket(conn);
10432 break; /* shouldn't happen */
10434 FD_ZERO(&input_mask);
10435 FD_SET(sock, &input_mask);
10437 if (select(sock +
1, &input_mask, NULL, NULL, NULL) <
0)
10439 fprintf(stderr,
"select() failed: %s\n", strerror(errno));
10443 /* Now check for input */
10444 PQconsumeInput(conn);
10445 while ((notify = PQnotifies(conn)) != NULL)
10448 "ASYNC NOTIFY of '%s' received from backend PID %d\n",
10449 notify-
>relname, notify-
>be_pid);
10452 PQconsumeInput(conn);
10456 fprintf(stderr,
"Done.\n");
10458 /* close the connection to the database and cleanup */
10467 <example id=
"libpq-example-3">
10468 <title><application>libpq
</application> Example Program
3</title>
10473 * src/test/examples/testlibpq3.c
10477 * Test out-of-line parameters and binary I/O.
10479 * Before running this, populate a database with the following commands
10480 * (provided in src/test/examples/testlibpq3.sql):
10482 * CREATE SCHEMA testlibpq3;
10483 * SET search_path = testlibpq3;
10484 * SET standard_conforming_strings = ON;
10485 * CREATE TABLE test1 (i int4, t text, b bytea);
10486 * INSERT INTO test1 values (
1, 'joe''s place', '\
000\
001\
002\
003\
004');
10487 * INSERT INTO test1 values (
2, 'ho there', '\
004\
003\
002\
001\
000');
10489 * The expected output is:
10493 * t = (
11 bytes) 'joe's place'
10494 * b = (
5 bytes) \
000\
001\
002\
003\
004
10498 * t = (
8 bytes) 'ho there'
10499 * b = (
5 bytes) \
004\
003\
002\
001\
000
10503 #include
<windows.h
>
10507 #include
<stdlib.h
>
10508 #include
<stdint.h
>
10509 #include
<string.h
>
10510 #include
<sys/types.h
>
10511 #include
"libpq-fe.h"
10513 /* for ntohl/htonl */
10514 #include
<netinet/in.h
>
10515 #include
<arpa/inet.h
>
10519 exit_nicely(PGconn *conn)
10526 * This function prints a query result that is a binary-format fetch from
10527 * a table defined as in the comment above. We split it out because the
10528 * main() function uses it twice.
10531 show_binary_results(PGresult *res)
10539 /* Use PQfnumber to avoid assumptions about field order in result */
10540 i_fnum = PQfnumber(res,
"i");
10541 t_fnum = PQfnumber(res,
"t");
10542 b_fnum = PQfnumber(res,
"b");
10544 for (i =
0; i < PQntuples(res); i++)
10552 /* Get the field values (we ignore possibility they are null!) */
10553 iptr = PQgetvalue(res, i, i_fnum);
10554 tptr = PQgetvalue(res, i, t_fnum);
10555 bptr = PQgetvalue(res, i, b_fnum);
10558 * The binary representation of INT4 is in network byte order, which
10559 * we'd better coerce to the local byte order.
10561 ival = ntohl(*((uint32_t *) iptr));
10564 * The binary representation of TEXT is, well, text, and since libpq
10565 * was nice enough to append a zero byte to it, it'll work just fine
10568 * The binary representation of BYTEA is a bunch of bytes, which could
10569 * include embedded nulls so we have to pay attention to field length.
10571 blen = PQgetlength(res, i, b_fnum);
10573 printf(
"tuple %d: got\n", i);
10574 printf(
" i = (%d bytes) %d\n",
10575 PQgetlength(res, i, i_fnum), ival);
10576 printf(
" t = (%d bytes) '%s'\n",
10577 PQgetlength(res, i, t_fnum), tptr);
10578 printf(
" b = (%d bytes) ", blen);
10579 for (j =
0; j < blen; j++)
10580 printf(
"\\%03o", bptr[j]);
10586 main(int argc, char **argv)
10588 const char *conninfo;
10591 const char *paramValues[
1];
10592 int paramLengths[
1];
10593 int paramFormats[
1];
10594 uint32_t binaryIntVal;
10597 * If the user supplies a parameter on the command line, use it as the
10598 * conninfo string; otherwise default to setting dbname=postgres and using
10599 * environment variables or defaults for all other connection parameters.
10602 conninfo = argv[
1];
10604 conninfo =
"dbname = postgres";
10606 /* Make a connection to the database */
10607 conn = PQconnectdb(conninfo);
10609 /* Check to see that the backend connection was successfully made */
10610 if (PQstatus(conn) != CONNECTION_OK)
10612 fprintf(stderr,
"%s", PQerrorMessage(conn));
10616 /* Set always-secure search path, so malicious users can't take control. */
10617 res = PQexec(conn,
"SET search_path = testlibpq3");
10618 if (PQresultStatus(res) != PGRES_COMMAND_OK)
10620 fprintf(stderr,
"SET failed: %s", PQerrorMessage(conn));
10627 * The point of this program is to illustrate use of PQexecParams() with
10628 * out-of-line parameters, as well as binary transmission of data.
10630 * This first example transmits the parameters as text, but receives the
10631 * results in binary format. By using out-of-line parameters we can avoid
10632 * a lot of tedious mucking about with quoting and escaping, even though
10633 * the data is text. Notice how we don't have to do anything special with
10634 * the quote mark in the parameter value.
10637 /* Here is our out-of-line parameter value */
10638 paramValues[
0] =
"joe's place";
10640 res = PQexecParams(conn,
10641 "SELECT * FROM test1 WHERE t = $1",
10643 NULL, /* let the backend deduce param type */
10645 NULL, /* don't need param lengths since text */
10646 NULL, /* default to all text params */
10647 1); /* ask for binary results */
10649 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10651 fprintf(stderr,
"SELECT failed: %s", PQerrorMessage(conn));
10656 show_binary_results(res);
10661 * In this second example we transmit an integer parameter in binary form,
10662 * and again retrieve the results in binary form.
10664 * Although we tell PQexecParams we are letting the backend deduce
10665 * parameter type, we really force the decision by casting the parameter
10666 * symbol in the query text. This is a good safety measure when sending
10667 * binary parameters.
10670 /* Convert integer value
"2" to network byte order */
10671 binaryIntVal = htonl((uint32_t)
2);
10673 /* Set up parameter arrays for PQexecParams */
10674 paramValues[
0] = (char *)
&binaryIntVal;
10675 paramLengths[
0] = sizeof(binaryIntVal);
10676 paramFormats[
0] =
1; /* binary */
10678 res = PQexecParams(conn,
10679 "SELECT * FROM test1 WHERE i = $1::int4",
10681 NULL, /* let the backend deduce param type */
10685 1); /* ask for binary results */
10687 if (PQresultStatus(res) != PGRES_TUPLES_OK)
10689 fprintf(stderr,
"SELECT failed: %s", PQerrorMessage(conn));
10694 show_binary_results(res);
10698 /* close the connection to the database and cleanup */