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<
/>.
17 <application>libpq<
/> is a set of library functions that allow
18 client programs to pass queries to the
<productname>PostgreSQL<
/>
19 backend server and to receive the results of these queries.
23 <application>libpq<
/> is also the underlying engine for several
24 other
<productname>PostgreSQL<
/> application interfaces, including
25 those written for C++, Perl, Python, Tcl and
<application>ECPG<
/>.
26 So some aspects of
<application>libpq<
/>'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<
/>.
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<
/><
/>
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<
/><indexterm><primary>PGconn<
/><
/> object, which
59 is obtained from the function
<function>PQconnectdb<
/> or
60 <function>PQsetdbLogin<
/>. Note that these functions will always
61 return a non-null object pointer, unless perhaps there is too
62 little memory even to allocate the
<structname>PGconn<
/> object.
63 The
<function>PQstatus<
/> function should be called to check
64 whether a connection was successfully made before queries are sent
65 via the connection object.
69 <term><function>PQconnectdb
</function><indexterm><primary>PQconnectdb<
/><
/></term>
72 Makes a new connection to the database server.
75 PGconn *PQconnectdb(const char *conninfo);
80 This function opens a new database connection using the parameters taken
81 from the string
<literal>conninfo
</literal>. Unlike
<function>PQsetdbLogin<
/> below,
82 the parameter set can be extended without changing the function signature,
83 so use of this function (or its nonblocking analogues
<function>PQconnectStart<
/>
84 and
<function>PQconnectPoll
</function>) is preferred for new application programming.
89 can be empty to use all default parameters, or it can contain one or more
90 parameter settings separated by whitespace.
91 Each parameter setting is in the form
<literal>keyword = value
</literal>.
92 Spaces around the equal sign are optional.
93 To write an empty value or a value containing
94 spaces, surround it with single quotes, e.g.,
95 <literal>keyword = 'a value'
</literal>.
96 Single quotes and backslashes within the value must be escaped with a
97 backslash, i.e.,
<literal>\'
</literal> and
<literal>\\
</literal>.
101 The currently recognized parameter key words are:
105 <term><literal>host
</literal></term>
108 Name of host to connect to.
<indexterm><primary>host name<
/><
/>
109 If this begins with a slash, it specifies Unix-domain
110 communication rather than TCP/IP communication; the value is the
111 name of the directory in which the socket file is stored. The
112 default behavior when
<literal>host
</literal> is not specified
113 is to connect to a Unix-domain
114 socket
<indexterm><primary>Unix domain socket<
/><
/> in
115 <filename>/tmp
</filename> (or whatever socket directory was specified
116 when
<productname>PostgreSQL<
/> was built). On machines without
117 Unix-domain sockets, the default is to connect to
<literal>localhost<
/>.
123 <term><literal>hostaddr
</literal></term>
126 Numeric IP address of host to connect to. This should be in the
127 standard IPv4 address format, e.g.,
<literal>172.28.40.9<
/>. If
128 your machine supports IPv6, you can also use those addresses.
129 TCP/IP communication is
130 always used when a nonempty string is specified for this parameter.
134 Using
<literal>hostaddr<
/> instead of
<literal>host<
/> allows the
135 application to avoid a host name look-up, which might be important in
136 applications with time constraints. However, Kerberos and GSSAPI authentication
137 requires the host name. The following therefore applies: If
138 <literal>host<
/> is specified without
<literal>hostaddr<
/>, a host name
139 lookup occurs. If
<literal>hostaddr<
/> is specified without
140 <literal>host<
/>, the value for
<literal>hostaddr<
/> gives the remote
141 address. When Kerberos is used, a reverse name query occurs to obtain
142 the host name for Kerberos. If both
143 <literal>host<
/> and
<literal>hostaddr<
/> are specified, the value for
144 <literal>hostaddr<
/> gives the remote address; the value for
145 <literal>host<
/> is ignored, unless Kerberos is used, in which case that
146 value is used for Kerberos authentication. (Note that authentication is
147 likely to fail if
<application>libpq
</application> is passed a host name
148 that is not the name of the machine at
<literal>hostaddr<
/>.) Also,
149 <literal>host<
/> rather than
<literal>hostaddr<
/> is used to identify
150 the connection in
<filename>~/.pgpass<
/> (see
151 <xref linkend=
"libpq-pgpass">).
155 Without either a host name or host address,
156 <application>libpq
</application> will connect using a
157 local Unix-domain socket; or on machines without Unix-domain
158 sockets, it will attempt to connect to
<literal>localhost<
/>.
164 <term><literal>port
</literal></term>
167 Port number to connect to at the server host, or socket file
168 name extension for Unix-domain
169 connections.
<indexterm><primary>port<
/><
/>
175 <term><literal>dbname
</literal></term>
178 The database name. Defaults to be the same as the user name.
184 <term><literal>user
</literal></term>
187 <productname>PostgreSQL
</productname> user name to connect as.
188 Defaults to be the same as the operating system name of the user
189 running the application.
195 <term><literal>password
</literal></term>
198 Password to be used if the server demands password authentication.
204 <term><literal>connect_timeout
</literal></term>
207 Maximum wait for connection, in seconds (write as a decimal integer
208 string). Zero or not specified means wait indefinitely. It is not
209 recommended to use a timeout of less than
2 seconds.
215 <term><literal>options
</literal></term>
218 Command-line options to be sent to the server.
224 <term><literal>tty
</literal></term>
227 Ignored (formerly, this specified where to send server debug output).
233 <term><literal>sslmode
</literal></term>
236 This option determines whether or with what priority a
237 <acronym>SSL<
/> TCP/IP connection will be negotiated with the
238 server. There are four modes:
<literal>disable<
/> will attempt
239 only an unencrypted
<acronym>SSL<
/> connection;
240 <literal>allow<
/> will negotiate, trying first a
241 non-
<acronym>SSL<
/> connection, then if that fails, trying an
242 <acronym>SSL<
/> connection;
<literal>prefer<
/> (the default)
243 will negotiate, trying first an
<acronym>SSL<
/> connection,
244 then if that fails, trying a regular non-
<acronym>SSL<
/>
245 connection;
<literal>require<
/> will try only an
246 <acronym>SSL<
/> connection.
<literal>sslmode<
/> is ignored
247 for Unix domain socket communication.
251 If
<productname>PostgreSQL<
/> is compiled without SSL support,
252 using option
<literal>require<
/> will cause an error, while
253 options
<literal>allow<
/> and
<literal>prefer<
/> will be
254 accepted but
<application>libpq<
/> will not in fact attempt
256 connection.
<indexterm><primary>SSL<
/><secondary
257 sortas=
"libpq">with libpq<
/></indexterm>
263 <term><literal>sslverify
</literal></term>
266 This option controls how libpq verifies the certificate on the
267 server when performing an
<acronym>SSL<
/> connection. There are
268 three options:
<literal>none<
/> disables verification completely
269 (not recommended!);
<literal>cert<
/> enables verification that
270 the certificate chains to a known CA only;
<literal>cn<
/> will
271 both verify that the certificate chains to a known CA and that
272 the
<literal>cn<
/> attribute of the certificate matches the
273 hostname the connection is being made to (default).
277 It is always recommended to use the
<literal>cn<
/> value for
278 this parameter, since this is the only option that prevents
279 man-in-the-middle attacks. Note that this requires the server
280 name on the certificate to match exactly with the host name
281 used for the connection, and therefore does not support connections
282 to aliased names. It can be used with pure IP address connections
283 only if the certificate also has just the IP address in the
284 <literal>cn<
/> field.
288 If the
<literal>cn<
/> attribute in the certificate sent by the
289 server starts with an asterisk (
<literal>*<
/>), it will be treated
290 as a wildcard. This wildcard can only be present at the start of
291 the value, and will match all characters
<emphasis>except<
/> a
292 dot (
<literal>.<
/>). This means the certificate will not match
299 <term><literal>requiressl
</literal></term>
302 This option is deprecated in favor of the
<literal>sslmode<
/>
307 If set to
1, an
<acronym>SSL
</acronym> connection to the server
308 is required (this is equivalent to
<literal>sslmode<
/>
309 <literal>require<
/>).
<application>libpq<
/> will then refuse
310 to connect if the server does not accept an
311 <acronym>SSL
</acronym> connection. If set to
0 (default),
312 <application>libpq<
/> will negotiate the connection type with
313 the server (equivalent to
<literal>sslmode<
/>
314 <literal>prefer<
/>). This option is only available if
315 <productname>PostgreSQL<
/> is compiled with SSL support.
321 <term><literal>sslcert
</literal></term>
324 This parameter specifies the file name of the client SSL
331 <term><literal>sslkey
</literal></term>
334 This parameter specifies the location for the secret key
335 used for the client certificate. It can either specify a filename
336 that will be used instead of the default
337 <filename>~/.postgresql/postgresql.key<
/>, or can specify an external
338 engine (engines are
<productname>OpenSSL<
/> loadable modules). The
339 external engine specification should consist of a colon-separated
340 engine name and an engine-specific key identifier.
346 <term><literal>sslrootcert
</literal></term>
349 This parameter specifies the file name of the root SSL certificate.
355 <term><literal>sslcrl
</literal></term>
358 This parameter specifies the file name of the SSL certificate
359 revocation list (CRL).
365 <term><literal>krbsrvname
</literal></term>
368 Kerberos service name to use when authenticating with Kerberos
5
370 This must match the service name specified in the server
371 configuration for Kerberos authentication to succeed. (See also
372 <xref linkend=
"kerberos-auth"> and
<xref linkend=
"gssapi-auth">.)
378 <term><literal>gsslib
</literal></term>
381 GSS library to use for GSSAPI authentication. Only used on Windows.
382 Set to
<literal>gssapi
</literal> to force libpq to use the GSSAPI
383 library for authentication instead of the default SSPI.
389 <term><literal>service
</literal></term>
392 Service name to use for additional parameters. It specifies a service
393 name in
<filename>pg_service.conf
</filename> that holds additional connection parameters.
394 This allows applications to specify only a service name so connection parameters
395 can be centrally maintained. See
<xref linkend=
"libpq-pgservice">.
401 If any parameter is unspecified, then the corresponding
402 environment variable (see
<xref linkend=
"libpq-envars">)
403 is checked. If the environment variable is not set either,
404 then the indicated built-in defaults are used.
410 <term><function>PQsetdbLogin
</function><indexterm><primary>PQsetdbLogin<
/><
/></term>
413 Makes a new connection to the database server.
415 PGconn *PQsetdbLogin(const char *pghost,
417 const char *pgoptions,
426 This is the predecessor of
<function>PQconnectdb
</function> with a fixed
427 set of parameters. It has the same functionality except that the
428 missing parameters will always take on default values. Write
<symbol>NULL
</symbol> or an
429 empty string for any one of the fixed parameters that is to be defaulted.
433 If the
<parameter>dbName
</parameter> contains an
<symbol>=
</symbol> sign, it
434 is taken as a
<parameter>conninfo
</parameter> string in exactly the same way as
435 if it had been passed to
<function>PQconnectdb
</function>, and the remaining
436 parameters are then applied as above.
442 <term><function>PQsetdb
</function><indexterm><primary>PQsetdb<
/><
/></term>
445 Makes a new connection to the database server.
447 PGconn *PQsetdb(char *pghost,
456 This is a macro that calls
<function>PQsetdbLogin
</function> with null pointers
457 for the
<parameter>login<
/> and
<parameter>pwd<
/> parameters. It is provided
458 for backward compatibility with very old programs.
464 <term><function>PQconnectStart
</function><indexterm><primary>PQconnectStart<
/><
/></term>
465 <term><function>PQconnectPoll
</function><indexterm><primary>PQconnectPoll<
/><
/></term>
468 <indexterm><primary>nonblocking connection
</primary></indexterm>
469 Make a connection to the database server in a nonblocking manner.
472 PGconn *PQconnectStart(const char *conninfo);
476 PostgresPollingStatusType PQconnectPoll(PGconn *conn);
481 These two functions are used to open a connection to a database server such
482 that your application's thread of execution is not blocked on remote I/O
484 The point of this approach is that the waits for I/O to complete can occur
485 in the application's main loop, rather than down inside
486 <function>PQconnectdb<
/>, and so the application can manage this
487 operation in parallel with other activities.
491 The database connection is made using the parameters taken from the string
492 <literal>conninfo
</literal>, passed to
<function>PQconnectStart
</function>. This string is in
493 the same format as described above for
<function>PQconnectdb
</function>.
496 Neither
<function>PQconnectStart
</function> nor
<function>PQconnectPoll
</function> will block, so long as a number of
497 restrictions are met:
501 The
<literal>hostaddr<
/> and
<literal>host<
/> parameters are used appropriately to ensure that
502 name and reverse name queries are not made. See the documentation of
503 these parameters under
<function>PQconnectdb
</function> above for details.
509 If you call
<function>PQtrace
</function>, ensure that the stream object
510 into which you trace will not block.
516 You ensure that the socket is in the appropriate state
517 before calling
<function>PQconnectPoll
</function>, as described below.
524 To begin a nonblocking connection request, call
<literal>conn = PQconnectStart(
"<replaceable>connection_info_string</>")
</literal>.
525 If
<varname>conn
</varname> is null, then
<application>libpq<
/> has been unable to allocate a new
<structname>PGconn<
/>
526 structure. Otherwise, a valid
<structname>PGconn<
/> pointer is returned (though not yet
527 representing a valid connection to the database). On return from
528 <function>PQconnectStart
</function>, call
<literal>status = PQstatus(conn)
</literal>. If
<varname>status
</varname> equals
529 <symbol>CONNECTION_BAD
</symbol>,
<function>PQconnectStart
</function> has failed.
533 If
<function>PQconnectStart<
/> succeeds, the next stage is to poll
534 <application>libpq<
/> so that it can proceed with the connection sequence.
535 Use
<function>PQsocket(conn)
</function> to obtain the descriptor of the
536 socket underlying the database connection.
537 Loop thus: If
<function>PQconnectPoll(conn)
</function> last returned
538 <symbol>PGRES_POLLING_READING
</symbol>, wait until the socket is ready to
539 read (as indicated by
<function>select()<
/>,
<function>poll()<
/>, or
540 similar system function).
541 Then call
<function>PQconnectPoll(conn)
</function> again.
542 Conversely, if
<function>PQconnectPoll(conn)
</function> last returned
543 <symbol>PGRES_POLLING_WRITING
</symbol>, wait until the socket is ready
544 to write, then call
<function>PQconnectPoll(conn)
</function> again.
545 If you have yet to call
546 <function>PQconnectPoll
</function>, i.e., just after the call to
547 <function>PQconnectStart
</function>, behave as if it last returned
548 <symbol>PGRES_POLLING_WRITING
</symbol>. Continue this loop until
549 <function>PQconnectPoll(conn)
</function> returns
550 <symbol>PGRES_POLLING_FAILED
</symbol>, indicating the connection procedure
551 has failed, or
<symbol>PGRES_POLLING_OK
</symbol>, indicating the connection
552 has been successfully made.
556 At any time during connection, the status of the connection can be
557 checked by calling
<function>PQstatus<
/>. If this gives
<symbol>CONNECTION_BAD<
/>, then the
558 connection procedure has failed; if it gives
<function>CONNECTION_OK<
/>, then the
559 connection is ready. Both of these states are equally detectable
560 from the return value of
<function>PQconnectPoll<
/>, described above. Other states might also occur
561 during (and only during) an asynchronous connection procedure. These
562 indicate the current stage of the connection procedure and might be useful
563 to provide feedback to the user for example. These statuses are:
567 <term><symbol>CONNECTION_STARTED
</symbol></term>
570 Waiting for connection to be made.
576 <term><symbol>CONNECTION_MADE
</symbol></term>
579 Connection OK; waiting to send.
585 <term><symbol>CONNECTION_AWAITING_RESPONSE
</symbol></term>
588 Waiting for a response from the server.
594 <term><symbol>CONNECTION_AUTH_OK
</symbol></term>
597 Received authentication; waiting for backend start-up to finish.
603 <term><symbol>CONNECTION_SSL_STARTUP
</symbol></term>
606 Negotiating SSL encryption.
612 <term><symbol>CONNECTION_SETENV
</symbol></term>
615 Negotiating environment-driven parameter settings.
621 Note that, although these constants will remain (in order to maintain
622 compatibility), an application should never rely upon these occurring in a
623 particular order, or at all, or on the status always being one of these
624 documented values. An application might do something like this:
626 switch(PQstatus(conn))
628 case CONNECTION_STARTED:
629 feedback =
"Connecting...";
632 case CONNECTION_MADE:
633 feedback =
"Connected to server...";
639 feedback =
"Connecting...";
645 The
<literal>connect_timeout
</literal> connection parameter is ignored
646 when using
<function>PQconnectPoll
</function>; it is the application's
647 responsibility to decide whether an excessive amount of time has elapsed.
648 Otherwise,
<function>PQconnectStart
</function> followed by a
649 <function>PQconnectPoll
</function> loop is equivalent to
650 <function>PQconnectdb
</function>.
654 Note that if
<function>PQconnectStart
</function> returns a non-null pointer, you must call
655 <function>PQfinish
</function> when you are finished with it, in order to dispose of
656 the structure and any associated memory blocks. This must be done even if
657 the connection attempt fails or is abandoned.
663 <term><function>PQconndefaults
</function><indexterm><primary>PQconndefaults<
/><
/></term>
666 Returns the default connection options.
668 PQconninfoOption *PQconndefaults(void);
672 char *keyword; /* The keyword of the option */
673 char *envvar; /* Fallback environment variable name */
674 char *compiled; /* Fallback compiled in default value */
675 char *val; /* Option's current value, or NULL */
676 char *label; /* Label for field in connect dialog */
677 char *dispchar; /* Indicates how to display this field
678 in a connect dialog. Values are:
679 "" Display entered value as is
680 "*" Password field - hide value
681 "D" Debug option - don't show by default */
682 int dispsize; /* Field size in characters for dialog */
688 Returns a connection options array. This can be used to determine
689 all possible
<function>PQconnectdb
</function> options and their
690 current default values. The return value points to an array of
691 <structname>PQconninfoOption
</structname> structures, which ends
692 with an entry having a null
<structfield>keyword<
/> pointer. The
693 null pointer is returned if memory could not be allocated. Note that
694 the current default values (
<structfield>val
</structfield> fields)
695 will depend on environment variables and other context. Callers
696 must treat the connection options data as read-only.
700 After processing the options array, free it by passing it to
701 <function>PQconninfoFree
</function>. If this is not done, a small amount of memory
702 is leaked for each call to
<function>PQconndefaults
</function>.
709 <term><function>PQconninfoParse
</function><indexterm><primary>PQconninfoParse<
/><
/></term>
712 Returns parsed connection options from the provided connection string.
715 PQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg);
720 Parses a connection string and returns the resulting options as an
721 array; or returns NULL if there is a problem with the connection
722 string. This can be used to determine
723 the
<function>PQconnectdb
</function> options in the provided
724 connection string. The return value points to an array of
725 <structname>PQconninfoOption
</structname> structures, which ends
726 with an entry having a null
<structfield>keyword<
/> pointer.
730 Note that only options explicitly specified in the string will have
731 values set in the result array; no defaults are inserted.
735 If
<literal>errmsg<
/> is not NULL, then
<literal>*errmsg<
/> is set
736 to NULL on success, else to a malloc'd error string explaining
737 the problem. (It is also possible for
<literal>*errmsg<
/> to be
738 set to NULL even when NULL is returned; this indicates an out-of-memory
743 After processing the options array, free it by passing it to
744 <function>PQconninfoFree
</function>. If this is not done, some memory
745 is leaked for each call to
<function>PQconninfoParse
</function>.
746 Conversely, if an error occurs and
<literal>errmsg<
/> is not NULL,
747 be sure to free the error string using
<function>PQfreemem<
/>.
754 <term><function>PQfinish
</function><indexterm><primary>PQfinish<
/><
/></term>
757 Closes the connection to the server. Also frees
758 memory used by the
<structname>PGconn
</structname> object.
760 void PQfinish(PGconn *conn);
765 Note that even if the server connection attempt fails (as
766 indicated by
<function>PQstatus
</function>), the application should call
<function>PQfinish
</function>
767 to free the memory used by the
<structname>PGconn
</structname> object.
768 The
<structname>PGconn<
/> pointer must not be used again after
769 <function>PQfinish
</function> has been called.
775 <term><function>PQreset
</function><indexterm><primary>PQreset<
/><
/></term>
778 Resets the communication channel to the server.
780 void PQreset(PGconn *conn);
785 This function will close the connection
786 to the server and attempt to reestablish a new
787 connection to the same server, using all the same
788 parameters previously used. This might be useful for
789 error recovery if a working connection is lost.
795 <term><function>PQresetStart
</function><indexterm><primary>PQresetStart<
/><
/></term>
796 <term><function>PQresetPoll
</function><indexterm><primary>PQresetPoll<
/><
/></term>
799 Reset the communication channel to the server, in a nonblocking manner.
802 int PQresetStart(PGconn *conn);
805 PostgresPollingStatusType PQresetPoll(PGconn *conn);
810 These functions will close the connection to the server and attempt to
811 reestablish a new connection to the same server, using all the same
812 parameters previously used. This can be useful for error recovery if a
813 working connection is lost. They differ from
<function>PQreset
</function> (above) in that they
814 act in a nonblocking manner. These functions suffer from the same
815 restrictions as
<function>PQconnectStart<
/> and
<function>PQconnectPoll<
/>.
819 To initiate a connection reset, call
820 <function>PQresetStart
</function>. If it returns
0, the reset has
821 failed. If it returns
1, poll the reset using
822 <function>PQresetPoll
</function> in exactly the same way as you
823 would create the connection using
<function>PQconnectPoll
</function>.
832 <sect1 id=
"libpq-status">
833 <title>Connection Status Functions
</title>
836 These functions can be used to interrogate the status
837 of an existing database connection object.
842 <indexterm><primary>libpq-fe.h<
/><
/>
843 <indexterm><primary>libpq-int.h<
/><
/>
844 <application>libpq
</application> application programmers should be careful to
845 maintain the
<structname>PGconn
</structname> abstraction. Use the accessor
846 functions described below to get at the contents of
<structname>PGconn
</structname>.
847 Reference to internal
<structname>PGconn
</structname> fields using
848 <filename>libpq-int.h<
/> is not recommended because they are subject to change
854 The following functions return parameter values established at connection.
855 These values are fixed for the life of the
<structname>PGconn<
/> object.
860 <function>PQdb
</function>
862 <primary>PQdb
</primary>
868 Returns the database name of the connection.
870 char *PQdb(const PGconn *conn);
878 <function>PQuser
</function>
880 <primary>PQuser
</primary>
886 Returns the user name of the connection.
888 char *PQuser(const PGconn *conn);
896 <function>PQpass
</function>
898 <primary>PQpass
</primary>
904 Returns the password of the connection.
906 char *PQpass(const PGconn *conn);
914 <function>PQhost
</function>
916 <primary>PQhost
</primary>
922 Returns the server host name of the connection.
924 char *PQhost(const PGconn *conn);
932 <function>PQport
</function>
934 <primary>PQport
</primary>
940 Returns the port of the connection.
943 char *PQport(const PGconn *conn);
951 <function>PQtty
</function>
953 <primary>PQtty
</primary>
959 Returns the debug
<acronym>TTY
</acronym> of the connection.
960 (This is obsolete, since the server no longer pays attention
961 to the
<acronym>TTY
</acronym> setting, but the function remains
962 for backwards compatibility.)
965 char *PQtty(const PGconn *conn);
973 <function>PQoptions
</function>
975 <primary>PQoptions
</primary>
981 Returns the command-line options passed in the connection request.
983 char *PQoptions(const PGconn *conn);
992 The following functions return status data that can change as operations
993 are executed on the
<structname>PGconn<
/> object.
998 <function>PQstatus
</function>
1000 <primary>PQstatus
</primary>
1006 Returns the status of the connection.
1008 ConnStatusType PQstatus(const PGconn *conn);
1013 The status can be one of a number of values. However, only two of
1014 these are seen outside of an asynchronous connection procedure:
1015 <literal>CONNECTION_OK
</literal> and
1016 <literal>CONNECTION_BAD
</literal>. A good connection to the database
1017 has the status
<literal>CONNECTION_OK
</literal>. A failed
1018 connection attempt is signaled by status
1019 <literal>CONNECTION_BAD
</literal>. Ordinarily, an OK status will
1020 remain so until
<function>PQfinish
</function>, but a communications
1021 failure might result in the status changing to
1022 <literal>CONNECTION_BAD
</literal> prematurely. In that case the
1023 application could try to recover by calling
1024 <function>PQreset
</function>.
1028 See the entry for
<function>PQconnectStart<
/> and
<function>PQconnectPoll<
/> with regards
1029 to other status codes
1037 <function>PQtransactionStatus
</function>
1039 <primary>PQtransactionStatus
</primary>
1045 Returns the current in-transaction status of the server.
1048 PGTransactionStatusType PQtransactionStatus(const PGconn *conn);
1051 The status can be
<literal>PQTRANS_IDLE
</literal> (currently idle),
1052 <literal>PQTRANS_ACTIVE
</literal> (a command is in progress),
1053 <literal>PQTRANS_INTRANS
</literal> (idle, in a valid transaction block),
1054 or
<literal>PQTRANS_INERROR
</literal> (idle, in a failed transaction block).
1055 <literal>PQTRANS_UNKNOWN
</literal> is reported if the connection is bad.
1056 <literal>PQTRANS_ACTIVE
</literal> is reported only when a query
1057 has been sent to the server and not yet completed.
1062 <function>PQtransactionStatus<
/> will give incorrect results when using
1063 a
<productname>PostgreSQL<
/> 7.3 server that has the parameter
<literal>autocommit<
/>
1064 set to off. The server-side autocommit feature has been
1065 deprecated and does not exist in later server versions.
1073 <function>PQparameterStatus
</function>
1075 <primary>PQparameterStatus
</primary>
1081 Looks up a current parameter setting of the server.
1084 const char *PQparameterStatus(const PGconn *conn, const char *paramName);
1087 Certain parameter values are reported by the server automatically at
1088 connection startup or whenever their values change.
1089 <function>PQparameterStatus<
/> can be used to interrogate these settings.
1090 It returns the current value of a parameter if known, or
<symbol>NULL
</symbol>
1091 if the parameter is not known.
1095 Parameters reported as of the current release include
1096 <literal>server_version<
/>,
1097 <literal>server_encoding<
/>,
1098 <literal>client_encoding<
/>,
1099 <literal>is_superuser<
/>,
1100 <literal>session_authorization<
/>,
1101 <literal>DateStyle<
/>,
1102 <literal>IntervalStyle<
/>,
1103 <literal>TimeZone<
/>,
1104 <literal>integer_datetimes<
/>, and
1105 <literal>standard_conforming_strings<
/>.
1106 (
<literal>server_encoding<
/>,
<literal>TimeZone<
/>, and
1107 <literal>integer_datetimes<
/> were not reported by releases before
8.0;
1108 <literal>standard_conforming_strings<
/> was not reported by releases
1109 before
8.1;
<literal>IntervalStyle<
/> was not reported by releases
1112 <literal>server_version<
/>,
1113 <literal>server_encoding<
/> and
1114 <literal>integer_datetimes<
/>
1115 cannot change after startup.
1119 Pre-
3.0-protocol servers do not report parameter settings, but
1120 <application>libpq<
/> includes logic to obtain values for
1121 <literal>server_version<
/> and
<literal>client_encoding<
/> anyway.
1122 Applications are encouraged to use
<function>PQparameterStatus<
/>
1123 rather than
<foreignphrase>ad hoc<
/> code to determine these values.
1124 (Beware however that on a pre-
3.0 connection, changing
1125 <literal>client_encoding<
/> via
<command>SET<
/> after connection
1126 startup will not be reflected by
<function>PQparameterStatus<
/>.)
1127 For
<literal>server_version<
/>, see also
1128 <function>PQserverVersion<
/>, which returns the information in a
1129 numeric form that is much easier to compare against.
1133 If no value for
<literal>standard_conforming_strings<
/> is reported,
1134 applications can assume it is
<literal>off<
/>, that is, backslashes
1135 are treated as escapes in string literals. Also, the presence of
1136 this parameter can be taken as an indication that the escape string
1137 syntax (
<literal>E'...'<
/>) is accepted.
1141 Although the returned pointer is declared
<literal>const<
/>, it in fact
1142 points to mutable storage associated with the
<literal>PGconn<
/> structure.
1143 It is unwise to assume the pointer will remain valid across queries.
1150 <function>PQprotocolVersion
</function>
1152 <primary>PQprotocolVersion
</primary>
1158 Interrogates the frontend/backend protocol being used.
1160 int PQprotocolVersion(const PGconn *conn);
1162 Applications might wish to use this to determine whether certain
1163 features are supported. Currently, the possible values are
2 (
2.0
1164 protocol),
3 (
3.0 protocol), or zero (connection bad). This will
1165 not change after connection startup is complete, but it could
1166 theoretically change during a connection reset. The
3.0 protocol
1167 will normally be used when communicating with
1168 <productname>PostgreSQL<
/> 7.4 or later servers; pre-
7.4 servers
1169 support only protocol
2.0. (Protocol
1.0 is obsolete and not
1170 supported by
<application>libpq
</application>.)
1177 <function>PQserverVersion
</function>
1179 <primary>PQserverVersion
</primary>
1185 Returns an integer representing the backend version.
1187 int PQserverVersion(const PGconn *conn);
1189 Applications might use this to determine the version of the database
1190 server they are connected to. The number is formed by converting
1191 the major, minor, and revision numbers into two-decimal-digit
1192 numbers and appending them together. For example, version
8.1.5
1193 will be returned as
80105, and version
8.2 will be returned as
1194 80200 (leading zeroes are not shown). Zero is returned if the
1202 <function>PQerrorMessage
</function>
1204 <primary>PQerrorMessage
</primary>
1210 <indexterm><primary>error message<
/><
/> Returns the error message
1211 most recently generated by an operation on the connection.
1214 char *PQerrorMessage(const PGconn *conn);
1220 Nearly all
<application>libpq<
/> functions will set a message for
1221 <function>PQerrorMessage
</function> if they fail. Note that by
1222 <application>libpq
</application> convention, a nonempty
1223 <function>PQerrorMessage
</function> result can be multiple lines,
1224 and will include a trailing newline. The caller should not free
1225 the result directly. It will be freed when the associated
1226 <structname>PGconn<
/> handle is passed to
1227 <function>PQfinish
</function>. The result string should not be
1228 expected to remain the same across operations on the
1229 <literal>PGconn<
/> structure.
1235 <term><function>PQsocket
</function><indexterm><primary>PQsocket<
/><
/></term>
1238 Obtains the file descriptor number of the connection socket to
1239 the server. A valid descriptor will be greater than or equal
1240 to
0; a result of -
1 indicates that no server connection is
1241 currently open. (This will not change during normal operation,
1242 but could change during connection setup or reset.)
1245 int PQsocket(const PGconn *conn);
1253 <term><function>PQbackendPID
</function><indexterm><primary>PQbackendPID<
/><
/></term>
1256 Returns the process
<acronym>ID
</acronym>
1257 (PID)
<indexterm><primary>PID<
/><secondary>determining PID of
1258 server process<
/><tertiary>in libpq<
/><
/> of the backend server
1259 process handling this connection.
1262 int PQbackendPID(const PGconn *conn);
1267 The backend
<acronym>PID
</acronym> is useful for debugging
1268 purposes and for comparison to
<command>NOTIFY
</command>
1269 messages (which include the
<acronym>PID
</acronym> of the
1270 notifying backend process). Note that the
1271 <acronym>PID
</acronym> belongs to a process executing on the
1272 database server host, not the local host!
1278 <term><function>PQconnectionNeedsPassword
</function><indexterm><primary>PQconnectionNeedsPassword<
/><
/></term>
1281 Returns true (
1) if the connection authentication method
1282 required a password, but none was available.
1283 Returns false (
0) if not.
1286 int PQconnectionNeedsPassword(const PGconn *conn);
1291 This function can be applied after a failed connection attempt
1292 to decide whether to prompt the user for a password.
1298 <term><function>PQconnectionUsedPassword
</function><indexterm><primary>PQconnectionUsedPassword<
/><
/></term>
1301 Returns true (
1) if the connection authentication method
1302 used a password. Returns false (
0) if not.
1305 int PQconnectionUsedPassword(const PGconn *conn);
1310 This function can be applied after either a failed or successful
1311 connection attempt to detect whether the server demanded a password.
1317 <term><function>PQgetssl
</function><indexterm><primary>PQgetssl<
/><
/></term>
1320 <indexterm><primary>SSL<
/><secondary sortas=
"libpq">in libpq
</secondary></indexterm>
1321 Returns the SSL structure used in the connection, or null
1322 if SSL is not in use.
1325 SSL *PQgetssl(const PGconn *conn);
1330 This structure can be used to verify encryption levels, check server
1331 certificates, and more. Refer to the
<productname>OpenSSL<
/>
1332 documentation for information about this structure.
1336 You must define
<symbol>USE_SSL
</symbol> in order to get the
1337 correct prototype for this function. Doing this will also
1338 automatically include
<filename>ssl.h
</filename> from
<productname>OpenSSL
</productname>.
1348 <sect1 id=
"libpq-exec">
1349 <title>Command Execution Functions
</title>
1352 Once a connection to a database server has been successfully
1353 established, the functions described here are used to perform
1354 SQL queries and commands.
1357 <sect2 id=
"libpq-exec-main">
1358 <title>Main Functions
</title>
1364 <function>PQexec
</function>
1366 <primary>PQexec
</primary>
1372 Submits a command to the server and waits for the result.
1375 PGresult *PQexec(PGconn *conn, const char *command);
1380 Returns a
<structname>PGresult
</structname> pointer or possibly a null
1381 pointer. A non-null pointer will generally be returned except in
1382 out-of-memory conditions or serious errors such as inability to send
1383 the command to the server. If a null pointer is returned, it should
1384 be treated like a
<symbol>PGRES_FATAL_ERROR
</symbol> result. Use
1385 <function>PQerrorMessage
</function> to get more information about such
1392 It is allowed to include multiple SQL commands (separated by semicolons)
1393 in the command string. Multiple queries sent in a single
1394 <function>PQexec<
/> call are processed in a single transaction, unless
1395 there are explicit
<command>BEGIN
</command>/
<command>COMMIT
</command>
1396 commands included in the query string to divide it into multiple
1397 transactions. Note however that the returned
1398 <structname>PGresult
</structname> structure describes only the result
1399 of the last command executed from the string. Should one of the
1400 commands fail, processing of the string stops with it and the returned
1401 <structname>PGresult
</structname> describes the error condition.
1408 <function>PQexecParams
</function>
1410 <primary>PQexecParams
</primary>
1416 Submits a command to the server and waits for the result,
1417 with the ability to pass parameters separately from the SQL
1421 PGresult *PQexecParams(PGconn *conn,
1422 const char *command,
1424 const Oid *paramTypes,
1425 const char * const *paramValues,
1426 const int *paramLengths,
1427 const int *paramFormats,
1433 <function>PQexecParams<
/> is like
<function>PQexec<
/>, but offers additional
1434 functionality: parameter values can be specified separately from the command
1435 string proper, and query results can be requested in either text or binary
1436 format.
<function>PQexecParams<
/> is supported only in protocol
3.0 and later
1437 connections; it will fail when using protocol
2.0.
1441 The function arguments are:
1445 <term><parameter>conn
</parameter></term>
1449 The connection object to send the command through.
1455 <term><parameter>command
</parameter></term>
1458 The SQL command string to be executed. If parameters are used,
1459 they are referred to in the command string as
<literal>$
1<
/>,
1460 <literal>$
2<
/>, etc.
1466 <term><parameter>nParams
</parameter></term>
1469 The number of parameters supplied; it is the length of the arrays
1470 <parameter>paramTypes[]<
/>,
<parameter>paramValues[]<
/>,
1471 <parameter>paramLengths[]<
/>, and
<parameter>paramFormats[]<
/>. (The
1472 array pointers can be
<symbol>NULL
</symbol> when
<parameter>nParams<
/>
1479 <term><parameter>paramTypes[]
</parameter></term>
1482 Specifies, by OID, the data types to be assigned to the
1483 parameter symbols. If
<parameter>paramTypes<
/> is
1484 <symbol>NULL
</symbol>, or any particular element in the array
1485 is zero, the server infers a data type for the parameter symbol
1486 in the same way it would do for an untyped literal string.
1492 <term><parameter>paramValues[]
</parameter></term>
1495 Specifies the actual values of the parameters. A null pointer
1496 in this array means the corresponding parameter is null;
1497 otherwise the pointer points to a zero-terminated text string
1498 (for text format) or binary data in the format expected by the
1499 server (for binary format).
1505 <term><parameter>paramLengths[]
</parameter></term>
1508 Specifies the actual data lengths of binary-format parameters.
1509 It is ignored for null parameters and text-format parameters.
1510 The array pointer can be null when there are no binary parameters.
1516 <term><parameter>paramFormats[]
</parameter></term>
1519 Specifies whether parameters are text (put a zero in the
1520 array entry for the corresponding parameter) or binary (put
1521 a one in the array entry for the corresponding parameter).
1522 If the array pointer is null then all parameters are presumed
1526 Values passed in binary format require knowlege of
1527 the internal representation expected by the backend.
1528 For example, integers must be passed in network byte
1529 order. Passing
<type>numeric<
/> values requires
1530 knowledge of the server storage format, as implemented
1532 <filename>src/backend/utils/adt/numeric.c::numeric_send()<
/> and
1533 <filename>src/backend/utils/adt/numeric.c::numeric_recv()<
/>.
1539 <term><parameter>resultFormat
</parameter></term>
1542 Specify zero to obtain results in text format, or one to obtain
1543 results in binary format. (There is not currently a provision
1544 to obtain different result columns in different formats,
1545 although that is possible in the underlying protocol.)
1557 The primary advantage of
<function>PQexecParams<
/> over
1558 <function>PQexec<
/> is that parameter values can be separated from the
1559 command string, thus avoiding the need for tedious and error-prone
1560 quoting and escaping.
1564 Unlike
<function>PQexec<
/>,
<function>PQexecParams<
/> allows at most
1565 one SQL command in the given string. (There can be semicolons in it,
1566 but not more than one nonempty command.) This is a limitation of the
1567 underlying protocol, but has some usefulness as an extra defense against
1568 SQL-injection attacks.
1573 Specifying parameter types via OIDs is tedious, particularly if you prefer
1574 not to hard-wire particular OID values into your program. However, you can
1575 avoid doing so even in cases where the server by itself cannot determine the
1576 type of the parameter, or chooses a different type than you want. In the
1577 SQL command text, attach an explicit cast to the parameter symbol to show what
1578 data type you will send. For example:
1580 SELECT * FROM mytable WHERE x = $
1::bigint;
1582 This forces parameter
<literal>$
1<
/> to be treated as
<type>bigint<
/>, whereas
1583 by default it would be assigned the same type as
<literal>x<
/>. Forcing the
1584 parameter type decision, either this way or by specifying a numeric type OID,
1585 is strongly recommended when sending parameter values in binary format, because
1586 binary format has less redundancy than text format and so there is less chance
1587 that the server will detect a type mismatch mistake for you.
1594 <term><function>PQprepare
</function>
1596 <primary>PQprepare
</primary>
1602 Submits a request to create a prepared statement with the
1603 given parameters, and waits for completion.
1605 PGresult *PQprepare(PGconn *conn,
1606 const char *stmtName,
1609 const Oid *paramTypes);
1614 <function>PQprepare<
/> creates a prepared statement for later
1615 execution with
<function>PQexecPrepared<
/>. This feature allows
1616 commands that will be used repeatedly to be parsed and planned just
1617 once, rather than each time they are executed.
1618 <function>PQprepare<
/> is supported only in protocol
3.0 and later
1619 connections; it will fail when using protocol
2.0.
1623 The function creates a prepared statement named
1624 <parameter>stmtName<
/> from the
<parameter>query<
/> string, which
1625 must contain a single SQL command.
<parameter>stmtName<
/> can be
1626 <literal>""<
/> to create an unnamed statement, in which case any
1627 pre-existing unnamed statement is automatically replaced; otherwise
1628 it is an error if the statement name is already defined in the
1629 current session. If any parameters are used, they are referred
1630 to in the query as
<literal>$
1<
/>,
<literal>$
2<
/>, etc.
1631 <parameter>nParams<
/> is the number of parameters for which types
1632 are pre-specified in the array
<parameter>paramTypes[]<
/>. (The
1633 array pointer can be
<symbol>NULL
</symbol> when
1634 <parameter>nParams<
/> is zero.)
<parameter>paramTypes[]<
/>
1635 specifies, by OID, the data types to be assigned to the parameter
1636 symbols. If
<parameter>paramTypes<
/> is
<symbol>NULL
</symbol>,
1637 or any particular element in the array is zero, the server assigns
1638 a data type to the parameter symbol in the same way it would do
1639 for an untyped literal string. Also, the query can use parameter
1640 symbols with numbers higher than
<parameter>nParams<
/>; data types
1641 will be inferred for these symbols as well. (See
1642 <function>PQdescribePrepared
</function> for a means to find out
1643 what data types were inferred.)
1647 As with
<function>PQexec<
/>, the result is normally a
1648 <structname>PGresult
</structname> object whose contents indicate
1649 server-side success or failure. A null result indicates
1650 out-of-memory or inability to send the command at all. Use
1651 <function>PQerrorMessage
</function> to get more information about
1658 Prepared statements for use with
<function>PQexecPrepared<
/> can also
1659 be created by executing SQL
<xref linkend=
"sql-prepare"
1660 endterm=
"sql-prepare-title"> statements. (But
<function>PQprepare<
/>
1661 is more flexible since it does not require parameter types to be
1662 pre-specified.) Also, although there is no
<application>libpq<
/>
1663 function for deleting a prepared statement, the SQL
<xref
1664 linkend=
"sql-deallocate" endterm=
"sql-deallocate-title"> statement
1665 can be used for that purpose.
1672 <function>PQexecPrepared
</function>
1674 <primary>PQexecPrepared
</primary>
1680 Sends a request to execute a prepared statement with given
1681 parameters, and waits for the result.
1683 PGresult *PQexecPrepared(PGconn *conn,
1684 const char *stmtName,
1686 const char * const *paramValues,
1687 const int *paramLengths,
1688 const int *paramFormats,
1694 <function>PQexecPrepared<
/> is like
<function>PQexecParams<
/>,
1695 but the command to be executed is specified by naming a
1696 previously-prepared statement, instead of giving a query string.
1697 This feature allows commands that will be used repeatedly to be
1698 parsed and planned just once, rather than each time they are
1699 executed. The statement must have been prepared previously in
1700 the current session.
<function>PQexecPrepared<
/> is supported
1701 only in protocol
3.0 and later connections; it will fail when
1706 The parameters are identical to
<function>PQexecParams<
/>, except that the
1707 name of a prepared statement is given instead of a query string, and the
1708 <parameter>paramTypes[]<
/> parameter is not present (it is not needed since
1709 the prepared statement's parameter types were determined when it was created).
1716 <function>PQdescribePrepared
</function>
1718 <primary>PQdescribePrepared
</primary>
1724 Submits a request to obtain information about the specified
1725 prepared statement, and waits for completion.
1727 PGresult *PQdescribePrepared(PGconn *conn, const char *stmtName);
1732 <function>PQdescribePrepared<
/> allows an application to obtain
1733 information about a previously prepared statement.
1734 <function>PQdescribePrepared<
/> is supported only in protocol
3.0
1735 and later connections; it will fail when using protocol
2.0.
1739 <parameter>stmtName<
/> can be
<literal>""<
/> or NULL to reference
1740 the unnamed statement, otherwise it must be the name of an existing
1741 prepared statement. On success, a
<structname>PGresult<
/> with
1742 status
<literal>PGRES_COMMAND_OK
</literal> is returned. The
1743 functions
<function>PQnparams
</function> and
1744 <function>PQparamtype
</function> can be applied to this
1745 <structname>PGresult<
/> to obtain information about the parameters
1746 of the prepared statement, and the functions
1747 <function>PQnfields
</function>,
<function>PQfname
</function>,
1748 <function>PQftype
</function>, etc provide information about the
1749 result columns (if any) of the statement.
1756 <function>PQdescribePortal
</function>
1758 <primary>PQdescribePortal
</primary>
1764 Submits a request to obtain information about the specified
1765 portal, and waits for completion.
1767 PGresult *PQdescribePortal(PGconn *conn, const char *portalName);
1772 <function>PQdescribePortal<
/> allows an application to obtain
1773 information about a previously created portal.
1774 (
<application>libpq<
/> does not provide any direct access to
1775 portals, but you can use this function to inspect the properties
1776 of a cursor created with a
<command>DECLARE CURSOR<
/> SQL command.)
1777 <function>PQdescribePortal<
/> is supported only in protocol
3.0
1778 and later connections; it will fail when using protocol
2.0.
1782 <parameter>portalName<
/> can be
<literal>""<
/> or NULL to reference
1783 the unnamed portal, otherwise it must be the name of an existing
1784 portal. On success, a
<structname>PGresult<
/> with status
1785 <literal>PGRES_COMMAND_OK
</literal> is returned. The functions
1786 <function>PQnfields
</function>,
<function>PQfname
</function>,
1787 <function>PQftype
</function>, etc can be applied to the
1788 <structname>PGresult<
/> to obtain information about the result
1789 columns (if any) of the portal.
1797 The
<structname>PGresult
</structname><indexterm><primary>PGresult<
/><
/>
1798 structure encapsulates the result returned by the server.
1799 <application>libpq
</application> application programmers should be
1800 careful to maintain the
<structname>PGresult
</structname> abstraction.
1801 Use the accessor functions below to get at the contents of
1802 <structname>PGresult
</structname>. Avoid directly referencing the
1803 fields of the
<structname>PGresult
</structname> structure because they
1804 are subject to change in the future.
1809 <function>PQresultStatus
</function>
1811 <primary>PQresultStatus
</primary>
1817 Returns the result status of the command.
1819 ExecStatusType PQresultStatus(const PGresult *res);
1824 <function>PQresultStatus
</function> can return one of the following values:
1828 <term><literal>PGRES_EMPTY_QUERY
</literal></term>
1831 The string sent to the server was empty.
1837 <term><literal>PGRES_COMMAND_OK
</literal></term>
1840 Successful completion of a command returning no data.
1846 <term><literal>PGRES_TUPLES_OK
</literal></term>
1849 Successful completion of a command returning data (such as
1850 a
<command>SELECT<
/> or
<command>SHOW<
/>).
1856 <term><literal>PGRES_COPY_OUT
</literal></term>
1859 Copy Out (from server) data transfer started.
1865 <term><literal>PGRES_COPY_IN
</literal></term>
1868 Copy In (to server) data transfer started.
1874 <term><literal>PGRES_BAD_RESPONSE
</literal></term>
1877 The server's response was not understood.
1883 <term><literal>PGRES_NONFATAL_ERROR
</literal></term>
1886 A nonfatal error (a notice or warning) occurred.
1892 <term><literal>PGRES_FATAL_ERROR
</literal></term>
1895 A fatal error occurred.
1901 If the result status is
<literal>PGRES_TUPLES_OK
</literal>, then
1902 the functions described below can be used to retrieve the rows
1903 returned by the query. Note that a
<command>SELECT
</command>
1904 command that happens to retrieve zero rows still shows
1905 <literal>PGRES_TUPLES_OK
</literal>.
1906 <literal>PGRES_COMMAND_OK
</literal> is for commands that can never
1907 return rows (
<command>INSERT
</command>,
<command>UPDATE
</command>,
1908 etc.). A response of
<literal>PGRES_EMPTY_QUERY
</literal> might
1909 indicate a bug in the client software.
1913 A result of status
<symbol>PGRES_NONFATAL_ERROR
</symbol> will
1914 never be returned directly by
<function>PQexec
</function> or other
1915 query execution functions; results of this kind are instead passed
1916 to the notice processor (see
<xref
1917 linkend=
"libpq-notice-processing">).
1924 <function>PQresStatus
</function>
1926 <primary>PQresStatus
</primary>
1932 Converts the enumerated type returned by
1933 <function>PQresultStatus<
/> into a string constant describing the
1934 status code. The caller should not free the result.
1937 char *PQresStatus(ExecStatusType status);
1945 <function>PQresultErrorMessage
</function>
1947 <primary>PQresultErrorMessage
</primary>
1953 Returns the error message associated with the command, or an empty string
1954 if there was no error.
1956 char *PQresultErrorMessage(const PGresult *res);
1958 If there was an error, the returned string will include a trailing
1959 newline. The caller should not free the result directly. It will
1960 be freed when the associated
<structname>PGresult<
/> handle is
1961 passed to
<function>PQclear
</function>.
1965 Immediately following a
<function>PQexec
</function> or
1966 <function>PQgetResult
</function> call,
1967 <function>PQerrorMessage
</function> (on the connection) will return
1968 the same string as
<function>PQresultErrorMessage
</function> (on
1969 the result). However, a
<structname>PGresult
</structname> will
1970 retain its error message until destroyed, whereas the connection's
1971 error message will change when subsequent operations are done.
1972 Use
<function>PQresultErrorMessage
</function> when you want to
1973 know the status associated with a particular
1974 <structname>PGresult
</structname>; use
1975 <function>PQerrorMessage
</function> when you want to know the
1976 status from the latest operation on the connection.
1982 <term><function>PQresultErrorField
</function><indexterm><primary>PQresultErrorField<
/><
/></term>
1985 Returns an individual field of an error report.
1987 char *PQresultErrorField(const PGresult *res, int fieldcode);
1989 <parameter>fieldcode<
/> is an error field identifier; see the symbols
1990 listed below.
<symbol>NULL
</symbol> is returned if the
1991 <structname>PGresult
</structname> is not an error or warning result,
1992 or does not include the specified field. Field values will normally
1993 not include a trailing newline. The caller should not free the
1994 result directly. It will be freed when the
1995 associated
<structname>PGresult<
/> handle is passed to
1996 <function>PQclear
</function>.
2000 The following field codes are available:
2003 <term><symbol>PG_DIAG_SEVERITY<
/></term>
2006 The severity; the field contents are
<literal>ERROR<
/>,
2007 <literal>FATAL<
/>, or
<literal>PANIC<
/> (in an error message),
2008 or
<literal>WARNING<
/>,
<literal>NOTICE<
/>,
<literal>DEBUG<
/>,
2009 <literal>INFO<
/>, or
<literal>LOG<
/> (in a notice message), or
2010 a localized translation of one of these. Always present.
2017 <primary>error codes
</primary>
2018 <secondary>libpq
</secondary>
2020 <term><symbol>PG_DIAG_SQLSTATE<
/></term>
2023 The SQLSTATE code for the error. The SQLSTATE code identifies
2024 the type of error that has occurred; it can be used by
2025 front-end applications to perform specific operations (such
2026 as error handling) in response to a particular database error.
2027 For a list of the possible SQLSTATE codes, see
<xref
2028 linkend=
"errcodes-appendix">. This field is not localizable,
2029 and is always present.
2035 <term><symbol>PG_DIAG_MESSAGE_PRIMARY<
/></term>
2038 The primary human-readable error message (typically one line).
2045 <term><symbol>PG_DIAG_MESSAGE_DETAIL<
/></term>
2048 Detail: an optional secondary error message carrying more
2049 detail about the problem. Might run to multiple lines.
2055 <term><symbol>PG_DIAG_MESSAGE_HINT<
/></term>
2058 Hint: an optional suggestion what to do about the problem.
2059 This is intended to differ from detail in that it offers advice
2060 (potentially inappropriate) rather than hard facts. Might
2061 run to multiple lines.
2067 <term><symbol>PG_DIAG_STATEMENT_POSITION<
/></term>
2070 A string containing a decimal integer indicating an error cursor
2071 position as an index into the original statement string. The
2072 first character has index
1, and positions are measured in
2073 characters not bytes.
2079 <term><symbol>PG_DIAG_INTERNAL_POSITION<
/></term>
2082 This is defined the same as the
2083 <symbol>PG_DIAG_STATEMENT_POSITION<
/> field, but it is used
2084 when the cursor position refers to an internally generated
2085 command rather than the one submitted by the client. The
2086 <symbol>PG_DIAG_INTERNAL_QUERY<
/> field will always appear when
2093 <term><symbol>PG_DIAG_INTERNAL_QUERY<
/></term>
2096 The text of a failed internally-generated command. This could
2097 be, for example, a SQL query issued by a PL/pgSQL function.
2103 <term><symbol>PG_DIAG_CONTEXT<
/></term>
2106 An indication of the context in which the error occurred.
2107 Presently this includes a call stack traceback of active
2108 procedural language functions and internally-generated queries.
2109 The trace is one entry per line, most recent first.
2115 <term><symbol>PG_DIAG_SOURCE_FILE<
/></term>
2118 The file name of the source-code location where the error was
2125 <term><symbol>PG_DIAG_SOURCE_LINE<
/></term>
2128 The line number of the source-code location where the error
2135 <term><symbol>PG_DIAG_SOURCE_FUNCTION<
/></term>
2138 The name of the source-code function reporting the error.
2146 The client is responsible for formatting displayed information to meet
2147 its needs; in particular it should break long lines as needed.
2148 Newline characters appearing in the error message fields should be
2149 treated as paragraph breaks, not line breaks.
2153 Errors generated internally by
<application>libpq
</application> will
2154 have severity and primary message, but typically no other fields.
2155 Errors returned by a pre-
3.0-protocol server will include severity and
2156 primary message, and sometimes a detail message, but no other fields.
2160 Note that error fields are only available from
2161 <structname>PGresult
</structname> objects, not
2162 <structname>PGconn
</structname> objects; there is no
2163 <function>PQerrorField
</function> function.
2169 <term><function>PQclear
</function><indexterm><primary>PQclear<
/><
/></term>
2172 Frees the storage associated with a
2173 <structname>PGresult
</structname>. Every command result should be
2174 freed via
<function>PQclear
</function> when it is no longer
2178 void PQclear(PGresult *res);
2183 You can keep a
<structname>PGresult
</structname> object around for
2184 as long as you need it; it does not go away when you issue a new
2185 command, nor even if you close the connection. To get rid of it,
2186 you must call
<function>PQclear
</function>. Failure to do this
2187 will result in memory leaks in your application.
2195 <sect2 id=
"libpq-exec-select-info">
2196 <title>Retrieving Query Result Information
</title>
2199 These functions are used to extract information from a
2200 <structname>PGresult
</structname> object that represents a successful
2201 query result (that is, one that has status
2202 <literal>PGRES_TUPLES_OK
</literal>). They can also be used to extract
2203 information from a successful Describe operation: a Describe's result
2204 has all the same column information that actual execution of the query
2205 would provide, but it has zero rows. For objects with other status values,
2206 these functions will act as though the result has zero rows and zero columns.
2212 <function>PQntuples
</function>
2214 <primary>PQntuples
</primary>
2220 Returns the number of rows (tuples) in the query result. Because
2221 it returns an integer result, large result sets might overflow the
2222 return value on
32-bit operating systems.
2225 int PQntuples(const PGresult *res);
2234 <function>PQnfields
</function>
2236 <primary>PQnfields
</primary>
2242 Returns the number of columns (fields) in each row of the query
2246 int PQnfields(const PGresult *res);
2254 <function>PQfname
</function>
2256 <primary>PQfname
</primary>
2262 Returns the column name associated with the given column number.
2263 Column numbers start at
0. The caller should not free the result
2264 directly. It will be freed when the associated
2265 <structname>PGresult<
/> handle is passed to
2266 <function>PQclear
</function>.
2268 char *PQfname(const PGresult *res,
2274 <symbol>NULL
</symbol> is returned if the column number is out of range.
2281 <function>PQfnumber
</function>
2283 <primary>PQfnumber
</primary>
2289 Returns the column number associated with the given column name.
2291 int PQfnumber(const PGresult *res,
2292 const char *column_name);
2297 -
1 is returned if the given name does not match any column.
2301 The given name is treated like an identifier in an SQL command,
2302 that is, it is downcased unless double-quoted. For example, given
2303 a query result generated from the SQL command:
2305 SELECT
1 AS FOO,
2 AS
"BAR";
2307 we would have the results:
2309 PQfname(res,
0)
<lineannotation>foo
</lineannotation>
2310 PQfname(res,
1)
<lineannotation>BAR
</lineannotation>
2311 PQfnumber(res,
"FOO")
<lineannotation>0</lineannotation>
2312 PQfnumber(res,
"foo")
<lineannotation>0</lineannotation>
2313 PQfnumber(res,
"BAR")
<lineannotation>-
1</lineannotation>
2314 PQfnumber(res,
"\"BAR\
"")
<lineannotation>1</lineannotation>
2322 <function>PQftable
</function>
2324 <primary>PQftable
</primary>
2330 Returns the OID of the table from which the given column was
2331 fetched. Column numbers start at
0.
2333 Oid PQftable(const PGresult *res,
2339 <literal>InvalidOid<
/> is returned if the column number is out of range,
2340 or if the specified column is not a simple reference to a table column,
2341 or when using pre-
3.0 protocol.
2342 You can query the system table
<literal>pg_class
</literal> to determine
2343 exactly which table is referenced.
2347 The type
<type>Oid
</type> and the constant
2348 <literal>InvalidOid
</literal> will be defined when you include
2349 the
<application>libpq
</application> header file. They will both
2350 be some integer type.
2357 <function>PQftablecol
</function>
2359 <primary>PQftablecol
</primary>
2365 Returns the column number (within its table) of the column making
2366 up the specified query result column. Query-result column numbers
2367 start at
0, but table columns have nonzero numbers.
2369 int PQftablecol(const PGresult *res,
2375 Zero is returned if the column number is out of range, or if the
2376 specified column is not a simple reference to a table column, or
2377 when using pre-
3.0 protocol.
2384 <function>PQfformat
</function>
2386 <primary>PQfformat
</primary>
2392 Returns the format code indicating the format of the given
2393 column. Column numbers start at
0.
2395 int PQfformat(const PGresult *res,
2401 Format code zero indicates textual data representation, while format
2402 code one indicates binary representation. (Other codes are reserved
2403 for future definition.)
2410 <function>PQftype
</function>
2412 <primary>PQftype
</primary>
2418 Returns the data type associated with the given column number.
2419 The integer returned is the internal OID number of the type.
2420 Column numbers start at
0.
2422 Oid PQftype(const PGresult *res,
2428 You can query the system table
<literal>pg_type
</literal> to
2429 obtain the names and properties of the various data types. The
2430 <acronym>OID
</acronym>s of the built-in data types are defined
2431 in the file
<filename>src/include/catalog/pg_type.h
</filename>
2439 <function>PQfmod
</function>
2441 <primary>PQfmod
</primary>
2447 Returns the type modifier of the column associated with the
2448 given column number. Column numbers start at
0.
2450 int PQfmod(const PGresult *res,
2456 The interpretation of modifier values is type-specific; they
2457 typically indicate precision or size limits. The value -
1 is
2458 used to indicate
<quote>no information available<
/>. Most data
2459 types do not use modifiers, in which case the value is always
2467 <function>PQfsize
</function>
2469 <primary>PQfsize
</primary>
2475 Returns the size in bytes of the column associated with the
2476 given column number. Column numbers start at
0.
2478 int PQfsize(const PGresult *res,
2484 <function>PQfsize<
/> returns the space allocated for this column
2485 in a database row, in other words the size of the server's
2486 internal representation of the data type. (Accordingly, it is
2487 not really very useful to clients.) A negative value indicates
2488 the data type is variable-length.
2495 <function>PQbinaryTuples
</function>
2497 <primary>PQbinaryTuples
</primary>
2503 Returns
1 if the
<structname>PGresult<
/> contains binary data
2504 and
0 if it contains text data.
2506 int PQbinaryTuples(const PGresult *res);
2511 This function is deprecated (except for its use in connection with
2512 <command>COPY<
/>), because it is possible for a single
2513 <structname>PGresult<
/> to contain text data in some columns and
2514 binary data in others.
<function>PQfformat<
/> is preferred.
2515 <function>PQbinaryTuples<
/> returns
1 only if all columns of the
2516 result are binary (format
1).
2523 <function>PQgetvalue
</function>
2525 <primary>PQgetvalue
</primary>
2531 Returns a single field value of one row of a
2532 <structname>PGresult
</structname>. Row and column numbers start
2533 at
0. The caller should not free the result directly. It will
2534 be freed when the associated
<structname>PGresult<
/> handle is
2535 passed to
<function>PQclear
</function>.
2537 char *PQgetvalue(const PGresult *res,
2544 For data in text format, the value returned by
2545 <function>PQgetvalue
</function> is a null-terminated character
2546 string representation of the field value. For data in binary
2547 format, the value is in the binary representation determined by
2548 the data type's
<function>typsend<
/> and
<function>typreceive<
/>
2549 functions. (The value is actually followed by a zero byte in
2550 this case too, but that is not ordinarily useful, since the
2551 value is likely to contain embedded nulls.)
2555 An empty string is returned if the field value is null. See
2556 <function>PQgetisnull<
/> to distinguish null values from
2557 empty-string values.
2561 The pointer returned by
<function>PQgetvalue
</function> points
2562 to storage that is part of the
<structname>PGresult
</structname>
2563 structure. One should not modify the data it points to, and one
2564 must explicitly copy the data into other storage if it is to be
2565 used past the lifetime of the
<structname>PGresult
</structname>
2573 <function>PQgetisnull
</function>
2575 <primary>PQgetisnull
</primary>
2578 <primary>null value
</primary>
2579 <secondary sortas=
"libpq">in libpq
</secondary>
2585 Tests a field for a null value. Row and column numbers start
2588 int PQgetisnull(const PGresult *res,
2595 This function returns
1 if the field is null and
0 if it
2596 contains a non-null value. (Note that
2597 <function>PQgetvalue
</function> will return an empty string,
2598 not a null pointer, for a null field.)
2605 <function>PQgetlength
</function>
2607 <primary>PQgetlength
</primary>
2612 Returns the actual length of a field value in bytes. Row and
2613 column numbers start at
0.
2615 int PQgetlength(const PGresult *res,
2622 This is the actual data length for the particular data value,
2623 that is, the size of the object pointed to by
2624 <function>PQgetvalue
</function>. For text data format this is
2625 the same as
<function>strlen()<
/>. For binary format this is
2626 essential information. Note that one should
<emphasis>not<
/>
2627 rely on
<function>PQfsize
</function> to obtain the actual data
2635 <function>PQnparams
</function>
2637 <primary>PQnparams
</primary>
2643 Returns the number of parameters of a prepared statement.
2645 int PQnparams(const PGresult *res);
2650 This function is only useful when inspecting the result of
2651 <function>PQdescribePrepared<
/>. For other types of queries it
2659 <function>PQparamtype
</function>
2661 <primary>PQparamtype
</primary>
2667 Returns the data type of the indicated statement parameter.
2668 Parameter numbers start at
0.
2670 Oid PQparamtype(const PGresult *res, int param_number);
2675 This function is only useful when inspecting the result of
2676 <function>PQdescribePrepared<
/>. For other types of queries it
2684 <function>PQprint
</function>
2686 <primary>PQprint
</primary>
2692 Prints out all the rows and, optionally, the column names to
2693 the specified output stream.
2695 void PQprint(FILE *fout, /* output stream */
2696 const PGresult *res,
2697 const PQprintOpt *po);
2699 pqbool header; /* print output field headings and row count */
2700 pqbool align; /* fill align the fields */
2701 pqbool standard; /* old brain dead format */
2702 pqbool html3; /* output HTML tables */
2703 pqbool expanded; /* expand tables */
2704 pqbool pager; /* use pager for output if needed */
2705 char *fieldSep; /* field separator */
2706 char *tableOpt; /* attributes for HTML table element */
2707 char *caption; /* HTML table caption */
2708 char **fieldName; /* null-terminated array of replacement field names */
2714 This function was formerly used by
<application>psql
</application>
2715 to print query results, but this is no longer the case. Note
2716 that it assumes all the data is in text format.
2723 <sect2 id=
"libpq-exec-nonselect">
2724 <title>Retrieving Result Information for Other Commands
</title>
2727 These functions are used to extract information from
2728 <structname>PGresult
</structname> objects that are not
2729 <command>SELECT<
/> results.
2735 <function>PQcmdStatus
</function>
2737 <primary>PQcmdStatus
</primary>
2743 Returns the command status tag from the SQL command that generated
2744 the
<structname>PGresult
</structname>.
2746 char *PQcmdStatus(PGresult *res);
2751 Commonly this is just the name of the command, but it might include
2752 additional data such as the number of rows processed. The caller
2753 should not free the result directly. It will be freed when the
2754 associated
<structname>PGresult<
/> handle is passed to
2755 <function>PQclear
</function>.
2762 <function>PQcmdTuples
</function>
2764 <primary>PQcmdTuples
</primary>
2770 Returns the number of rows affected by the SQL command.
2772 char *PQcmdTuples(PGresult *res);
2777 This function returns a string containing the number of rows
2778 affected by the
<acronym>SQL<
/> statement that generated the
2779 <structname>PGresult<
/>. This function can only be used following
2780 the execution of an
<command>INSERT<
/>,
<command>UPDATE<
/>,
2781 <command>DELETE<
/>,
<command>MOVE<
/>,
<command>FETCH<
/>, or
2782 <command>COPY<
/> statement, or an
<command>EXECUTE<
/> of a
2783 prepared query that contains an
<command>INSERT<
/>,
2784 <command>UPDATE<
/>, or
<command>DELETE<
/> statement. If the
2785 command that generated the
<structname>PGresult<
/> was anything
2786 else,
<function>PQcmdTuples<
/> returns an empty string. The caller
2787 should not free the return value directly. It will be freed when
2788 the associated
<structname>PGresult<
/> handle is passed to
2789 <function>PQclear
</function>.
2796 <function>PQoidValue
</function>
2798 <primary>PQoidValue
</primary>
2804 Returns the OID
<indexterm><primary>OID<
/><secondary>in libpq<
/><
/>
2805 of the inserted row, if the
<acronym>SQL<
/> command was an
2806 <command>INSERT<
/> that inserted exactly one row into a table that
2807 has OIDs, or a
<command>EXECUTE<
/> of a prepared query containing
2808 a suitable
<command>INSERT<
/> statement. Otherwise, this function
2809 returns
<literal>InvalidOid
</literal>. This function will also
2810 return
<literal>InvalidOid
</literal> if the table affected by the
2811 <command>INSERT<
/> statement does not contain OIDs.
2813 Oid PQoidValue(const PGresult *res);
2821 <function>PQoidStatus
</function>
2823 <primary>PQoidStatus
</primary>
2829 Returns a string with the OID of the inserted row, if the
2830 <acronym>SQL
</acronym> command was an
<command>INSERT
</command>
2831 that inserted exactly one row, or a
<command>EXECUTE
</command> of
2832 a prepared statement consisting of a suitable
2833 <command>INSERT
</command>. (The string will be
<literal>0<
/> if
2834 the
<command>INSERT
</command> did not insert exactly one row, or
2835 if the target table does not have OIDs.) If the command was not
2836 an
<command>INSERT
</command>, returns an empty string.
2838 char *PQoidStatus(const PGresult *res);
2843 This function is deprecated in favor of
2844 <function>PQoidValue
</function>. It is not thread-safe.
2852 <sect2 id=
"libpq-exec-escape-string">
2853 <title>Escaping Strings for Inclusion in SQL Commands
</title>
2855 <indexterm zone=
"libpq-exec-escape-string">
2856 <primary>PQescapeStringConn
</primary>
2858 <indexterm zone=
"libpq-exec-escape-string">
2859 <primary>PQescapeString
</primary>
2861 <indexterm zone=
"libpq-exec-escape-string">
2862 <primary>escaping strings
</primary>
2863 <secondary>in libpq
</secondary>
2867 <function>PQescapeStringConn
</function> escapes a string for use within an SQL
2868 command. This is useful when inserting data values as literal constants
2869 in SQL commands. Certain characters (such as quotes and backslashes) must
2870 be escaped to prevent them from being interpreted specially by the SQL parser.
2871 <function>PQescapeStringConn<
/> performs this operation.
2876 It is especially important to do proper escaping when handling strings that
2877 were received from an untrustworthy source. Otherwise there is a security
2878 risk: you are vulnerable to
<quote>SQL injection<
/> attacks wherein unwanted
2879 SQL commands are fed to your database.
2884 Note that it is not necessary nor correct to do escaping when a data
2885 value is passed as a separate parameter in
<function>PQexecParams<
/> or
2886 its sibling routines.
2889 size_t PQescapeStringConn (PGconn *conn,
2890 char *to, const char *from, size_t length,
2896 <function>PQescapeStringConn<
/> writes an escaped version of the
2897 <parameter>from<
/> string to the
<parameter>to<
/> buffer, escaping
2898 special characters so that they cannot cause any harm, and adding a
2899 terminating zero byte. The single quotes that must surround
2900 <productname>PostgreSQL<
/> string literals are not included in the
2901 result string; they should be provided in the SQL command that the
2902 result is inserted into. The parameter
<parameter>from<
/> points to
2903 the first character of the string that is to be escaped, and the
2904 <parameter>length<
/> parameter gives the number of bytes in this
2905 string. A terminating zero byte is not required, and should not be
2906 counted in
<parameter>length<
/>. (If a terminating zero byte is found
2907 before
<parameter>length<
/> bytes are processed,
2908 <function>PQescapeStringConn<
/> stops at the zero; the behavior is
2909 thus rather like
<function>strncpy<
/>.)
<parameter>to<
/> shall point
2910 to a buffer that is able to hold at least one more byte than twice
2911 the value of
<parameter>length<
/>, otherwise the behavior is undefined.
2912 Behavior is likewise undefined if the
<parameter>to<
/> and
2913 <parameter>from<
/> strings overlap.
2917 If the
<parameter>error<
/> parameter is not NULL, then
2918 <literal>*error<
/> is set to zero on success, nonzero on error.
2919 Presently the only possible error conditions involve invalid multibyte
2920 encoding in the source string. The output string is still generated
2921 on error, but it can be expected that the server will reject it as
2922 malformed. On error, a suitable message is stored in the
2923 <parameter>conn<
/> object, whether or not
<parameter>error<
/> is NULL.
2927 <function>PQescapeStringConn<
/> returns the number of bytes written
2928 to
<parameter>to<
/>, not including the terminating zero byte.
2933 size_t PQescapeString (char *to, const char *from, size_t length);
2938 <function>PQescapeString<
/> is an older, deprecated version of
2939 <function>PQescapeStringConn<
/>; the difference is that it does
2940 not take
<parameter>conn<
/> or
<parameter>error<
/> parameters.
2941 Because of this, it cannot adjust its behavior depending on the
2942 connection properties (such as character encoding) and therefore
2943 <emphasis>it might give the wrong results<
/>. Also, it has no way
2944 to report error conditions.
2948 <function>PQescapeString<
/> can be used safely in single-threaded
2949 client programs that work with only one
<productname>PostgreSQL<
/>
2950 connection at a time (in this case it can find out what it needs to
2951 know
<quote>behind the scenes<
/>). In other contexts it is a security
2952 hazard and should be avoided in favor of
2953 <function>PQescapeStringConn<
/>.
2958 <sect2 id=
"libpq-exec-escape-bytea">
2959 <title>Escaping Binary Strings for Inclusion in SQL Commands
</title>
2961 <indexterm zone=
"libpq-exec-escape-bytea">
2962 <primary>bytea
</primary>
2963 <secondary sortas=
"libpq">in libpq
</secondary>
2969 <function>PQescapeByteaConn
</function>
2971 <primary>PQescapeByteaConn
</primary>
2977 Escapes binary data for use within an SQL command with the type
2978 <type>bytea
</type>. As with
<function>PQescapeStringConn
</function>,
2979 this is only used when inserting data directly into an SQL command string.
2981 unsigned char *PQescapeByteaConn(PGconn *conn,
2982 const unsigned char *from,
2989 Certain byte values
<emphasis>must
</emphasis> be escaped (but all
2990 byte values
<emphasis>can
</emphasis> be escaped) when used as part
2991 of a
<type>bytea
</type> literal in an
<acronym>SQL
</acronym>
2992 statement. In general, to escape a byte, it is converted into the
2993 three digit octal number equal to the octet value, and preceded by
2994 usually two backslashes. The single quote (
<literal>'<
/>) and backslash
2995 (
<literal>\<
/>) characters have special alternative escape
2996 sequences. See
<xref linkend=
"datatype-binary"> for more
2997 information.
<function>PQescapeByteaConn
</function> performs this
2998 operation, escaping only the minimally required bytes.
3002 The
<parameter>from
</parameter> parameter points to the first
3003 byte of the string that is to be escaped, and the
3004 <parameter>from_length
</parameter> parameter gives the number of
3005 bytes in this binary string. (A terminating zero byte is
3006 neither necessary nor counted.) The
<parameter>to_length
</parameter>
3007 parameter points to a variable that will hold the resultant
3008 escaped string length. This result string length includes the terminating
3009 zero byte of the result.
3013 <function>PQescapeByteaConn<
/> returns an escaped version of the
3014 <parameter>from
</parameter> parameter binary string in memory
3015 allocated with
<function>malloc()<
/>. This memory must be freed using
3016 <function>PQfreemem()<
/> when the result is no longer needed. The
3017 return string has all special characters replaced so that they can
3018 be properly processed by the
<productname>PostgreSQL
</productname>
3019 string literal parser, and the
<type>bytea
</type> input function. A
3020 terminating zero byte is also added. The single quotes that must
3021 surround
<productname>PostgreSQL
</productname> string literals are
3022 not part of the result string.
3026 On error, a NULL pointer is returned, and a suitable error message
3027 is stored in the
<parameter>conn<
/> object. Currently, the only
3028 possible error is insufficient memory for the result string.
3035 <function>PQescapeBytea
</function>
3037 <primary>PQescapeBytea
</primary>
3043 <function>PQescapeBytea<
/> is an older, deprecated version of
3044 <function>PQescapeByteaConn<
/>.
3046 unsigned char *PQescapeBytea(const unsigned char *from,
3053 The only difference from
<function>PQescapeByteaConn<
/> is that
3054 <function>PQescapeBytea<
/> does not take a
<structname>PGconn<
/>
3055 parameter. Because of this, it cannot adjust its behavior
3056 depending on the connection properties (in particular, whether
3057 standard-conforming strings are enabled) and therefore
3058 <emphasis>it might give the wrong results<
/>. Also, it has no
3059 way to return an error message on failure.
3063 <function>PQescapeBytea<
/> can be used safely in single-threaded
3064 client programs that work with only one
<productname>PostgreSQL<
/>
3065 connection at a time (in this case it can find out what it needs
3066 to know
<quote>behind the scenes<
/>). In other contexts it is
3067 a security hazard and should be avoided in favor of
3068 <function>PQescapeByteaConn<
/>.
3075 <function>PQunescapeBytea
</function>
3077 <primary>PQunescapeBytea
</primary>
3083 Converts a string representation of binary data into binary data
3084 — the reverse of
<function>PQescapeBytea
</function>. This
3085 is needed when retrieving
<type>bytea
</type> data in text format,
3086 but not when retrieving it in binary format.
3089 unsigned char *PQunescapeBytea(const unsigned char *from, size_t *to_length);
3094 The
<parameter>from
</parameter> parameter points to a string
3095 such as might be returned by
<function>PQgetvalue
</function> when applied
3096 to a
<type>bytea
</type> column.
<function>PQunescapeBytea
</function>
3097 converts this string representation into its binary representation.
3098 It returns a pointer to a buffer allocated with
3099 <function>malloc()
</function>, or null on error, and puts the size of
3100 the buffer in
<parameter>to_length
</parameter>. The result must be
3101 freed using
<function>PQfreemem<
/> when it is no longer needed.
3105 This conversion is not exactly the inverse of
3106 <function>PQescapeBytea
</function>, because the string is not expected
3107 to be
<quote>escaped<
/> when received from
<function>PQgetvalue
</function>.
3108 In particular this means there is no need for string quoting considerations,
3109 and so no need for a
<structname>PGconn<
/> parameter.
3119 <sect1 id=
"libpq-async">
3120 <title>Asynchronous Command Processing
</title>
3122 <indexterm zone=
"libpq-async">
3123 <primary>nonblocking connection
</primary>
3127 The
<function>PQexec
</function> function is adequate for submitting
3128 commands in normal, synchronous applications. It has a couple of
3129 deficiencies, however, that can be of importance to some users:
3134 <function>PQexec
</function> waits for the command to be completed.
3135 The application might have other work to do (such as maintaining a
3136 user interface), in which case it won't want to block waiting for
3143 Since the execution of the client application is suspended while it
3144 waits for the result, it is hard for the application to decide that
3145 it would like to try to cancel the ongoing command. (It can be done
3146 from a signal handler, but not otherwise.)
3152 <function>PQexec
</function> can return only one
3153 <structname>PGresult
</structname> structure. If the submitted command
3154 string contains multiple
<acronym>SQL
</acronym> commands, all but
3155 the last
<structname>PGresult
</structname> are discarded by
3156 <function>PQexec
</function>.
3163 Applications that do not like these limitations can instead use the
3164 underlying functions that
<function>PQexec
</function> is built from:
3165 <function>PQsendQuery
</function> and
<function>PQgetResult
</function>.
3167 <function>PQsendQueryParams
</function>,
3168 <function>PQsendPrepare
</function>,
3169 <function>PQsendQueryPrepared
</function>,
3170 <function>PQsendDescribePrepared
</function>, and
3171 <function>PQsendDescribePortal
</function>,
3172 which can be used with
<function>PQgetResult
</function> to duplicate
3173 the functionality of
3174 <function>PQexecParams
</function>,
3175 <function>PQprepare
</function>,
3176 <function>PQexecPrepared
</function>,
3177 <function>PQdescribePrepared
</function>, and
3178 <function>PQdescribePortal
</function>
3184 <function>PQsendQuery
</function>
3186 <primary>PQsendQuery
</primary>
3192 Submits a command to the server without waiting for the result(s).
3193 1 is returned if the command was successfully dispatched and
0 if
3194 not (in which case, use
<function>PQerrorMessage<
/> to get more
3195 information about the failure).
3197 int PQsendQuery(PGconn *conn, const char *command);
3200 After successfully calling
<function>PQsendQuery
</function>, call
3201 <function>PQgetResult
</function> one or more times to obtain the
3202 results.
<function>PQsendQuery
</function> cannot be called again
3203 (on the same connection) until
<function>PQgetResult
</function>
3204 has returned a null pointer, indicating that the command is done.
3211 <function>PQsendQueryParams
</function>
3213 <primary>PQsendQueryParams
</primary>
3219 Submits a command and separate parameters to the server without
3220 waiting for the result(s).
3222 int PQsendQueryParams(PGconn *conn,
3223 const char *command,
3225 const Oid *paramTypes,
3226 const char * const *paramValues,
3227 const int *paramLengths,
3228 const int *paramFormats,
3232 This is equivalent to
<function>PQsendQuery
</function> except that
3233 query parameters can be specified separately from the query string.
3234 The function's parameters are handled identically to
3235 <function>PQexecParams
</function>. Like
3236 <function>PQexecParams
</function>, it will not work on
2.0-protocol
3237 connections, and it allows only one command in the query string.
3244 <function>PQsendPrepare<
/>
3246 <primary>PQsendPrepare
</primary>
3252 Sends a request to create a prepared statement with the given
3253 parameters, without waiting for completion.
3255 int PQsendPrepare(PGconn *conn,
3256 const char *stmtName,
3259 const Oid *paramTypes);
3262 This is an asynchronous version of
<function>PQprepare<
/>: it
3263 returns
1 if it was able to dispatch the request, and
0 if not.
3264 After a successful call, call
<function>PQgetResult
</function> to
3265 determine whether the server successfully created the prepared
3266 statement. The function's parameters are handled identically to
3267 <function>PQprepare
</function>. Like
3268 <function>PQprepare
</function>, it will not work on
2.0-protocol
3276 <function>PQsendQueryPrepared
</function>
3278 <primary>PQsendQueryPrepared
</primary>
3284 Sends a request to execute a prepared statement with given
3285 parameters, without waiting for the result(s).
3287 int PQsendQueryPrepared(PGconn *conn,
3288 const char *stmtName,
3290 const char * const *paramValues,
3291 const int *paramLengths,
3292 const int *paramFormats,
3296 This is similar to
<function>PQsendQueryParams
</function>, but
3297 the command to be executed is specified by naming a
3298 previously-prepared statement, instead of giving a query string.
3299 The function's parameters are handled identically to
3300 <function>PQexecPrepared
</function>. Like
3301 <function>PQexecPrepared
</function>, it will not work on
3302 2.0-protocol connections.
3309 <function>PQsendDescribePrepared<
/>
3311 <primary>PQsendDescribePrepared
</primary>
3317 Submits a request to obtain information about the specified
3318 prepared statement, without waiting for completion.
3320 int PQsendDescribePrepared(PGconn *conn, const char *stmtName);
3323 This is an asynchronous version of
<function>PQdescribePrepared<
/>:
3324 it returns
1 if it was able to dispatch the request, and
0 if not.
3325 After a successful call, call
<function>PQgetResult
</function> to
3326 obtain the results. The function's parameters are handled
3327 identically to
<function>PQdescribePrepared
</function>. Like
3328 <function>PQdescribePrepared
</function>, it will not work on
3329 2.0-protocol connections.
3336 <function>PQsendDescribePortal<
/>
3338 <primary>PQsendDescribePortal
</primary>
3344 Submits a request to obtain information about the specified
3345 portal, without waiting for completion.
3347 int PQsendDescribePortal(PGconn *conn, const char *portalName);
3350 This is an asynchronous version of
<function>PQdescribePortal<
/>:
3351 it returns
1 if it was able to dispatch the request, and
0 if not.
3352 After a successful call, call
<function>PQgetResult
</function> to
3353 obtain the results. The function's parameters are handled
3354 identically to
<function>PQdescribePortal
</function>. Like
3355 <function>PQdescribePortal
</function>, it will not work on
3356 2.0-protocol connections.
3363 <function>PQgetResult
</function>
3365 <primary>PQgetResult
</primary>
3371 Waits for the next result from a prior
3372 <function>PQsendQuery
</function>,
3373 <function>PQsendQueryParams
</function>,
3374 <function>PQsendPrepare
</function>, or
3375 <function>PQsendQueryPrepared
</function> call, and returns it.
3376 A null pointer is returned when the command is complete and there
3377 will be no more results.
3379 PGresult *PQgetResult(PGconn *conn);
3384 <function>PQgetResult
</function> must be called repeatedly until
3385 it returns a null pointer, indicating that the command is done.
3386 (If called when no command is active,
3387 <function>PQgetResult
</function> will just return a null pointer
3388 at once.) Each non-null result from
3389 <function>PQgetResult
</function> should be processed using the
3390 same
<structname>PGresult<
/> accessor functions previously
3391 described. Don't forget to free each result object with
3392 <function>PQclear
</function> when done with it. Note that
3393 <function>PQgetResult
</function> will block only if a command is
3394 active and the necessary response data has not yet been read by
3395 <function>PQconsumeInput
</function>.
3403 Using
<function>PQsendQuery
</function> and
3404 <function>PQgetResult
</function> solves one of
3405 <function>PQexec
</function>'s problems: If a command string contains
3406 multiple
<acronym>SQL
</acronym> commands, the results of those commands
3407 can be obtained individually. (This allows a simple form of overlapped
3408 processing, by the way: the client can be handling the results of one
3409 command while the server is still working on later queries in the same
3410 command string.) However, calling
<function>PQgetResult
</function>
3411 will still cause the client to block until the server completes the
3412 next
<acronym>SQL
</acronym> command. This can be avoided by proper
3413 use of two more functions:
3418 <function>PQconsumeInput
</function>
3420 <primary>PQconsumeInput
</primary>
3426 If input is available from the server, consume it.
3428 int PQconsumeInput(PGconn *conn);
3433 <function>PQconsumeInput
</function> normally returns
1 indicating
3434 <quote>no error
</quote>, but returns
0 if there was some kind of
3435 trouble (in which case
<function>PQerrorMessage
</function> can be
3436 consulted). Note that the result does not say whether any input
3437 data was actually collected. After calling
3438 <function>PQconsumeInput
</function>, the application can check
3439 <function>PQisBusy
</function> and/or
3440 <function>PQnotifies
</function> to see if their state has changed.
3444 <function>PQconsumeInput
</function> can be called even if the
3445 application is not prepared to deal with a result or notification
3446 just yet. The function will read available data and save it in
3447 a buffer, thereby causing a
<function>select()
</function>
3448 read-ready indication to go away. The application can thus use
3449 <function>PQconsumeInput
</function> to clear the
3450 <function>select()
</function> condition immediately, and then
3451 examine the results at leisure.
3458 <function>PQisBusy
</function>
3460 <primary>PQisBusy
</primary>
3466 Returns
1 if a command is busy, that is,
3467 <function>PQgetResult
</function> would block waiting for input.
3468 A
0 return indicates that
<function>PQgetResult
</function> can be
3469 called with assurance of not blocking.
3471 int PQisBusy(PGconn *conn);
3476 <function>PQisBusy
</function> will not itself attempt to read data
3477 from the server; therefore
<function>PQconsumeInput
</function>
3478 must be invoked first, or the busy state will never end.
3486 A typical application using these functions will have a main loop that
3487 uses
<function>select()
</function> or
<function>poll()<
/> to wait for
3488 all the conditions that it must respond to. One of the conditions
3489 will be input available from the server, which in terms of
3490 <function>select()
</function> means readable data on the file
3491 descriptor identified by
<function>PQsocket
</function>. When the main
3492 loop detects input ready, it should call
3493 <function>PQconsumeInput
</function> to read the input. It can then
3494 call
<function>PQisBusy
</function>, followed by
3495 <function>PQgetResult
</function> if
<function>PQisBusy
</function>
3496 returns false (
0). It can also call
<function>PQnotifies
</function>
3497 to detect
<command>NOTIFY<
/> messages (see
<xref
3498 linkend=
"libpq-notify">).
3503 <function>PQsendQuery
</function>/
<function>PQgetResult
</function>
3504 can also attempt to cancel a command that is still being processed
3505 by the server; see
<xref linkend=
"libpq-cancel">. But regardless of
3506 the return value of
<function>PQcancel
</function>, the application
3507 must continue with the normal result-reading sequence using
3508 <function>PQgetResult
</function>. A successful cancellation will
3509 simply cause the command to terminate sooner than it would have
3514 By using the functions described above, it is possible to avoid
3515 blocking while waiting for input from the database server. However,
3516 it is still possible that the application will block waiting to send
3517 output to the server. This is relatively uncommon but can happen if
3518 very long SQL commands or data values are sent. (It is much more
3519 probable if the application sends data via
<command>COPY IN
</command>,
3520 however.) To prevent this possibility and achieve completely
3521 nonblocking database operation, the following additional functions
3527 <function>PQsetnonblocking
</function>
3529 <primary>PQsetnonblocking
</primary>
3535 Sets the nonblocking status of the connection.
3537 int PQsetnonblocking(PGconn *conn, int arg);
3542 Sets the state of the connection to nonblocking if
3543 <parameter>arg
</parameter> is
1, or blocking if
3544 <parameter>arg
</parameter> is
0. Returns
0 if OK, -
1 if error.
3548 In the nonblocking state, calls to
3549 <function>PQsendQuery
</function>,
<function>PQputline
</function>,
3550 <function>PQputnbytes
</function>, and
3551 <function>PQendcopy
</function> will not block but instead return
3552 an error if they need to be called again.
3556 Note that
<function>PQexec
</function> does not honor nonblocking
3557 mode; if it is called, it will act in blocking fashion anyway.
3564 <function>PQisnonblocking
</function>
3566 <primary>PQisnonblocking
</primary>
3572 Returns the blocking status of the database connection.
3574 int PQisnonblocking(const PGconn *conn);
3579 Returns
1 if the connection is set to nonblocking mode and
0 if
3587 <function>PQflush
</function>
3589 <primary>PQflush
</primary>
3595 Attempts to flush any queued output data to the server. Returns
3596 0 if successful (or if the send queue is empty), -
1 if it failed
3597 for some reason, or
1 if it was unable to send all the data in
3598 the send queue yet (this case can only occur if the connection
3601 int PQflush(PGconn *conn);
3610 After sending any command or data on a nonblocking connection, call
3611 <function>PQflush
</function>. If it returns
1, wait for the socket
3612 to be write-ready and call it again; repeat until it returns
0. Once
3613 <function>PQflush
</function> returns
0, wait for the socket to be
3614 read-ready and then read the response as described above.
3619 <sect1 id=
"libpq-cancel">
3620 <title>Cancelling Queries in Progress
</title>
3622 <indexterm zone=
"libpq-cancel">
3623 <primary>canceling
</primary>
3624 <secondary>SQL command
</secondary>
3628 A client application can request cancellation of a command that is
3629 still being processed by the server, using the functions described in
3635 <function>PQgetCancel
</function>
3637 <primary>PQgetCancel
</primary>
3643 Creates a data structure containing the information needed to cancel
3644 a command issued through a particular database connection.
3646 PGcancel *PQgetCancel(PGconn *conn);
3651 <function>PQgetCancel
</function> creates a
3652 <structname>PGcancel<
/><indexterm><primary>PGcancel<
/><
/> object
3653 given a
<structname>PGconn<
/> connection object. It will return
3654 NULL if the given
<parameter>conn<
/> is NULL or an invalid
3655 connection. The
<structname>PGcancel<
/> object is an opaque
3656 structure that is not meant to be accessed directly by the
3657 application; it can only be passed to
<function>PQcancel
</function>
3658 or
<function>PQfreeCancel
</function>.
3665 <function>PQfreeCancel
</function>
3667 <primary>PQfreeCancel
</primary>
3673 Frees a data structure created by
<function>PQgetCancel
</function>.
3675 void PQfreeCancel(PGcancel *cancel);
3680 <function>PQfreeCancel
</function> frees a data object previously created
3681 by
<function>PQgetCancel
</function>.
3688 <function>PQcancel
</function>
3690 <primary>PQcancel
</primary>
3696 Requests that the server abandon processing of the current command.
3698 int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize);
3703 The return value is
1 if the cancel request was successfully
3704 dispatched and
0 if not. If not,
<parameter>errbuf<
/> is filled
3705 with an error message explaining why not.
<parameter>errbuf<
/>
3706 must be a char array of size
<parameter>errbufsize<
/> (the
3707 recommended size is
256 bytes).
3711 Successful dispatch is no guarantee that the request will have
3712 any effect, however. If the cancellation is effective, the current
3713 command will terminate early and return an error result. If the
3714 cancellation fails (say, because the server was already done
3715 processing the command), then there will be no visible result at
3720 <function>PQcancel
</function> can safely be invoked from a signal
3721 handler, if the
<parameter>errbuf<
/> is a local variable in the
3722 signal handler. The
<structname>PGcancel<
/> object is read-only
3723 as far as
<function>PQcancel
</function> is concerned, so it can
3724 also be invoked from a thread that is separate from the one
3725 manipulating the
<structname>PGconn<
/> object.
3734 <function>PQrequestCancel
</function>
3736 <primary>PQrequestCancel
</primary>
3742 Requests that the server abandon processing of the current
3745 int PQrequestCancel(PGconn *conn);
3750 <function>PQrequestCancel
</function> is a deprecated variant of
3751 <function>PQcancel
</function>. It operates directly on the
3752 <structname>PGconn<
/> object, and in case of failure stores the
3753 error message in the
<structname>PGconn<
/> object (whence it can
3754 be retrieved by
<function>PQerrorMessage
</function>). Although
3755 the functionality is the same, this approach creates hazards for
3756 multiple-thread programs and signal handlers, since it is possible
3757 that overwriting the
<structname>PGconn<
/>'s error message will
3758 mess up the operation currently in progress on the connection.
3767 <sect1 id=
"libpq-fastpath">
3768 <title>The Fast-Path Interface
</title>
3770 <indexterm zone=
"libpq-fastpath">
3771 <primary>fast path
</primary>
3775 <productname>PostgreSQL
</productname> provides a fast-path interface
3776 to send simple function calls to the server.
3781 This interface is somewhat obsolete, as one can achieve similar
3782 performance and greater functionality by setting up a prepared
3783 statement to define the function call. Then, executing the statement
3784 with binary transmission of parameters and results substitutes for a
3785 fast-path function call.
3790 The function
<function>PQfn
</function><indexterm><primary>PQfn<
/><
/>
3791 requests execution of a server function via the fast-path interface:
3793 PGresult *PQfn(PGconn *conn,
3798 const PQArgBlock *args,
3813 The
<parameter>fnid<
/> argument is the OID of the function to be
3814 executed.
<parameter>args<
/> and
<parameter>nargs<
/> define the
3815 parameters to be passed to the function; they must match the declared
3816 function argument list. When the
<parameter>isint<
/> field of a
3817 parameter structure is true, the
<parameter>u.integer<
/> value is sent
3818 to the server as an integer of the indicated length (this must be
1,
3819 2, or
4 bytes); proper byte-swapping occurs. When
<parameter>isint<
/>
3820 is false, the indicated number of bytes at
<parameter>*u.ptr<
/> are
3821 sent with no processing; the data must be in the format expected by
3822 the server for binary transmission of the function's argument data
3823 type.
<parameter>result_buf
</parameter> is the buffer in which to
3824 place the return value. The caller must have allocated sufficient
3825 space to store the return value. (There is no check!) The actual result
3826 length will be returned in the integer pointed to by
3827 <parameter>result_len
</parameter>. If a
1,
2, or
4-byte integer result
3828 is expected, set
<parameter>result_is_int
</parameter> to
1, otherwise
3829 set it to
0. Setting
<parameter>result_is_int
</parameter> to
1 causes
3830 <application>libpq<
/> to byte-swap the value if necessary, so that it
3831 is delivered as a proper
<type>int
</type> value for the client machine.
3832 When
<parameter>result_is_int<
/> is
0, the binary-format byte string
3833 sent by the server is returned unmodified.
3837 <function>PQfn
</function> always returns a valid
3838 <structname>PGresult
</structname> pointer. The result status should be
3839 checked before the result is used. The caller is responsible for
3840 freeing the
<structname>PGresult
</structname> with
3841 <function>PQclear
</function> when it is no longer needed.
3845 Note that it is not possible to handle null arguments, null results,
3846 nor set-valued results when using this interface.
3851 <sect1 id=
"libpq-notify">
3852 <title>Asynchronous Notification
</title>
3854 <indexterm zone=
"libpq-notify">
3855 <primary>NOTIFY
</primary>
3856 <secondary>in libpq
</secondary>
3860 <productname>PostgreSQL
</productname> offers asynchronous notification
3861 via the
<command>LISTEN
</command> and
<command>NOTIFY
</command>
3862 commands. A client session registers its interest in a particular
3863 notification condition with the
<command>LISTEN
</command> command (and
3864 can stop listening with the
<command>UNLISTEN
</command> command). All
3865 sessions listening on a particular condition will be notified
3866 asynchronously when a
<command>NOTIFY
</command> command with that
3867 condition name is executed by any session. No additional information
3868 is passed from the notifier to the listener. Thus, typically, any
3869 actual data that needs to be communicated is transferred through a
3870 database table. Commonly, the condition name is the same as the
3871 associated table, but it is not necessary for there to be any associated
3876 <application>libpq
</application> applications submit
3877 <command>LISTEN
</command> and
<command>UNLISTEN
</command> commands as
3878 ordinary SQL commands. The arrival of
<command>NOTIFY
</command>
3879 messages can subsequently be detected by calling
3880 <function>PQnotifies
</function>.
<indexterm><primary>PQnotifies<
/><
/>
3884 The function
<function>PQnotifies
</function>
3885 returns the next notification from a list of unhandled
3886 notification messages received from the server. It returns a null pointer if
3887 there are no pending notifications. Once a notification is
3888 returned from
<function>PQnotifies<
/>, it is considered handled and will be
3889 removed from the list of notifications.
3891 PGnotify *PQnotifies(PGconn *conn);
3893 typedef struct pgNotify {
3894 char *relname; /* notification condition name */
3895 int be_pid; /* process ID of notifying server process */
3896 char *extra; /* notification parameter */
3899 After processing a
<structname>PGnotify
</structname> object returned
3900 by
<function>PQnotifies
</function>, be sure to free it with
3901 <function>PQfreemem
</function>. It is sufficient to free the
3902 <structname>PGnotify
</structname> pointer; the
3903 <structfield>relname
</structfield> and
<structfield>extra
</structfield>
3904 fields do not represent separate allocations. (At present, the
3905 <structfield>extra
</structfield> field is unused and will always point
3906 to an empty string.)
3910 <xref linkend=
"libpq-example-2"> gives a sample program that illustrates
3911 the use of asynchronous notification.
3915 <function>PQnotifies
</function> does not actually read data from the
3916 server; it just returns messages previously absorbed by another
3917 <application>libpq
</application> function. In prior releases of
3918 <application>libpq
</application>, the only way to ensure timely receipt
3919 of
<command>NOTIFY<
/> messages was to constantly submit commands, even
3920 empty ones, and then check
<function>PQnotifies
</function> after each
3921 <function>PQexec
</function>. While this still works, it is deprecated
3922 as a waste of processing power.
3926 A better way to check for
<command>NOTIFY<
/> messages when you have no
3927 useful commands to execute is to call
3928 <function>PQconsumeInput
</function>, then check
3929 <function>PQnotifies
</function>. You can use
3930 <function>select()
</function> to wait for data to arrive from the
3931 server, thereby using no
<acronym>CPU
</acronym> power unless there is
3932 something to do. (See
<function>PQsocket
</function> to obtain the file
3933 descriptor number to use with
<function>select()
</function>.) Note that
3934 this will work OK whether you submit commands with
3935 <function>PQsendQuery
</function>/
<function>PQgetResult
</function> or
3936 simply use
<function>PQexec
</function>. You should, however, remember
3937 to check
<function>PQnotifies
</function> after each
3938 <function>PQgetResult
</function> or
<function>PQexec
</function>, to
3939 see if any notifications came in during the processing of the command.
3944 <sect1 id=
"libpq-copy">
3945 <title>Functions Associated with the
<command>COPY
</command> Command
</title>
3947 <indexterm zone=
"libpq-copy">
3948 <primary>COPY
</primary>
3949 <secondary>with libpq
</secondary>
3953 The
<command>COPY
</command> command in
3954 <productname>PostgreSQL
</productname> has options to read from or write
3955 to the network connection used by
<application>libpq
</application>.
3956 The functions described in this section allow applications to take
3957 advantage of this capability by supplying or consuming copied data.
3961 The overall process is that the application first issues the SQL
3962 <command>COPY
</command> command via
<function>PQexec
</function> or one
3963 of the equivalent functions. The response to this (if there is no
3964 error in the command) will be a
<structname>PGresult<
/> object bearing
3965 a status code of
<literal>PGRES_COPY_OUT
</literal> or
3966 <literal>PGRES_COPY_IN
</literal> (depending on the specified copy
3967 direction). The application should then use the functions of this
3968 section to receive or transmit data rows. When the data transfer is
3969 complete, another
<structname>PGresult<
/> object is returned to indicate
3970 success or failure of the transfer. Its status will be
3971 <literal>PGRES_COMMAND_OK
</literal> for success or
3972 <literal>PGRES_FATAL_ERROR
</literal> if some problem was encountered.
3973 At this point further SQL commands can be issued via
3974 <function>PQexec
</function>. (It is not possible to execute other SQL
3975 commands using the same connection while the
<command>COPY
</command>
3976 operation is in progress.)
3980 If a
<command>COPY
</command> command is issued via
3981 <function>PQexec
</function> in a string that could contain additional
3982 commands, the application must continue fetching results via
3983 <function>PQgetResult<
/> after completing the
<command>COPY
</command>
3984 sequence. Only when
<function>PQgetResult<
/> returns
3985 <symbol>NULL
</symbol> is it certain that the
<function>PQexec
</function>
3986 command string is done and it is safe to issue more commands.
3990 The functions of this section should be executed only after obtaining
3991 a result status of
<literal>PGRES_COPY_OUT
</literal> or
3992 <literal>PGRES_COPY_IN
</literal> from
<function>PQexec
</function> or
3993 <function>PQgetResult
</function>.
3997 A
<structname>PGresult<
/> object bearing one of these status values
3998 carries some additional data about the
<command>COPY
</command> operation
3999 that is starting. This additional data is available using functions
4000 that are also used in connection with query results:
4005 <function>PQnfields
</function>
4007 <primary>PQnfields
</primary>
4008 <secondary>with COPY
</secondary>
4014 Returns the number of columns (fields) to be copied.
4021 <function>PQbinaryTuples
</function>
4023 <primary>PQbinaryTuples
</primary>
4024 <secondary>with COPY
</secondary>
4030 0 indicates the overall copy format is textual (rows separated by
4031 newlines, columns separated by separator characters, etc).
1
4032 indicates the overall copy format is binary. See
<xref
4033 linkend=
"sql-copy" endterm=
"sql-copy-title"> for more information.
4040 <function>PQfformat
</function>
4042 <primary>PQfformat
</primary>
4043 <secondary>with COPY
</secondary>
4049 Returns the format code (
0 for text,
1 for binary) associated with
4050 each column of the copy operation. The per-column format codes
4051 will always be zero when the overall copy format is textual, but
4052 the binary format can support both text and binary columns.
4053 (However, as of the current implementation of
<command>COPY<
/>,
4054 only binary columns appear in a binary copy; so the per-column
4055 formats always match the overall format at present.)
4064 These additional data values are only available when using protocol
4065 3.0. When using protocol
2.0, all these functions will return
0.
4069 <sect2 id=
"libpq-copy-send">
4070 <title>Functions for Sending
<command>COPY
</command> Data
</title>
4073 These functions are used to send data during
<literal>COPY FROM
4074 STDIN<
/>. They will fail if called when the connection is not in
4075 <literal>COPY_IN<
/> state.
4081 <function>PQputCopyData
</function>
4083 <primary>PQputCopyData
</primary>
4089 Sends data to the server during
<literal>COPY_IN<
/> state.
4091 int PQputCopyData(PGconn *conn,
4098 Transmits the
<command>COPY
</command> data in the specified
4099 <parameter>buffer<
/>, of length
<parameter>nbytes<
/>, to the server.
4100 The result is
1 if the data was sent, zero if it was not sent
4101 because the attempt would block (this case is only possible if the
4102 connection is in nonblocking mode), or -
1 if an error occurred.
4103 (Use
<function>PQerrorMessage
</function> to retrieve details if
4104 the return value is -
1. If the value is zero, wait for write-ready
4109 The application can divide the
<command>COPY
</command> data stream
4110 into buffer loads of any convenient size. Buffer-load boundaries
4111 have no semantic significance when sending. The contents of the
4112 data stream must match the data format expected by the
4113 <command>COPY<
/> command; see
<xref linkend=
"sql-copy"
4114 endterm=
"sql-copy-title"> for details.
4121 <function>PQputCopyEnd
</function>
4123 <primary>PQputCopyEnd
</primary>
4129 Sends end-of-data indication to the server during
<literal>COPY_IN<
/> state.
4131 int PQputCopyEnd(PGconn *conn,
4132 const char *errormsg);
4137 Ends the
<literal>COPY_IN<
/> operation successfully if
4138 <parameter>errormsg<
/> is
<symbol>NULL
</symbol>. If
4139 <parameter>errormsg<
/> is not
<symbol>NULL
</symbol> then the
4140 <command>COPY<
/> is forced to fail, with the string pointed to by
4141 <parameter>errormsg<
/> used as the error message. (One should not
4142 assume that this exact error message will come back from the server,
4143 however, as the server might have already failed the
4144 <command>COPY<
/> for its own reasons. Also note that the option
4145 to force failure does not work when using pre-
3.0-protocol
4150 The result is
1 if the termination data was sent, zero if it was
4151 not sent because the attempt would block (this case is only possible
4152 if the connection is in nonblocking mode), or -
1 if an error
4153 occurred. (Use
<function>PQerrorMessage
</function> to retrieve
4154 details if the return value is -
1. If the value is zero, wait for
4155 write-ready and try again.)
4159 After successfully calling
<function>PQputCopyEnd<
/>, call
4160 <function>PQgetResult<
/> to obtain the final result status of the
4161 <command>COPY<
/> command. One can wait for this result to be
4162 available in the usual way. Then return to normal operation.
4170 <sect2 id=
"libpq-copy-receive">
4171 <title>Functions for Receiving
<command>COPY
</command> Data
</title>
4174 These functions are used to receive data during
<literal>COPY TO
4175 STDOUT<
/>. They will fail if called when the connection is not in
4176 <literal>COPY_OUT<
/> state.
4182 <function>PQgetCopyData
</function>
4184 <primary>PQgetCopyData
</primary>
4190 Receives data from the server during
<literal>COPY_OUT<
/> state.
4192 int PQgetCopyData(PGconn *conn,
4199 Attempts to obtain another row of data from the server during a
4200 <command>COPY
</command>. Data is always returned one data row at
4201 a time; if only a partial row is available, it is not returned.
4202 Successful return of a data row involves allocating a chunk of
4203 memory to hold the data. The
<parameter>buffer<
/> parameter must
4204 be non-
<symbol>NULL
</symbol>.
<parameter>*buffer<
/> is set to
4205 point to the allocated memory, or to
<symbol>NULL
</symbol> in cases
4206 where no buffer is returned. A non-
<symbol>NULL
</symbol> result
4207 buffer must be freed using
<function>PQfreemem<
/> when no longer
4212 When a row is successfully returned, the return value is the number
4213 of data bytes in the row (this will always be greater than zero).
4214 The returned string is always null-terminated, though this is
4215 probably only useful for textual
<command>COPY
</command>. A result
4216 of zero indicates that the
<command>COPY
</command> is still in
4217 progress, but no row is yet available (this is only possible when
4218 <parameter>async<
/> is true). A result of -
1 indicates that the
4219 <command>COPY
</command> is done. A result of -
2 indicates that an
4220 error occurred (consult
<function>PQerrorMessage<
/> for the reason).
4224 When
<parameter>async<
/> is true (not zero),
4225 <function>PQgetCopyData<
/> will not block waiting for input; it
4226 will return zero if the
<command>COPY
</command> is still in progress
4227 but no complete row is available. (In this case wait for read-ready
4228 and then call
<function>PQconsumeInput<
/> before calling
4229 <function>PQgetCopyData<
/> again.) When
<parameter>async<
/> is
4230 false (zero),
<function>PQgetCopyData<
/> will block until data is
4231 available or the operation completes.
4235 After
<function>PQgetCopyData<
/> returns -
1, call
4236 <function>PQgetResult<
/> to obtain the final result status of the
4237 <command>COPY<
/> command. One can wait for this result to be
4238 available in the usual way. Then return to normal operation.
4246 <sect2 id=
"libpq-copy-deprecated">
4247 <title>Obsolete Functions for
<command>COPY
</command></title>
4250 These functions represent older methods of handling
<command>COPY<
/>.
4251 Although they still work, they are deprecated due to poor error handling,
4252 inconvenient methods of detecting end-of-data, and lack of support for binary
4253 or nonblocking transfers.
4259 <function>PQgetline
</function>
4261 <primary>PQgetline
</primary>
4267 Reads a newline-terminated line of characters (transmitted
4268 by the server) into a buffer string of size
<parameter>length<
/>.
4270 int PQgetline(PGconn *conn,
4277 This function copies up to
<parameter>length<
/>-
1 characters into
4278 the buffer and converts the terminating newline into a zero byte.
4279 <function>PQgetline
</function> returns
<symbol>EOF
</symbol> at the
4280 end of input,
0 if the entire line has been read, and
1 if the
4281 buffer is full but the terminating newline has not yet been read.
4284 Note that the application must check to see if a new line consists
4285 of the two characters
<literal>\.
</literal>, which indicates
4286 that the server has finished sending the results of the
4287 <command>COPY
</command> command. If the application might receive
4288 lines that are more than
<parameter>length<
/>-
1 characters long,
4289 care is needed to be sure it recognizes the
<literal>\.
</literal>
4290 line correctly (and does not, for example, mistake the end of a
4291 long data line for a terminator line).
4298 <function>PQgetlineAsync
</function>
4300 <primary>PQgetlineAsync
</primary>
4306 Reads a row of
<command>COPY
</command> data (transmitted by the
4307 server) into a buffer without blocking.
4309 int PQgetlineAsync(PGconn *conn,
4316 This function is similar to
<function>PQgetline
</function>, but it can be used
4318 that must read
<command>COPY
</command> data asynchronously, that is, without blocking.
4319 Having issued the
<command>COPY
</command> command and gotten a
<literal>PGRES_COPY_OUT
</literal>
4321 application should call
<function>PQconsumeInput
</function> and
4322 <function>PQgetlineAsync
</function> until the
4323 end-of-data signal is detected.
4326 Unlike
<function>PQgetline
</function>, this function takes
4327 responsibility for detecting end-of-data.
4331 On each call,
<function>PQgetlineAsync
</function> will return data if a
4332 complete data row is available in
<application>libpq<
/>'s input buffer.
4333 Otherwise, no data is returned until the rest of the row arrives.
4334 The function returns -
1 if the end-of-copy-data marker has been recognized,
4335 or
0 if no data is available, or a positive number giving the number of
4336 bytes of data returned. If -
1 is returned, the caller must next call
4337 <function>PQendcopy
</function>, and then return to normal processing.
4341 The data returned will not extend beyond a data-row boundary. If possible
4342 a whole row will be returned at one time. But if the buffer offered by
4343 the caller is too small to hold a row sent by the server, then a partial
4344 data row will be returned. With textual data this can be detected by testing
4345 whether the last returned byte is
<literal>\n
</literal> or not. (In a binary
4346 <command>COPY<
/>, actual parsing of the
<command>COPY<
/> data format will be needed to make the
4347 equivalent determination.)
4348 The returned string is not null-terminated. (If you want to add a
4349 terminating null, be sure to pass a
<parameter>bufsize
</parameter> one smaller
4350 than the room actually available.)
4357 <function>PQputline
</function>
4359 <primary>PQputline
</primary>
4365 Sends a null-terminated string to the server. Returns
0 if
4366 OK and
<symbol>EOF
</symbol> if unable to send the string.
4368 int PQputline(PGconn *conn,
4369 const char *string);
4374 The
<command>COPY
</command> data stream sent by a series of calls
4375 to
<function>PQputline
</function> has the same format as that
4376 returned by
<function>PQgetlineAsync
</function>, except that
4377 applications are not obliged to send exactly one data row per
4378 <function>PQputline
</function> call; it is okay to send a partial
4379 line or multiple lines per call.
4384 Before
<productname>PostgreSQL
</productname> protocol
3.0, it was necessary
4385 for the application to explicitly send the two characters
4386 <literal>\.
</literal> as a final line to indicate to the server that it had
4387 finished sending
<command>COPY<
/> data. While this still works, it is deprecated and the
4388 special meaning of
<literal>\.
</literal> can be expected to be removed in a
4389 future release. It is sufficient to call
<function>PQendcopy
</function> after
4390 having sent the actual data.
4398 <function>PQputnbytes
</function>
4400 <primary>PQputnbytes
</primary>
4406 Sends a non-null-terminated string to the server. Returns
4407 0 if OK and
<symbol>EOF
</symbol> if unable to send the string.
4409 int PQputnbytes(PGconn *conn,
4416 This is exactly like
<function>PQputline
</function>, except that the data
4417 buffer need not be null-terminated since the number of bytes to send is
4418 specified directly. Use this procedure when sending binary data.
4425 <function>PQendcopy
</function>
4427 <primary>PQendcopy
</primary>
4433 Synchronizes with the server.
4435 int PQendcopy(PGconn *conn);
4437 This function waits until the server has finished the copying.
4438 It should either be issued when the last string has been sent
4439 to the server using
<function>PQputline
</function> or when the
4440 last string has been received from the server using
4441 <function>PGgetline
</function>. It must be issued or the server
4442 will get
<quote>out of sync
</quote> with the client. Upon return
4443 from this function, the server is ready to receive the next SQL
4444 command. The return value is
0 on successful completion,
4445 nonzero otherwise. (Use
<function>PQerrorMessage
</function> to
4446 retrieve details if the return value is nonzero.)
4450 When using
<function>PQgetResult
</function>, the application should
4451 respond to a
<literal>PGRES_COPY_OUT
</literal> result by executing
4452 <function>PQgetline
</function> repeatedly, followed by
4453 <function>PQendcopy
</function> after the terminator line is seen.
4454 It should then return to the
<function>PQgetResult
</function> loop
4455 until
<function>PQgetResult
</function> returns a null pointer.
4456 Similarly a
<literal>PGRES_COPY_IN
</literal> result is processed
4457 by a series of
<function>PQputline
</function> calls followed by
4458 <function>PQendcopy
</function>, then return to the
4459 <function>PQgetResult
</function> loop. This arrangement will
4460 ensure that a
<command>COPY
</command> command embedded in a series
4461 of
<acronym>SQL
</acronym> commands will be executed correctly.
4465 Older applications are likely to submit a
<command>COPY
</command>
4466 via
<function>PQexec
</function> and assume that the transaction
4467 is done after
<function>PQendcopy
</function>. This will work
4468 correctly only if the
<command>COPY
</command> is the only
4469 <acronym>SQL
</acronym> command in the command string.
4479 <sect1 id=
"libpq-control">
4480 <title>Control Functions
</title>
4483 These functions control miscellaneous details of
<application>libpq<
/>'s
4490 <function>PQclientEncoding
</function>
4492 <primary>PQclientEncoding
</primary>
4498 Returns the client encoding.
4500 int PQclientEncoding(const PGconn *
<replaceable>conn
</replaceable>);
4503 Note that it returns the encoding ID, not a symbolic string
4504 such as
<literal>EUC_JP
</literal>. To convert an encoding ID to an encoding name, you
4508 char *pg_encoding_to_char(int
<replaceable>encoding_id
</replaceable>);
4516 <function>PQsetClientEncoding
</function>
4518 <primary>PQsetClientEncoding
</primary>
4524 Sets the client encoding.
4526 int PQsetClientEncoding(PGconn *
<replaceable>conn
</replaceable>, const char *
<replaceable>encoding
</replaceable>);
4529 <replaceable>conn
</replaceable> is a connection to the server,
4530 and
<replaceable>encoding
</replaceable> is the encoding you want to
4531 use. If the function successfully sets the encoding, it returns
0,
4532 otherwise -
1. The current encoding for this connection can be
4533 determined by using
<function>PQclientEncoding<
/>.
4540 <function>PQsetErrorVerbosity
</function>
4542 <primary>PQsetErrorVerbosity
</primary>
4548 Determines the verbosity of messages returned by
4549 <function>PQerrorMessage<
/> and
<function>PQresultErrorMessage<
/>.
4557 PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity);
4560 <function>PQsetErrorVerbosity<
/> sets the verbosity mode, returning
4561 the connection's previous setting. In
<firstterm>TERSE<
/> mode,
4562 returned messages include severity, primary text, and position only;
4563 this will normally fit on a single line. The default mode produces
4564 messages that include the above plus any detail, hint, or context
4565 fields (these might span multiple lines). The
<firstterm>VERBOSE<
/>
4566 mode includes all available fields. Changing the verbosity does not
4567 affect the messages available from already-existing
4568 <structname>PGresult<
/> objects, only subsequently-created ones.
4575 <function>PQtrace
</function>
4577 <primary>PQtrace
</primary>
4583 Enables tracing of the client/server communication to a debugging file stream.
4585 void PQtrace(PGconn *conn, FILE *stream);
4591 On Windows, if the
<application>libpq<
/> library and an application are
4592 compiled with different flags, this function call will crash the
4593 application because the internal representation of the
<literal>FILE<
/>
4594 pointers differ. Specifically, multithreaded/single-threaded,
4595 release/debug, and static/dynamic flags should be the same for the
4596 library and all applications using that library.
4605 <function>PQuntrace
</function>
4607 <primary>PQuntrace
</primary>
4613 Disables tracing started by
<function>PQtrace
</function>.
4615 void PQuntrace(PGconn *conn);
4624 <sect1 id=
"libpq-misc">
4625 <title>Miscellaneous Functions
</title>
4628 As always, there are some functions that just don't fit anywhere.
4634 <function>PQfreemem
</function>
4636 <primary>PQfreemem
</primary>
4642 Frees memory allocated by
<application>libpq<
/>.
4644 void PQfreemem(void *ptr);
4649 Frees memory allocated by
<application>libpq<
/>, particularly
4650 <function>PQescapeByteaConn
</function>,
4651 <function>PQescapeBytea
</function>,
4652 <function>PQunescapeBytea
</function>,
4653 and
<function>PQnotifies
</function>.
4654 It is particularly important that this function, rather than
4655 <function>free()<
/>, be used on Microsoft Windows. This is because
4656 allocating memory in a DLL and releasing it in the application works
4657 only if multithreaded/single-threaded, release/debug, and static/dynamic
4658 flags are the same for the DLL and the application. On non-Microsoft
4659 Windows platforms, this function is the same as the standard library
4660 function
<function>free()<
/>.
4667 <function>PQconninfoFree
</function>
4669 <primary>PQconninfoFree
</primary>
4675 Frees the data structures allocated by
4676 <function>PQconndefaults<
/> or
<function>PQconninfoParse<
/>.
4678 void PQconninfoFree(PQconninfoOption *connOptions);
4683 A simple
<function>PQfreemem
</function> will not do for this, since
4684 the array contains references to subsidiary strings.
4691 <function>PQencryptPassword
</function>
4693 <primary>PQencryptPassword
</primary>
4699 Prepares the encrypted form of a
<productname>PostgreSQL<
/> password.
4701 char * PQencryptPassword(const char *passwd, const char *user);
4703 This function is intended to be used by client applications that
4704 wish to send commands like
<literal>ALTER USER joe PASSWORD
4705 'pwd'<
/>. It is good practice not to send the original cleartext
4706 password in such a command, because it might be exposed in command
4707 logs, activity displays, and so on. Instead, use this function to
4708 convert the password to encrypted form before it is sent. The
4709 arguments are the cleartext password, and the SQL name of the user
4710 it is for. The return value is a string allocated by
4711 <function>malloc
</function>, or
<symbol>NULL
</symbol> if out of
4712 memory. The caller can assume the string doesn't contain any
4713 special characters that would require escaping. Use
4714 <function>PQfreemem<
/> to free the result when done with it.
4721 <function>PQmakeEmptyPGresult
</function>
4723 <primary>PQmakeEmptyPGresult
</primary>
4729 Constructs an empty
<structname>PGresult
</structname> object with the given status.
4731 PGresult *PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status);
4736 This is
<application>libpq<
/>'s internal function to allocate and
4737 initialize an empty
<structname>PGresult
</structname> object. This
4738 function returns NULL if memory could not be allocated. It is
4739 exported because some applications find it useful to generate result
4740 objects (particularly objects with error status) themselves. If
4741 <parameter>conn
</parameter> is not null and
<parameter>status<
/>
4742 indicates an error, the current error message of the specified
4743 connection is copied into the
<structname>PGresult
</structname>.
4744 Also, if
<parameter>conn
</parameter> is not null, any event procedures
4745 registered in the connection are copied into the
4746 <structname>PGresult
</structname>. (They do not get
4747 <literal>PGEVT_RESULTCREATE<
/> calls, but see
4748 <function>PQfireResultCreateEvents
</function>.)
4749 Note that
<function>PQclear
</function> should eventually be called
4750 on the object, just as with a
<structname>PGresult
</structname>
4751 returned by
<application>libpq
</application> itself.
4758 <function>PQfireResultCreateEvents
</function>
4760 <primary>PQfireResultCreateEvents
</primary>
4765 Fires a
<literal>PGEVT_RESULTCREATE
</literal> event (see
<xref
4766 linkend=
"libpq-events">) for each event procedure registered in the
4767 <structname>PGresult
</structname> object. Returns non-zero for success,
4768 zero if any event procedure fails.
4771 int PQfireResultCreateEvents(PGconn *conn, PGresult *res);
4776 The
<literal>conn<
/> argument is passed through to event procedures
4777 but not used directly. It can be
<literal>NULL<
/> if the event
4778 procedures won't use it.
4782 Event procedures that have already received a
4783 <literal>PGEVT_RESULTCREATE<
/> or
<literal>PGEVT_RESULTCOPY<
/> event
4784 for this object are not fired again.
4788 The main reason that this function is separate from
4789 <function>PQmakeEmptyPGResult
</function> is that it is often appropriate
4790 to create a
<structname>PGresult
</structname> and fill it with data
4791 before invoking the event procedures.
4798 <function>PQcopyResult
</function>
4800 <primary>PQcopyResult
</primary>
4806 Makes a copy of a
<structname>PGresult
</structname> object. The copy is
4807 not linked to the source result in any way and
4808 <function>PQclear
</function> must be called when the copy is no longer
4809 needed. If the function fails, NULL is returned.
4812 PGresult *PQcopyResult(const PGresult *src, int flags);
4817 This is not intended to make an exact copy. The returned result is
4818 always put into
<literal>PGRES_TUPLES_OK
</literal> status, and does not
4819 copy any error message in the source. (It does copy the command status
4820 string, however.) The
<parameter>flags
</parameter> argument determines
4821 what else is copied. It is a bitwise OR of several flags.
4822 <literal>PG_COPYRES_ATTRS
</literal> specifies copying the source
4823 result's attributes (column definitions).
4824 <literal>PG_COPYRES_TUPLES
</literal> specifies copying the source
4825 result's tuples. (This implies copying the attributes, too.)
4826 <literal>PG_COPYRES_NOTICEHOOKS
</literal> specifies
4827 copying the source result's notify hooks.
4828 <literal>PG_COPYRES_EVENTS
</literal> specifies copying the source
4829 result's events. (But any instance data associated with the source
4837 <function>PQsetResultAttrs
</function>
4839 <primary>PQsetResultAttrs
</primary>
4845 Sets the attributes of a
<structname>PGresult
</structname> object.
4847 int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs);
4852 The provided
<parameter>attDescs
</parameter> are copied into the result.
4853 If the
<parameter>attDescs
</parameter> pointer is NULL or
4854 <parameter>numAttributes
</parameter> is less than one, the request is
4855 ignored and the function succeeds. If
<parameter>res
</parameter>
4856 already contains attributes, the function will fail. If the function
4857 fails, the return value is zero. If the function succeeds, the return
4865 <function>PQsetvalue
</function>
4867 <primary>PQsetvalue
</primary>
4873 Sets a tuple field value of a
<structname>PGresult
</structname> object.
4875 int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len);
4880 The function will automatically grow the result's internal tuples array
4881 as needed. However, the
<parameter>tup_num
</parameter> argument must be
4882 less than or equal to
<function>PQntuples
</function>, meaning this
4883 function can only grow the tuples array one tuple at a time. But any
4884 field of any existing tuple can be modified in any order. If a value at
4885 <parameter>field_num
</parameter> already exists, it will be overwritten.
4886 If
<parameter>len
</parameter> is
<literal>-
1</literal> or
4887 <parameter>value
</parameter> is
<literal>NULL
</literal>, the field value
4888 will be set to an SQL
<literal>NULL
</literal>. The
4889 <parameter>value
</parameter> is copied into the result's private storage,
4890 thus is no longer needed after the function
4891 returns. If the function fails, the return value is zero. If the
4892 function succeeds, the return value is non-zero.
4899 <function>PQresultAlloc
</function>
4901 <primary>PQresultAlloc
</primary>
4907 Allocate subsidiary storage for a
<structname>PGresult
</structname> object.
4909 void *PQresultAlloc(PGresult *res, size_t nBytes);
4914 Any memory allocated with this function will be freed when
4915 <parameter>res
</parameter> is cleared. If the function fails,
4916 the return value is
<literal>NULL
</literal>. The result is
4917 guaranteed to be adequately aligned for any type of data,
4918 just as for
<function>malloc<
/>.
4927 <sect1 id=
"libpq-notice-processing">
4928 <title>Notice Processing
</title>
4930 <indexterm zone=
"libpq-notice-processing">
4931 <primary>notice processing
</primary>
4932 <secondary>in libpq
</secondary>
4936 Notice and warning messages generated by the server are not returned
4937 by the query execution functions, since they do not imply failure of
4938 the query. Instead they are passed to a notice handling function, and
4939 execution continues normally after the handler returns. The default
4940 notice handling function prints the message on
4941 <filename>stderr
</filename>, but the application can override this
4942 behavior by supplying its own handling function.
4946 For historical reasons, there are two levels of notice handling, called
4947 the notice receiver and notice processor. The default behavior is for
4948 the notice receiver to format the notice and pass a string to the notice
4949 processor for printing. However, an application that chooses to provide
4950 its own notice receiver will typically ignore the notice processor
4951 layer and just do all the work in the notice receiver.
4955 The function
<function>PQsetNoticeReceiver
</function>
4956 <indexterm><primary>notice
4957 receiver<
/><
/><indexterm><primary>PQsetNoticeReceiver<
/><
/> sets or
4958 examines the current notice receiver for a connection object.
4959 Similarly,
<function>PQsetNoticeProcessor
</function>
4960 <indexterm><primary>notice
4961 processor<
/><
/><indexterm><primary>PQsetNoticeProcessor<
/><
/> sets or
4962 examines the current notice processor.
4965 typedef void (*PQnoticeReceiver) (void *arg, const PGresult *res);
4968 PQsetNoticeReceiver(PGconn *conn,
4969 PQnoticeReceiver proc,
4972 typedef void (*PQnoticeProcessor) (void *arg, const char *message);
4975 PQsetNoticeProcessor(PGconn *conn,
4976 PQnoticeProcessor proc,
4980 Each of these functions returns the previous notice receiver or
4981 processor function pointer, and sets the new value. If you supply a
4982 null function pointer, no action is taken, but the current pointer is
4987 When a notice or warning message is received from the server, or
4988 generated internally by
<application>libpq
</application>, the notice
4989 receiver function is called. It is passed the message in the form of
4990 a
<symbol>PGRES_NONFATAL_ERROR
</symbol>
4991 <structname>PGresult
</structname>. (This allows the receiver to extract
4992 individual fields using
<function>PQresultErrorField<
/>, or the complete
4993 preformatted message using
<function>PQresultErrorMessage<
/>.) The same
4994 void pointer passed to
<function>PQsetNoticeReceiver
</function> is also
4995 passed. (This pointer can be used to access application-specific state
5000 The default notice receiver simply extracts the message (using
5001 <function>PQresultErrorMessage<
/>) and passes it to the notice
5006 The notice processor is responsible for handling a notice or warning
5007 message given in text form. It is passed the string text of the message
5008 (including a trailing newline), plus a void pointer that is the same
5009 one passed to
<function>PQsetNoticeProcessor
</function>. (This pointer
5010 can be used to access application-specific state if needed.)
5014 The default notice processor is simply:
5017 defaultNoticeProcessor(void *arg, const char *message)
5019 fprintf(stderr,
"%s", message);
5025 Once you have set a notice receiver or processor, you should expect
5026 that that function could be called as long as either the
5027 <structname>PGconn<
/> object or
<structname>PGresult<
/> objects made
5028 from it exist. At creation of a
<structname>PGresult<
/>, the
5029 <structname>PGconn<
/>'s current notice handling pointers are copied
5030 into the
<structname>PGresult<
/> for possible use by functions like
5031 <function>PQgetvalue
</function>.
5036 <sect1 id=
"libpq-events">
5037 <title>Event System
</title>
5040 <application>libpq
</application>'s event system is designed to notify
5041 registered event handlers about interesting
5042 <application>libpq
</application> events, such as the creation or
5043 destruction of
<structname>PGconn
</structname> and
5044 <structname>PGresult
</structname> objects. A principal use case is that
5045 this allows applications to associate their own data with a
5046 <structname>PGconn
</structname> or
<structname>PGresult
</structname>
5047 and ensure that that data is freed at an appropriate time.
5051 Each registered event handler is associated with two pieces of data,
5052 known to
<application>libpq
</application> only as opaque
<literal>void *<
/>
5053 pointers. There is a
<firstterm>passthrough<
/> pointer that is provided
5054 by the application when the event handler is registered with a
5055 <structname>PGconn<
/>. The passthrough pointer never changes for the
5056 life of the
<structname>PGconn<
/> and all
<structname>PGresult<
/>s
5057 generated from it; so if used, it must point to long-lived data.
5058 In addition there is an
<firstterm>instance data<
/> pointer, which starts
5059 out NULL in every
<structname>PGconn<
/> and
<structname>PGresult<
/>.
5060 This pointer can be manipulated using the
5061 <function>PQinstanceData
</function>,
5062 <function>PQsetInstanceData
</function>,
5063 <function>PQresultInstanceData
</function> and
5064 <function>PQsetResultInstanceData
</function> functions. Note that
5065 unlike the passthrough pointer, instance data of a
<structname>PGconn<
/>
5066 is not automatically inherited by
<structname>PGresult<
/>s created from
5067 it.
<application>libpq
</application> does not know what passthrough
5068 and instance data pointers point to (if anything) and will never attempt
5069 to free them
— that is the responsibility of the event handler.
5072 <sect2 id=
"libpq-events-types">
5073 <title>Event Types
</title>
5076 The enum
<literal>PGEventId<
/> names the types of events handled by
5077 the event system. All its values have names beginning with
5078 <literal>PGEVT
</literal>. For each event type, there is a corresponding
5079 event info structure that carries the parameters passed to the event
5080 handlers. The event types are:
5085 <term><literal>PGEVT_REGISTER
</literal></term>
5088 The register event occurs when
<function>PQregisterEventProc
</function>
5089 is called. It is the ideal time to initialize any
5090 <literal>instanceData
</literal> an event procedure may need. Only one
5091 register event will be fired per event handler per connection. If the
5092 event procedure fails, the registration is aborted.
5101 When a
<literal>PGEVT_REGISTER
</literal> event is received, the
5102 <parameter>evtInfo
</parameter> pointer should be cast to a
5103 <structname>PGEventRegister *
</structname>. This structure contains a
5104 <structname>PGconn
</structname> that should be in the
5105 <literal>CONNECTION_OK
</literal> status; guaranteed if one calls
5106 <function>PQregisterEventProc
</function> right after obtaining a good
5107 <structname>PGconn
</structname>. When returning a failure code, all
5108 cleanup must be performed as no
<literal>PGEVT_CONNDESTROY
</literal>
5115 <term><literal>PGEVT_CONNRESET
</literal></term>
5118 The connection reset event is fired on completion of
5119 <function>PQreset
</function> or
<function>PQresetPoll
</function>. In
5120 both cases, the event is only fired if the reset was successful. If
5121 the event procedure fails, the entire connection reset will fail; the
5122 <structname>PGconn
</structname> is put into
5123 <literal>CONNECTION_BAD
</literal> status and
5124 <function>PQresetPoll
</function> will return
5125 <literal>PGRES_POLLING_FAILED
</literal>.
5134 When a
<literal>PGEVT_CONNRESET
</literal> event is received, the
5135 <parameter>evtInfo
</parameter> pointer should be cast to a
5136 <structname>PGEventConnReset *
</structname>. Although the contained
5137 <structname>PGconn
</structname> was just reset, all event data remains
5138 unchanged. This event should be used to reset/reload/requery any
5139 associated
<literal>instanceData
</literal>. Note that even if the
5140 event procedure fails to process
<literal>PGEVT_CONNRESET<
/>, it will
5141 still receive a
<literal>PGEVT_CONNDESTROY<
/> event when the connection
5148 <term><literal>PGEVT_CONNDESTROY
</literal></term>
5151 The connection destroy event is fired in response to
5152 <function>PQfinish
</function>. It is the event procedure's
5153 responsibility to properly clean up its event data as libpq has no
5154 ability to manage this memory. Failure to clean up will lead
5161 } PGEventConnDestroy;
5164 When a
<literal>PGEVT_CONNDESTROY
</literal> event is received, the
5165 <parameter>evtInfo
</parameter> pointer should be cast to a
5166 <structname>PGEventConnDestroy *
</structname>. This event is fired
5167 prior to
<function>PQfinish
</function> performing any other cleanup.
5168 The return value of the event procedure is ignored since there is no
5169 way of indicating a failure from
<function>PQfinish
</function>. Also,
5170 an event procedure failure should not abort the process of cleaning up
5177 <term><literal>PGEVT_RESULTCREATE
</literal></term>
5180 The result creation event is fired in response to any query execution
5181 function that generates a result, including
5182 <function>PQgetResult
</function>. This event will only be fired after
5183 the result has been created successfully.
5190 } PGEventResultCreate;
5193 When a
<literal>PGEVT_RESULTCREATE
</literal> event is received, the
5194 <parameter>evtInfo
</parameter> pointer should be cast to a
5195 <structname>PGEventResultCreate *
</structname>. The
5196 <parameter>conn
</parameter> is the connection used to generate the
5197 result. This is the ideal place to initialize any
5198 <literal>instanceData
</literal> that needs to be associated with the
5199 result. If the event procedure fails, the result will be cleared and
5200 the failure will be propagated. The event procedure must not try to
5201 <function>PQclear<
/> the result object for itself. When returning a
5202 failure code, all cleanup must be performed as no
5203 <literal>PGEVT_RESULTDESTROY
</literal> event will be sent.
5209 <term><literal>PGEVT_RESULTCOPY
</literal></term>
5212 The result copy event is fired in response to
5213 <function>PQcopyResult
</function>. This event will only be fired after
5214 the copy is complete. Only event procedures that have
5215 successfully handled the
<literal>PGEVT_RESULTCREATE
</literal>
5216 or
<literal>PGEVT_RESULTCOPY
</literal> event for the source result
5217 will receive
<literal>PGEVT_RESULTCOPY
</literal> events.
5222 const PGresult *src;
5224 } PGEventResultCopy;
5227 When a
<literal>PGEVT_RESULTCOPY
</literal> event is received, the
5228 <parameter>evtInfo
</parameter> pointer should be cast to a
5229 <structname>PGEventResultCopy *
</structname>. The
5230 <parameter>src
</parameter> result is what was copied while the
5231 <parameter>dest
</parameter> result is the copy destination. This event
5232 can be used to provide a deep copy of
<literal>instanceData
</literal>,
5233 since
<literal>PQcopyResult
</literal> cannot do that. If the event
5234 procedure fails, the entire copy operation will fail and the
5235 <parameter>dest
</parameter> result will be cleared. When returning a
5236 failure code, all cleanup must be performed as no
5237 <literal>PGEVT_RESULTDESTROY
</literal> event will be sent for the
5244 <term><literal>PGEVT_RESULTDESTROY
</literal></term>
5247 The result destroy event is fired in response to a
5248 <function>PQclear
</function>. It is the event procedure's
5249 responsibility to properly clean up its event data as libpq has no
5250 ability to manage this memory. Failure to clean up will lead
5257 } PGEventResultDestroy;
5260 When a
<literal>PGEVT_RESULTDESTROY
</literal> event is received, the
5261 <parameter>evtInfo
</parameter> pointer should be cast to a
5262 <structname>PGEventResultDestroy *
</structname>. This event is fired
5263 prior to
<function>PQclear
</function> performing any other cleanup.
5264 The return value of the event procedure is ignored since there is no
5265 way of indicating a failure from
<function>PQclear
</function>. Also,
5266 an event procedure failure should not abort the process of cleaning up
5274 <sect2 id=
"libpq-events-proc">
5275 <title>Event Callback Procedure
</title>
5280 <literal>PGEventProc
</literal>
5282 <primary>PGEventProc
</primary>
5288 <literal>PGEventProc
</literal> is a typedef for a pointer to an
5289 event procedure, that is, the user callback function that receives
5290 events from libpq. The signature of an event procedure must be
5293 int eventproc(PGEventId evtId, void *evtInfo, void *passThrough)
5296 The
<parameter>evtId
</parameter> parameter indicates which
5297 <literal>PGEVT
</literal> event occurred. The
5298 <parameter>evtInfo
</parameter> pointer must be cast to the appropriate
5299 structure type to obtain further information about the event.
5300 The
<parameter>passThrough
</parameter> parameter is the pointer
5301 provided to
<function>PQregisterEventProc
</function> when the event
5302 procedure was registered. The function should return a non-zero value
5303 if it succeeds and zero if it fails.
5307 A particular event procedure can be registered only once in any
5308 <structname>PGconn<
/>. This is because the address of the procedure
5309 is used as a lookup key to identify the associated instance data.
5314 On Windows, functions can have two different addresses: one visible
5315 from outside a DLL and another visible from inside the DLL. One
5316 should be careful that only one of these addresses is used with
5317 <application>libpq<
/>'s event-procedure functions, else confusion will
5318 result. The simplest rule for writing code that will work is to
5319 ensure that event procedures are declared
<literal>static<
/>. If the
5320 procedure's address must be available outside its own source file,
5321 expose a separate function to return the address.
5329 <sect2 id=
"libpq-events-funcs">
5330 <title>Event Support Functions
</title>
5335 <function>PQregisterEventProc
</function>
5337 <primary>PQregisterEventProc
</primary>
5343 Registers an event callback procedure with libpq.
5346 int PQregisterEventProc(PGconn *conn, PGEventProc proc,
5347 const char *name, void *passThrough);
5352 An event procedure must be registered once on each
5353 <structname>PGconn<
/> you want to receive events about. There is no
5354 limit, other than memory, on the number of event procedures that
5355 can be registered with a connection. The function returns a non-zero
5356 value if it succeeds and zero if it fails.
5360 The
<parameter>proc
</parameter> argument will be called when a libpq
5361 event is fired. Its memory address is also used to lookup
5362 <literal>instanceData
</literal>. The
<parameter>name
</parameter>
5363 argument is used to refer to the event procedure in error messages.
5364 This value cannot be NULL or a zero-length string. The name string is
5365 copied into the
<structname>PGconn<
/>, so what is passed need not be
5366 long-lived. The
<parameter>passThrough
</parameter> pointer is passed
5367 to the
<parameter>proc
</parameter> whenever an event occurs. This
5368 argument can be NULL.
5375 <function>PQsetInstanceData
</function>
5377 <primary>PQsetInstanceData
</primary>
5382 Sets the conn's instanceData for proc to data. This returns non-zero
5383 for success and zero for failure. (Failure is only possible if
5384 the proc has not been properly registered in the conn.)
5387 int PQsetInstanceData(PGconn *conn, PGEventProc proc, void *data);
5395 <function>PQinstanceData
</function>
5397 <primary>PQinstanceData
</primary>
5402 Returns the conn's instanceData associated with proc, or NULL
5406 void *PQinstanceData(const PGconn *conn, PGEventProc proc);
5414 <function>PQresultSetInstanceData
</function>
5416 <primary>PQresultSetInstanceData
</primary>
5421 Sets the result's instanceData for proc to data. This returns non-zero
5422 for success and zero for failure. (Failure is only possible if the
5423 proc has not been properly registered in the result.)
5426 int PQresultSetInstanceData(PGresult *res, PGEventProc proc, void *data);
5434 <function>PQresultInstanceData
</function>
5436 <primary>PQresultInstanceData
</primary>
5441 Returns the result's instanceData associated with proc, or NULL
5445 void *PQresultInstanceData(const PGresult *res, PGEventProc proc);
5453 <sect2 id=
"libpq-events-example">
5454 <title>Event Example
</title>
5457 Here is a skeleton example of managing private data associated with
5458 libpq connections and results.
5463 /* required header for libpq events (note: includes libpq-fe.h) */
5464 #include
<libpq-events.h
>
5466 /* The instanceData */
5474 static int myEventProc(PGEventId evtId, void *evtInfo, void *passThrough);
5481 PGconn *conn = PQconnectdb(
"dbname = postgres");
5483 if (PQstatus(conn) != CONNECTION_OK)
5485 fprintf(stderr,
"Connection to database failed: %s",
5486 PQerrorMessage(conn));
5491 /* called once on any connection that should receive events.
5492 * Sends a PGEVT_REGISTER to myEventProc.
5494 if (!PQregisterEventProc(conn, myEventProc,
"mydata_proc", NULL))
5496 fprintf(stderr,
"Cannot register PGEventProc\n");
5501 /* conn instanceData is available */
5502 data = PQinstanceData(conn, myEventProc);
5504 /* Sends a PGEVT_RESULTCREATE to myEventProc */
5505 res = PQexec(conn,
"SELECT 1 + 1");
5507 /* result instanceData is available */
5508 data = PQresultInstanceData(res, myEventProc);
5510 /* If PG_COPYRES_EVENTS is used, sends a PGEVT_RESULTCOPY to myEventProc */
5511 res_copy = PQcopyResult(res, PG_COPYRES_TUPLES | PG_COPYRES_EVENTS);
5513 /* result instanceData is available if PG_COPYRES_EVENTS was
5514 * used during the PQcopyResult call.
5516 data = PQresultInstanceData(res_copy, myEventProc);
5518 /* Both clears send a PGEVT_RESULTDESTROY to myEventProc */
5522 /* Sends a PGEVT_CONNDESTROY to myEventProc */
5529 myEventProc(PGEventId evtId, void *evtInfo, void *passThrough)
5533 case PGEVT_REGISTER:
5535 PGEventRegister *e = (PGEventRegister *)evtInfo;
5536 mydata *data = get_mydata(e-
>conn);
5538 /* associate app specific data with connection */
5539 PQsetInstanceData(e-
>conn, myEventProc, data);
5543 case PGEVT_CONNRESET:
5545 PGEventConnReset *e = (PGEventConnReset *)evtInfo;
5546 mydata *data = PQinstanceData(e-
>conn, myEventProc);
5549 memset(data,
0, sizeof(mydata));
5553 case PGEVT_CONNDESTROY:
5555 PGEventConnDestroy *e = (PGEventConnDestroy *)evtInfo;
5556 mydata *data = PQinstanceData(e-
>conn, myEventProc);
5558 /* free instance data because the conn is being destroyed */
5564 case PGEVT_RESULTCREATE:
5566 PGEventResultCreate *e = (PGEventResultCreate *)evtInfo;
5567 mydata *conn_data = PQinstanceData(e-
>conn, myEventProc);
5568 mydata *res_data = dup_mydata(conn_data);
5570 /* associate app specific data with result (copy it from conn) */
5571 PQsetResultInstanceData(e-
>result, myEventProc, res_data);
5575 case PGEVT_RESULTCOPY:
5577 PGEventResultCopy *e = (PGEventResultCopy *)evtInfo;
5578 mydata *src_data = PQresultInstanceData(e-
>src, myEventProc);
5579 mydata *dest_data = dup_mydata(src_data);
5581 /* associate app specific data with result (copy it from a result) */
5582 PQsetResultInstanceData(e-
>dest, myEventProc, dest_data);
5586 case PGEVT_RESULTDESTROY:
5588 PGEventResultDestroy *e = (PGEventResultDestroy *)evtInfo;
5589 mydata *data = PQresultInstanceData(e-
>result, myEventProc);
5591 /* free instance data because the result is being destroyed */
5597 /* unknown event id, just return TRUE. */
5602 return TRUE; /* event processing succeeded */
5609 <sect1 id=
"libpq-envars">
5610 <title>Environment Variables
</title>
5612 <indexterm zone=
"libpq-envars">
5613 <primary>environment variable
</primary>
5617 The following environment variables can be used to select default
5618 connection parameter values, which will be used by
5619 <function>PQconnectdb<
/>,
<function>PQsetdbLogin<
/> and
5620 <function>PQsetdb<
/> if no value is directly specified by the calling
5621 code. These are useful to avoid hard-coding database connection
5622 information into simple client applications, for example.
5628 <primary><envar>PGHOST
</envar></primary>
5630 <envar>PGHOST
</envar> sets the database server name.
5631 If this begins with a slash, it specifies Unix-domain communication
5632 rather than TCP/IP communication; the value is then the name of the
5633 directory in which the socket file is stored (in a default installation
5634 setup this would be
<filename>/tmp
</filename>).
5641 <primary><envar>PGHOSTADDR
</envar></primary>
5643 <envar>PGHOSTADDR
</envar> specifies the numeric IP address of the database
5644 server. This can be set instead of or in addition to
<envar>PGHOST
</envar>
5645 to avoid DNS lookup overhead. See the documentation of
5646 these parameters, under
<function>PQconnectdb
</function> above, for details
5647 on their interaction.
5650 When neither
<envar>PGHOST
</envar> nor
<envar>PGHOSTADDR
</envar> is set,
5651 the default behavior is to connect using a local Unix-domain socket; or on
5652 machines without Unix-domain sockets,
<application>libpq
</application> will
5653 attempt to connect to
<literal>localhost<
/>.
5660 <primary><envar>PGPORT
</envar></primary>
5662 <envar>PGPORT
</envar> sets the TCP port number or Unix-domain socket
5663 file extension for communicating with the
5664 <productname>PostgreSQL
</productname> server.
5671 <primary><envar>PGDATABASE
</envar></primary>
5673 <envar>PGDATABASE
</envar> sets the
5674 <productname>PostgreSQL
</productname> database name.
5681 <primary><envar>PGUSER
</envar></primary>
5683 <envar>PGUSER
</envar> sets the user name used to connect to the
5691 <primary><envar>PGPASSWORD
</envar></primary>
5693 <envar>PGPASSWORD
</envar> sets the password used if the server
5694 demands password authentication. Use of this environment variable
5695 is not recommended for security reasons (some operating systems
5696 allow non-root users to see process environment variables via
5697 <application>ps<
/>); instead consider using the
5698 <filename>~/.pgpass<
/> file (see
<xref linkend=
"libpq-pgpass">).
5705 <primary><envar>PGPASSFILE
</envar></primary>
5707 <envar>PGPASSFILE
</envar> specifies the name of the password file to
5708 use for lookups. If not set, it defaults to
<filename>~/.pgpass<
/>
5709 (see
<xref linkend=
"libpq-pgpass">).
5716 <primary><envar>PGSERVICE
</envar></primary>
5718 <envar>PGSERVICE
</envar>
5719 sets the service name to be looked up in
5720 <filename>pg_service.conf
</filename>. This offers a shorthand way
5721 of setting all the parameters.
5728 <primary><envar>PGREALM
</envar></primary>
5730 <envar>PGREALM
</envar> sets the Kerberos realm to use with
5731 <productname>PostgreSQL
</productname>, if it is different from the
5732 local realm. If
<envar>PGREALM
</envar> is set,
5733 <application>libpq
</application> applications will attempt
5734 authentication with servers for this realm and use separate ticket
5735 files to avoid conflicts with local ticket files. This
5736 environment variable is only used if Kerberos authentication is
5737 selected by the server.
5744 <primary><envar>PGOPTIONS
</envar></primary>
5746 <envar>PGOPTIONS
</envar> sets additional run-time options for the
5747 <productname>PostgreSQL
</productname> server. For example, setting
5748 <envar>PGOPTIONS
</envar> to
<literal>-c geqo=off<
/> sets the session's
5749 value of the
<varname>geqo<
/> parameter to
<literal>off<
/>.
5750 For a detailed discussion of the available options consult
<xref
5751 linkend=
"runtime-config">.
5758 <primary><envar>PGSSLMODE
</envar></primary>
5760 <envar>PGSSLMODE
</envar> determines whether and with what priority
5761 an
<acronym>SSL<
/> connection will be negotiated with the server.
5762 There are four modes:
<literal>disable<
/> will attempt only an
5763 unencrypted
<acronym>SSL<
/> connection;
<literal>allow<
/> will
5764 negotiate, trying first a non-
<acronym>SSL<
/> connection, then if
5765 that fails, trying an
<acronym>SSL<
/> connection;
<literal>prefer<
/>
5766 (the default) will negotiate, trying first an
<acronym>SSL<
/>
5767 connection, then if that fails, trying a regular non-
<acronym>SSL<
/>
5768 connection;
<literal>require<
/> will try only an
<acronym>SSL<
/>
5769 connection. If
<productname>PostgreSQL<
/> is compiled without SSL
5770 support, using option
<literal>require<
/> will cause an error, while
5771 options
<literal>allow<
/> and
<literal>prefer<
/> will be accepted
5772 but
<application>libpq<
/> will not in fact attempt an
<acronym>SSL<
/>
5780 <primary><envar>PGSSLVERIFY
</envar></primary>
5782 <envar>PGSSLVERIFY
</envar> controls how libpq verifies the certificate on the
5783 server when performing an
<acronym>SSL<
/> connection. There are
5784 three options:
<literal>none<
/> disables verification completely
5785 (not recommended!);
<literal>cert<
/> enables verification that
5786 the certificate chains to a known CA only;
<literal>cn<
/> will
5787 both verify that the certificate chains to a known CA and that
5788 the
<literal>cn<
/> attribute of the certificate matches the
5789 hostname the connection is being made to (default).
5796 <primary><envar>PGREQUIRESSL
</envar></primary>
5798 <envar>PGREQUIRESSL
</envar> sets whether or not the connection must
5799 be made over
<acronym>SSL
</acronym>. If set to
<quote>1</quote>,
5800 <application>libpq<
/> will refuse to connect if the server does not
5801 accept an
<acronym>SSL
</acronym> connection (equivalent to
5802 <literal>sslmode<
/> <literal>prefer<
/>). This option is deprecated
5803 in favor of the
<literal>sslmode<
/> setting, and is only available
5804 if
<productname>PostgreSQL<
/> is compiled with SSL support.
5811 <primary><envar>PGSSLCERT
</envar></primary>
5813 <envar>PGSSLCERT
</envar> specifies the location for the client
5814 certificate to use if the server requests one.
5821 <primary><envar>PGSSLKEY
</envar></primary>
5823 <envar>PGSSLKEY
</envar> specifies the location for the secret key
5824 used for the client certificate. It can either specify a filename
5825 that will be used instead of the default
5826 <filename>~/.postgresql/postgresql.key<
/>, or can specify an external
5827 engine (engines are
<productname>OpenSSL<
/> loadable modules). The
5828 external engine specification should consist of a colon-separated
5829 engine name and an engine-specific key identifier.
5836 <primary><envar>PGSSLROOTCERT
</envar></primary>
5838 <envar>PGSSLROOTCERT
</envar> specifies the file name where the SSL
5839 root certificate is stored.
5846 <primary><envar>PGSSLCRL
</envar></primary>
5848 <envar>PGSSLCRL
</envar> specifies the file name where the SSL certificate
5849 revocation list is stored.
5856 <primary><envar>PGKRBSRVNAME
</envar></primary>
5858 <envar>PGKRBSRVNAME
</envar> sets the Kerberos service name to use
5859 when authenticating with Kerberos
5 or GSSAPI.
5866 <primary><envar>PGGSSLIB
</envar></primary>
5868 <envar>PGGSSLIB
</envar> sets the GSS library to use for GSSAPI
5876 <primary><envar>PGCONNECT_TIMEOUT
</envar></primary>
5878 <envar>PGCONNECT_TIMEOUT
</envar> sets the maximum number of seconds
5879 that
<application>libpq
</application> will wait when attempting to
5880 connect to the
<productname>PostgreSQL
</productname> server. If
5881 unset or set to zero,
<application>libpq
</application> will wait
5882 indefinitely. It is not recommended to set the timeout to less than
5890 The following environment variables can be used to specify default
5891 behavior for each
<productname>PostgreSQL
</productname> session. (See
5892 also the
<xref linkend=
"sql-alteruser" endterm=
"sql-alteruser-title">
5893 and
<xref linkend=
"sql-alterdatabase" endterm=
"sql-alterdatabase-title">
5894 commands for ways to set default behavior on a per-user or per-database
5901 <primary><envar>PGDATESTYLE
</envar></primary>
5903 <envar>PGDATESTYLE
</envar> sets the default style of date/time
5904 representation. (Equivalent to
<literal>SET datestyle TO
5912 <primary><envar>PGTZ
</envar></primary>
5914 <envar>PGTZ
</envar> sets the default time zone. (Equivalent to
5915 <literal>SET timezone TO ...
</literal>.)
5922 <primary><envar>PGCLIENTENCODING
</envar></primary>
5924 <envar>PGCLIENTENCODING
</envar> sets the default client character
5925 set encoding. (Equivalent to
<literal>SET client_encoding TO
5933 <primary><envar>PGGEQO
</envar></primary>
5935 <envar>PGGEQO
</envar> sets the default mode for the genetic query
5936 optimizer. (Equivalent to
<literal>SET geqo TO ...
</literal>.)
5941 Refer to the
<acronym>SQL
</acronym> command
<xref linkend=
"sql-set"
5942 endterm=
"sql-set-title"> for information on correct values for these
5943 environment variables.
5947 The following environment variables determine internal behavior of
5948 <application>libpq
</application>; they override compiled-in defaults.
5954 <primary><envar>PGSYSCONFDIR
</envar></primary>
5956 <envar>PGSYSCONFDIR
</envar> sets the directory containing the
5957 <filename>pg_service.conf<
/> file.
5964 <primary><envar>PGLOCALEDIR
</envar></primary>
5966 <envar>PGLOCALEDIR
</envar> sets the directory containing the
5967 <literal>locale<
/> files for message internationalization.
5976 <sect1 id=
"libpq-pgpass">
5977 <title>The Password File
</title>
5979 <indexterm zone=
"libpq-pgpass">
5980 <primary>password file
</primary>
5982 <indexterm zone=
"libpq-pgpass">
5983 <primary>.pgpass
</primary>
5987 The file
<filename>.pgpass
</filename> in a user's home directory or the
5988 file referenced by
<envar>PGPASSFILE
</envar> can contain passwords to
5989 be used if the connection requires a password (and no password has been
5990 specified otherwise). On Microsoft Windows the file is named
5991 <filename>%APPDATA%\postgresql\pgpass.conf<
/> (where
5992 <filename>%APPDATA%<
/> refers to the Application Data subdirectory in
5993 the user's profile).
5997 This file should contain lines of the following format:
5999 <replaceable>hostname
</replaceable>:
<replaceable>port
</replaceable>:
<replaceable>database
</replaceable>:
<replaceable>username
</replaceable>:
<replaceable>password
</replaceable>
6001 Each of the first four fields can be a literal value, or
6002 <literal>*
</literal>, which matches anything. The password field from
6003 the first line that matches the current connection parameters will be
6004 used. (Therefore, put more-specific entries first when you are using
6005 wildcards.) If an entry needs to contain
<literal>:
</literal> or
6006 <literal>\
</literal>, escape this character with
<literal>\
</literal>.
6007 A host name of
<literal>localhost<
/> matches both TCP (host name
6008 <literal>localhost<
/>) and Unix domain socket (
<literal>pghost<
/> empty
6009 or the default socket directory) connections coming from the local
6014 On Unix systems, the permissions on
<filename>.pgpass
</filename> must
6015 disallow any access to world or group; achieve this by the command
6016 <command>chmod
0600 ~/.pgpass
</command>. If the permissions are less
6017 strict than this, the file will be ignored. On Microsoft Windows, it
6018 is assumed that the file is stored in a directory that is secure, so
6019 no special permissions check is made.
6024 <sect1 id=
"libpq-pgservice">
6025 <title>The Connection Service File
</title>
6027 <indexterm zone=
"libpq-pgservice">
6028 <primary>connection service file
</primary>
6030 <indexterm zone=
"libpq-pgservice">
6031 <primary>pg_service.conf
</primary>
6035 The connection service file allows libpq connection parameters to be
6036 associated with a single service name. That service name can then be
6037 specified by a libpq connection, and the associated settings will be
6038 used. This allows connection parameters to be modified without requiring
6039 a recompile of the libpq application. The service name can also be
6040 specified using the
<envar>PGSERVICE
</envar> environment variable.
6044 To use this feature, copy
6045 <filename>share/pg_service.conf.sample
</filename> to
6046 <filename>etc/pg_service.conf
</filename> and edit the file to add
6047 service names and parameters. This file can be used for client-only
6048 installs too. The file's location can also be specified by the
6049 <envar>PGSYSCONFDIR
</envar> environment variable.
6054 <sect1 id=
"libpq-ldap">
6055 <title>LDAP Lookup of Connection Parameters
</title>
6057 <indexterm zone=
"libpq-ldap">
6058 <primary>LDAP connection parameter lookup
</primary>
6062 If
<application>libpq
</application> has been compiled with LDAP support (option
6063 <literal><option>--with-ldap
</option></literal> for
<command>configure
</command>)
6064 it is possible to retrieve connection options like
<literal>host
</literal>
6065 or
<literal>dbname
</literal> via LDAP from a central server.
6066 The advantage is that if the connection parameters for a database change,
6067 the connection information doesn't have to be updated on all client machines.
6071 LDAP connection parameter lookup uses the connection service file
6072 <filename>pg_service.conf
</filename> (see
<xref
6073 linkend=
"libpq-pgservice">). A line in a
6074 <filename>pg_service.conf
</filename> stanza that starts with
6075 <literal>ldap://
</literal> will be recognized as an LDAP URL and an
6076 LDAP query will be performed. The result must be a list of
6077 <literal>keyword = value
</literal> pairs which will be used to set
6078 connection options. The URL must conform to RFC
1959 and be of the
6081 ldap://[
<replaceable>hostname
</replaceable>[:
<replaceable>port
</replaceable>]]/
<replaceable>search_base
</replaceable>?
<replaceable>attribute
</replaceable>?
<replaceable>search_scope
</replaceable>?
<replaceable>filter
</replaceable>
6083 where
<replaceable>hostname
</replaceable> defaults to
6084 <literal>localhost
</literal> and
<replaceable>port
</replaceable>
6089 Processing of
<filename>pg_service.conf
</filename> is terminated after
6090 a successful LDAP lookup, but is continued if the LDAP server cannot
6091 be contacted. This is to provide a fallback with further LDAP URL
6092 lines that point to different LDAP servers, classical
<literal>keyword
6093 = value
</literal> pairs, or default connection options. If you would
6094 rather get an error message in this case, add a syntactically incorrect
6095 line after the LDAP URL.
6099 A sample LDAP entry that has been created with the LDIF file
6102 dn:cn=mydatabase,dc=mycompany,dc=com
6105 objectclass:groupOfUniqueNames
6107 uniqueMember:host=dbserver.mycompany.com
6108 uniqueMember:port=
5439
6109 uniqueMember:dbname=mydb
6110 uniqueMember:user=mydb_user
6111 uniqueMember:sslmode=require
6113 might be queried with the following LDAP URL:
6115 ldap://ldap.mycompany.com/dc=mycompany,dc=com?uniqueMember?one?(cn=mydatabase)
6120 You can also mix regular service file entries with LDAP lookups.
6121 A complete example for a stanza in
<filename>pg_service.conf
</filename>
6124 # only host and port are stored in LDAP, specify dbname and user explicitly
6128 ldap://ldap.acme.com/cn=dbserver,cn=hosts?pgconnectinfo?base?(objectclass=*)
6135 <sect1 id=
"libpq-ssl">
6136 <title>SSL Support
</title>
6138 <indexterm zone=
"libpq-ssl">
6139 <primary>SSL
</primary>
6143 <productname>PostgreSQL<
/> has native support for using
<acronym>SSL<
/>
6144 connections to encrypt client/server communications for increased
6145 security. See
<xref linkend=
"ssl-tcp"> for details about the server-side
6146 <acronym>SSL<
/> functionality.
6150 <application>libpq
</application> reads the system-wide
6151 <productname>OpenSSL
</productname> configuration file. By default, this
6152 file is named
<filename>openssl.cnf
</filename> and is located in the
6153 directory reported by
<literal>openssl version -d<
/>. This default
6154 can be overridden by setting environment variable
6155 <envar>OPENSSL_CONF
</envar> to the name of the desired configuration
6160 When the
<literal>sslverify<
/> parameter is set to
<literal>cn<
/> or
6161 <literal>cert<
/>, libpq will verify that the server certificate is
6162 trustworthy by checking the certificate chain up to a
<acronym>CA<
/>.
6163 For this to work, place the certificate of a trusted
<acronym>CA<
/>
6164 in the file
<filename>~/.postgresql/root.crt<
/> in the user's home directory.
6165 (On Microsoft Windows the file is named
6166 <filename>%APPDATA%\postgresql\root.crt
</filename>.)
6167 <application>libpq
</application> will then verify that the server's
6168 certificate is signed by one of the trusted certificate authorities.
6169 The SSL connection will fail if the server does not present a trusted
6170 certificate. Certificate Revocation List (CRL) entries are also checked
6171 if the file
<filename>~/.postgresql/root.crl
</filename> exists
6172 (
<filename>%APPDATA%\postgresql\root.crl
</filename> on Microsoft
6174 The location of the root certificate store and the CRL can be overridden
6175 by the connection parameters
<literal>sslrootcert<
/> and
<literal>sslcrl<
/>
6176 or the environment variables
<envar>PGSSLROOTCERT<
/> and
<envar>PGSSLCRL<
/>.
6180 If the server requests a trusted client certificate,
6181 <application>libpq
</application> will send the certificate stored in
6182 file
<filename>~/.postgresql/postgresql.crt<
/> in the user's home
6183 directory. The certificate must be signed by one of the certificate
6184 authorities (
<acronym>CA
</acronym>) trusted by the server. A matching
6185 private key file
<filename>~/.postgresql/postgresql.key<
/> must also
6186 be present. The private
6187 key file must not allow any access to world or group; achieve this by the
6188 command
<command>chmod
0600 ~/.postgresql/postgresql.key
</command>.
6189 On Microsoft Windows these files are named
6190 <filename>%APPDATA%\postgresql\postgresql.crt
</filename> and
6191 <filename>%APPDATA%\postgresql\postgresql.key
</filename>, and there
6192 is no special permissions check since the directory is presumed secure.
6193 The location of the certificate and key files can be overridden by the
6194 connection parameters
<literal>sslcert<
/> and
<literal>sslkey<
/> or the
6195 environment variables
<envar>PGSSLCERT<
/> and
<envar>PGSSLKEY<
/>.
6199 If you are using
<acronym>SSL<
/> inside your application (in addition
6200 to inside
<application>libpq
</application>), you can use
6201 <function>PQinitSSL(int)<
/> to tell
<application>libpq
</application>
6202 that the
<acronym>SSL<
/> library has already been initialized by your
6204 <!-- If this URL changes replace it with a URL to www.archive.org. -->
6206 url=
"http://h71000.www7.hp.com/doc/83final/BA554_90007/ch04.html"></ulink>
6207 for details on the SSL API.
6210 <table id=
"libpq-ssl-file-usage">
6211 <title>Libpq/Client SSL File Usage
</title>
6216 <entry>Contents
</entry>
6217 <entry>Effect
</entry>
6224 <entry><filename>~/.postgresql/postgresql.crt<
/></entry>
6225 <entry>client certificate
</entry>
6226 <entry>requested by server
</entry>
6230 <entry><filename>~/.postgresql/postgresql.key<
/></entry>
6231 <entry>client private key
</entry>
6232 <entry>proves client certificate sent by owner; does not indicate
6233 certificate owner is trustworthy
</entry>
6237 <entry><filename>~/.postgresql/root.crt<
/></entry>
6238 <entry>trusted certificate authorities
</entry>
6239 <entry>checks server certificate is signed by a trusted certificate
6244 <entry><filename>~/.postgresql/root.crl<
/></entry>
6245 <entry>certificates revoked by certificate authorities
</entry>
6246 <entry>server certificate must not be on this list
</entry>
6256 <sect1 id=
"libpq-threading">
6257 <title>Behavior in Threaded Programs
</title>
6259 <indexterm zone=
"libpq-threading">
6260 <primary>threads
</primary>
6261 <secondary>with libpq
</secondary>
6265 <application>libpq
</application> is reentrant and thread-safe if the
6266 <filename>configure
</filename> command-line option
6267 <literal>--enable-thread-safety<
/> was used when the
6268 <productname>PostgreSQL
</productname> distribution was built. In
6269 addition, you might need to use additional compiler command-line
6270 options when you compile your application code. Refer to your
6271 system's documentation for information about how to build
6272 thread-enabled applications, or look in
6273 <filename>src/Makefile.global
</filename> for
<literal>PTHREAD_CFLAGS<
/>
6274 and
<literal>PTHREAD_LIBS<
/>. This function allows the querying of
6275 <application>libpq
</application>'s thread-safe status:
6281 <function>PQisthreadsafe
</function>
6283 <primary>PQisthreadsafe
</primary>
6289 Returns the thread safety status of the
6290 <application>libpq
</application> library.
6292 int PQisthreadsafe();
6297 Returns
1 if the
<application>libpq
</application> is thread-safe
6305 One thread restriction is that no two threads attempt to manipulate
6306 the same
<structname>PGconn<
/> object at the same time. In particular,
6307 you cannot issue concurrent commands from different threads through
6308 the same connection object. (If you need to run concurrent commands,
6309 use multiple connections.)
6313 <structname>PGresult<
/> objects are read-only after creation, and so
6314 can be passed around freely between threads.
6318 The deprecated functions
<function>PQrequestCancel
</function> and
6319 <function>PQoidStatus
</function> are not thread-safe and should not be
6320 used in multithread programs.
<function>PQrequestCancel
</function>
6321 can be replaced by
<function>PQcancel
</function>.
6322 <function>PQoidStatus
</function> can be replaced by
6323 <function>PQoidValue
</function>.
6327 If you are using Kerberos inside your application (in addition to inside
6328 <application>libpq
</application>), you will need to do locking around
6329 Kerberos calls because Kerberos functions are not thread-safe. See
6330 function
<function>PQregisterThreadLock<
/> in the
6331 <application>libpq
</application> source code for a way to do cooperative
6332 locking between
<application>libpq
</application> and your application.
6336 If you experience problems with threaded applications, run the program
6337 in
<filename>src/tools/thread<
/> to see if your platform has
6338 thread-unsafe functions. This program is run by
6339 <filename>configure
</filename>, but for binary distributions your
6340 library might not match the library used to build the binaries.
6345 <sect1 id=
"libpq-build">
6346 <title>Building
<application>libpq
</application> Programs
</title>
6348 <indexterm zone=
"libpq-build">
6349 <primary>compiling
</primary>
6350 <secondary>libpq applications
</secondary>
6354 To build (i.e., compile and link) a program using
6355 <application>libpq
</application> you need to do all of the following
6361 Include the
<filename>libpq-fe.h
</filename> header file:
6363 #include
<libpq-fe.h
>
6365 If you failed to do that then you will normally get error messages
6366 from your compiler similar to
6368 foo.c: In function `main':
6369 foo.c:
34: `PGconn' undeclared (first use in this function)
6370 foo.c:
35: `PGresult' undeclared (first use in this function)
6371 foo.c:
54: `CONNECTION_BAD' undeclared (first use in this function)
6372 foo.c:
68: `PGRES_COMMAND_OK' undeclared (first use in this function)
6373 foo.c:
95: `PGRES_TUPLES_OK' undeclared (first use in this function)
6380 Point your compiler to the directory where the
<productname>PostgreSQL<
/> header
6381 files were installed, by supplying the
6382 <literal>-I
<replaceable>directory
</replaceable></literal> option
6383 to your compiler. (In some cases the compiler will look into
6384 the directory in question by default, so you can omit this
6385 option.) For instance, your compile command line could look
6388 cc -c -I/usr/local/pgsql/include testprog.c
6390 If you are using makefiles then add the option to the
6391 <varname>CPPFLAGS
</varname> variable:
6393 CPPFLAGS += -I/usr/local/pgsql/include
6398 If there is any chance that your program might be compiled by
6399 other users then you should not hardcode the directory location
6400 like that. Instead, you can run the utility
6401 <command>pg_config
</command><indexterm><primary>pg_config<
/><secondary
6402 sortas=
"libpq">with libpq<
/><
/> to find out where the header
6403 files are on the local system:
6405 <prompt>$
</prompt> pg_config --includedir
6406 <computeroutput>/usr/local/include
</computeroutput>
6411 Failure to specify the correct option to the compiler will
6412 result in an error message such as
6414 testlibpq.c:
8:
22: libpq-fe.h: No such file or directory
6421 When linking the final program, specify the option
6422 <literal>-lpq
</literal> so that the
<application>libpq
</application>
6423 library gets pulled in, as well as the option
6424 <literal>-L
<replaceable>directory
</replaceable></literal> to point
6425 the compiler to the directory where the
6426 <application>libpq
</application> library resides. (Again, the
6427 compiler will search some directories by default.) For maximum
6428 portability, put the
<option>-L
</option> option before the
6429 <option>-lpq
</option> option. For example:
6431 cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq
6436 You can find out the library directory using
6437 <command>pg_config
</command> as well:
6439 <prompt>$
</prompt> pg_config --libdir
6440 <computeroutput>/usr/local/pgsql/lib
</computeroutput>
6445 Error messages that point to problems in this area could look like
6448 testlibpq.o: In function `main':
6449 testlibpq.o(.text+
0x60): undefined reference to `PQsetdbLogin'
6450 testlibpq.o(.text+
0x71): undefined reference to `PQstatus'
6451 testlibpq.o(.text+
0xa4): undefined reference to `PQerrorMessage'
6453 This means you forgot
<option>-lpq
</option>.
6455 /usr/bin/ld: cannot find -lpq
6457 This means you forgot the
<option>-L
</option> option or did not
6458 specify the right directory.
6467 <sect1 id=
"libpq-example">
6468 <title>Example Programs
</title>
6471 These examples and others can be found in the
6472 directory
<filename>src/test/examples
</filename> in the source code
6476 <example id=
"libpq-example-1">
6477 <title><application>libpq
</application> Example Program
1</title>
6484 * Test the C version of libpq, the PostgreSQL frontend library.
6488 #include
"libpq-fe.h"
6491 exit_nicely(PGconn *conn)
6498 main(int argc, char **argv)
6500 const char *conninfo;
6508 * If the user supplies a parameter on the command line, use it as the
6509 * conninfo string; otherwise default to setting dbname=postgres and using
6510 * environment variables or defaults for all other connection parameters.
6515 conninfo =
"dbname = postgres";
6517 /* Make a connection to the database */
6518 conn = PQconnectdb(conninfo);
6520 /* Check to see that the backend connection was successfully made */
6521 if (PQstatus(conn) != CONNECTION_OK)
6523 fprintf(stderr,
"Connection to database failed: %s",
6524 PQerrorMessage(conn));
6529 * Our test case here involves using a cursor, for which we must be inside
6530 * a transaction block. We could do the whole thing with a single
6531 * PQexec() of
"select * from pg_database", but that's too trivial to make
6535 /* Start a transaction block */
6536 res = PQexec(conn,
"BEGIN");
6537 if (PQresultStatus(res) != PGRES_COMMAND_OK)
6539 fprintf(stderr,
"BEGIN command failed: %s", PQerrorMessage(conn));
6545 * Should PQclear PGresult whenever it is no longer needed to avoid memory
6551 * Fetch rows from pg_database, the system catalog of databases
6553 res = PQexec(conn,
"DECLARE myportal CURSOR FOR select * from pg_database");
6554 if (PQresultStatus(res) != PGRES_COMMAND_OK)
6556 fprintf(stderr,
"DECLARE CURSOR failed: %s", PQerrorMessage(conn));
6562 res = PQexec(conn,
"FETCH ALL in myportal");
6563 if (PQresultStatus(res) != PGRES_TUPLES_OK)
6565 fprintf(stderr,
"FETCH ALL failed: %s", PQerrorMessage(conn));
6570 /* first, print out the attribute names */
6571 nFields = PQnfields(res);
6572 for (i =
0; i < nFields; i++)
6573 printf(
"%-15s", PQfname(res, i));
6576 /* next, print out the rows */
6577 for (i =
0; i < PQntuples(res); i++)
6579 for (j =
0; j < nFields; j++)
6580 printf(
"%-15s", PQgetvalue(res, i, j));
6586 /* close the portal ... we don't bother to check for errors ... */
6587 res = PQexec(conn,
"CLOSE myportal");
6590 /* end the transaction */
6591 res = PQexec(conn,
"END");
6594 /* close the connection to the database and cleanup */
6603 <example id=
"libpq-example-2">
6604 <title><application>libpq
</application> Example Program
2</title>
6610 * Test of the asynchronous notification interface
6612 * Start this program, then from psql in another window do
6614 * Repeat four times to get this program to exit.
6616 * Or, if you want to get fancy, try this:
6617 * populate a database with the following commands
6618 * (provided in src/test/examples/testlibpq2.sql):
6620 * CREATE TABLE TBL1 (i int4);
6622 * CREATE TABLE TBL2 (i int4);
6624 * CREATE RULE r1 AS ON INSERT TO TBL1 DO
6625 * (INSERT INTO TBL2 VALUES (new.i); NOTIFY TBL2);
6627 * and do this four times:
6629 * INSERT INTO TBL1 VALUES (
10);
6635 #include
<sys/time.h
>
6636 #include
"libpq-fe.h"
6639 exit_nicely(PGconn *conn)
6646 main(int argc, char **argv)
6648 const char *conninfo;
6655 * If the user supplies a parameter on the command line, use it as the
6656 * conninfo string; otherwise default to setting dbname=postgres and using
6657 * environment variables or defaults for all other connection parameters.
6662 conninfo =
"dbname = postgres";
6664 /* Make a connection to the database */
6665 conn = PQconnectdb(conninfo);
6667 /* Check to see that the backend connection was successfully made */
6668 if (PQstatus(conn) != CONNECTION_OK)
6670 fprintf(stderr,
"Connection to database failed: %s",
6671 PQerrorMessage(conn));
6676 * Issue LISTEN command to enable notifications from the rule's NOTIFY.
6678 res = PQexec(conn,
"LISTEN TBL2");
6679 if (PQresultStatus(res) != PGRES_COMMAND_OK)
6681 fprintf(stderr,
"LISTEN command failed: %s", PQerrorMessage(conn));
6687 * should PQclear PGresult whenever it is no longer needed to avoid memory
6692 /* Quit after four notifies are received. */
6694 while (nnotifies <
4)
6697 * Sleep until something happens on the connection. We use select(
2)
6698 * to wait for input, but you could also use poll() or similar
6704 sock = PQsocket(conn);
6707 break; /* shouldn't happen */
6709 FD_ZERO(&input_mask);
6710 FD_SET(sock, &input_mask);
6712 if (select(sock +
1, &input_mask, NULL, NULL, NULL) <
0)
6714 fprintf(stderr,
"select() failed: %s\n", strerror(errno));
6718 /* Now check for input */
6719 PQconsumeInput(conn);
6720 while ((notify = PQnotifies(conn)) != NULL)
6723 "ASYNC NOTIFY of '%s' received from backend pid %d\n",
6724 notify-
>relname, notify-
>be_pid);
6730 fprintf(stderr,
"Done.\n");
6732 /* close the connection to the database and cleanup */
6741 <example id=
"libpq-example-3">
6742 <title><application>libpq
</application> Example Program
3<
/>
6748 * Test out-of-line parameters and binary I/O.
6750 * Before running this, populate a database with the following commands
6751 * (provided in src/test/examples/testlibpq3.sql):
6753 * CREATE TABLE test1 (i int4, t text, b bytea);
6755 * INSERT INTO test1 values (
1, 'joe''s place', '\\
000\\
001\\
002\\
003\\
004');
6756 * INSERT INTO test1 values (
2, 'ho there', '\\
004\\
003\\
002\\
001\\
000');
6758 * The expected output is:
6762 * t = (
11 bytes) 'joe's place'
6763 * b = (
5 bytes) \
000\
001\
002\
003\
004
6767 * t = (
8 bytes) 'ho there'
6768 * b = (
5 bytes) \
004\
003\
002\
001\
000
6773 #include
<sys/types.h
>
6774 #include
"libpq-fe.h"
6776 /* for ntohl/htonl */
6777 #include
<netinet/in.h
>
6778 #include
<arpa/inet.h
>
6782 exit_nicely(PGconn *conn)
6789 * This function prints a query result that is a binary-format fetch from
6790 * a table defined as in the comment above. We split it out because the
6791 * main() function uses it twice.
6794 show_binary_results(PGresult *res)
6802 /* Use PQfnumber to avoid assumptions about field order in result */
6803 i_fnum = PQfnumber(res,
"i");
6804 t_fnum = PQfnumber(res,
"t");
6805 b_fnum = PQfnumber(res,
"b");
6807 for (i =
0; i < PQntuples(res); i++)
6815 /* Get the field values (we ignore possibility they are null!) */
6816 iptr = PQgetvalue(res, i, i_fnum);
6817 tptr = PQgetvalue(res, i, t_fnum);
6818 bptr = PQgetvalue(res, i, b_fnum);
6821 * The binary representation of INT4 is in network byte order, which
6822 * we'd better coerce to the local byte order.
6824 ival = ntohl(*((uint32_t *) iptr));
6827 * The binary representation of TEXT is, well, text, and since libpq
6828 * was nice enough to append a zero byte to it, it'll work just fine
6831 * The binary representation of BYTEA is a bunch of bytes, which could
6832 * include embedded nulls so we have to pay attention to field length.
6834 blen = PQgetlength(res, i, b_fnum);
6836 printf(
"tuple %d: got\n", i);
6837 printf(
" i = (%d bytes) %d\n",
6838 PQgetlength(res, i, i_fnum), ival);
6839 printf(
" t = (%d bytes) '%s'\n",
6840 PQgetlength(res, i, t_fnum), tptr);
6841 printf(
" b = (%d bytes) ", blen);
6842 for (j =
0; j < blen; j++)
6843 printf(
"\\%03o", bptr[j]);
6849 main(int argc, char **argv)
6851 const char *conninfo;
6854 const char *paramValues[
1];
6855 int paramLengths[
1];
6856 int paramFormats[
1];
6857 uint32_t binaryIntVal;
6860 * If the user supplies a parameter on the command line, use it as the
6861 * conninfo string; otherwise default to setting dbname=postgres and using
6862 * environment variables or defaults for all other connection parameters.
6867 conninfo =
"dbname = postgres";
6869 /* Make a connection to the database */
6870 conn = PQconnectdb(conninfo);
6872 /* Check to see that the backend connection was successfully made */
6873 if (PQstatus(conn) != CONNECTION_OK)
6875 fprintf(stderr,
"Connection to database failed: %s",
6876 PQerrorMessage(conn));
6881 * The point of this program is to illustrate use of PQexecParams() with
6882 * out-of-line parameters, as well as binary transmission of data.
6884 * This first example transmits the parameters as text, but receives the
6885 * results in binary format. By using out-of-line parameters we can
6886 * avoid a lot of tedious mucking about with quoting and escaping, even
6887 * though the data is text. Notice how we don't have to do anything
6888 * special with the quote mark in the parameter value.
6891 /* Here is our out-of-line parameter value */
6892 paramValues[
0] =
"joe's place";
6894 res = PQexecParams(conn,
6895 "SELECT * FROM test1 WHERE t = $1",
6897 NULL, /* let the backend deduce param type */
6899 NULL, /* don't need param lengths since text */
6900 NULL, /* default to all text params */
6901 1); /* ask for binary results */
6903 if (PQresultStatus(res) != PGRES_TUPLES_OK)
6905 fprintf(stderr,
"SELECT failed: %s", PQerrorMessage(conn));
6910 show_binary_results(res);
6915 * In this second example we transmit an integer parameter in binary
6916 * form, and again retrieve the results in binary form.
6918 * Although we tell PQexecParams we are letting the backend deduce
6919 * parameter type, we really force the decision by casting the parameter
6920 * symbol in the query text. This is a good safety measure when sending
6921 * binary parameters.
6924 /* Convert integer value
"2" to network byte order */
6925 binaryIntVal = htonl((uint32_t)
2);
6927 /* Set up parameter arrays for PQexecParams */
6928 paramValues[
0] = (char *)
&binaryIntVal;
6929 paramLengths[
0] = sizeof(binaryIntVal);
6930 paramFormats[
0] =
1; /* binary */
6932 res = PQexecParams(conn,
6933 "SELECT * FROM test1 WHERE i = $1::int4",
6935 NULL, /* let the backend deduce param type */
6939 1); /* ask for binary results */
6941 if (PQresultStatus(res) != PGRES_TUPLES_OK)
6943 fprintf(stderr,
"SELECT failed: %s", PQerrorMessage(conn));
6948 show_binary_results(res);
6952 /* close the connection to the database and cleanup */