+ linkend="libpq-pgservice">). A line in a
+ pg_service.conf stanza that starts with
+ ldap:// will be recognized as an LDAP URL and an
+ LDAP query will be performed. The result must be a list of
+ keyword = value pairs which will be used to set
+ connection options. The URL must conform to RFC 1959 and be of the
+ form
+
+ ldap://[hostname[:port]]/search_base?attribute?search_scope?filter
+
+ where hostname defaults to
+ localhost and port
+ defaults to 389.
-
-
-
-
-
+
- Frees memory allocated by
libpq>.
-
-void PQfreemem(void *ptr);
-
-
-
- Frees memory allocated by
libpq>, particularly
- PQescapeByteaConn,
- PQescapeBytea,
- PQunescapeBytea,
- and PQnotifies.
- It is particularly important that this function, rather than
- free()>, be used on Microsoft Windows. This is because
- allocating memory in a DLL and releasing it in the application works
- only if multithreaded/single-threaded, release/debug, and static/dynamic
- flags are the same for the DLL and the application. On non-Microsoft
- Windows platforms, this function is the same as the standard library
- function free()>.
+ Processing of pg_service.conf is terminated after
+ a successful LDAP lookup, but is continued if the LDAP server cannot
+ be contacted. This is to provide a fallback with further LDAP URL
+ lines that point to different LDAP servers, classical keyword
+ = value pairs, or default connection options. If you would
+ rather get an error message in this case, add a syntactically incorrect
+ line after the LDAP URL.
-
-
-
-
-
-
-
-
Asynchronous Command Processing
-
-
-
-
-The PQexec function is adequate for submitting commands in
-normal, synchronous
-applications. It has a couple of deficiencies, however, that can be of importance to some users:
-
-
-
-PQexec waits for the command to be completed. The application might have other
-work to do (such as maintaining a user interface), in which case it won't
-want to block waiting for the response.
-
-
-
-Since the execution of the client application is suspended while it
-waits for the result, it is hard for the application to decide that it
-would like to try to cancel the ongoing command. (It can be done from
-a signal handler, but not otherwise.)
-
-
-
-PQexec can return only one PGresult structure. If the submitted command
-string contains multiple
SQL commands, all but the last
PGresult are
-discarded by PQexec.
-
-
-
-
-
-Applications that do not like these limitations can instead use the
-underlying functions that PQexec is built from:
-PQsendQuery and PQgetResult.
-There are also
-PQsendQueryParams,
-PQsendPrepare,
-PQsendQueryPrepared,
-PQsendDescribePrepared, and
-PQsendDescribePortal,
-which can be used with PQgetResult to duplicate the
-functionality of
-PQexecParams,
-PQprepare,
-PQexecPrepared,
-PQdescribePrepared, and
-PQdescribePortal
-respectively.
-
-
-
-
PQsendQueryPQsendQuery>>
-
- Submits a command to the server without
- waiting for the result(s). 1 is returned if the command was
- successfully dispatched and 0 if not (in which case, use
- PQerrorMessage> to get more information about the failure).
-
-int PQsendQuery(PGconn *conn, const char *command);
-
-
- After successfully calling PQsendQuery, call
- PQgetResult one or more
- times to obtain the results. PQsendQuery cannot be called
- again (on the same connection) until PQgetResult has returned a null pointer,
- indicating that the command is done.
-
-
-
-
-
-
PQsendQueryParamsPQsendQueryParams>>
-
- Submits a command and separate parameters to the server without
- waiting for the result(s).
-
-int PQsendQueryParams(PGconn *conn,
- const char *command,
- int nParams,
- const Oid *paramTypes,
- const char * const *paramValues,
- const int *paramLengths,
- const int *paramFormats,
- int resultFormat);
-
-
- This is equivalent to PQsendQuery except that
- query parameters can be specified separately from the query string.
- The function's parameters are handled identically to
- PQexecParams. Like
- PQexecParams, it will not work on 2.0-protocol
- connections, and it allows only one command in the query string.
-
-
-
-
-
-
PQsendPrepare>PQsendPrepare>>
-
- Sends a request to create a prepared statement with the given
- parameters, without waiting for completion.
-
-int PQsendPrepare(PGconn *conn,
- const char *stmtName,
- const char *query,
- int nParams,
- const Oid *paramTypes);
-
-
- This is an asynchronous version of PQprepare>: it
- returns 1 if it was able to dispatch the request, and 0 if not.
- After a successful call, call PQgetResult
- to determine whether the server successfully created the prepared
- statement.
- The function's parameters are handled identically to
- PQprepare. Like
- PQprepare, it will not work on 2.0-protocol
- connections.
-
-
-
-
-
-
PQsendQueryPreparedPQsendQueryPrepared>>
-
- Sends a request to execute a prepared statement with given
- parameters, without waiting for the result(s).
-
-int PQsendQueryPrepared(PGconn *conn,
- const char *stmtName,
- int nParams,
- const char * const *paramValues,
- const int *paramLengths,
- const int *paramFormats,
- int resultFormat);
-
-
- This is similar to PQsendQueryParams, but the
- command to be executed is specified by naming a previously-prepared
- statement, instead of giving a query string.
- The function's parameters are handled identically to
- PQexecPrepared. Like
- PQexecPrepared, it will not work on 2.0-protocol
- connections.
-
-
-
-
-
-
PQsendDescribePrepared>PQsendDescribePrepared>>
-
- Submits a request to obtain information about the specified
- prepared statement, without waiting for completion.
-
-int PQsendDescribePrepared(PGconn *conn, const char *stmtName);
-
-
- This is an asynchronous version of PQdescribePrepared>: it
- returns 1 if it was able to dispatch the request, and 0 if not.
- After a successful call, call PQgetResult
- to obtain the results.
- The function's parameters are handled identically to
- PQdescribePrepared. Like
- PQdescribePrepared, it will not work on 2.0-protocol
- connections.
-
-
-
-
-
-
PQsendDescribePortal>PQsendDescribePortal>>
-
- Submits a request to obtain information about the specified
- portal, without waiting for completion.
-
-int PQsendDescribePortal(PGconn *conn, const char *portalName);
-
-
- This is an asynchronous version of PQdescribePortal>: it
- returns 1 if it was able to dispatch the request, and 0 if not.
- After a successful call, call PQgetResult
- to obtain the results.
- The function's parameters are handled identically to
- PQdescribePortal. Like
- PQdescribePortal, it will not work on 2.0-protocol
- connections.
-
-
-
-
-
-
PQgetResultPQgetResult>>
-
- Waits for the next result from a prior
- PQsendQuery,
- PQsendQueryParams,
- PQsendPrepare, or
- PQsendQueryPrepared call,
- and returns it. A null pointer is returned when the command is complete
- and there will be no more results.
-
-PGresult *PQgetResult(PGconn *conn);
-
-
-
- PQgetResult must be called repeatedly until it returns a null pointer,
- indicating that the command is done. (If called when no command is
- active, PQgetResult will just return a null pointer at once.)
- Each non-null result from PQgetResult should be processed using
- the same PGresult> accessor functions previously described.
- Don't forget to free each result object with PQclear when done with it.
- Note that PQgetResult will block only if a command is active and the
- necessary response data has not yet been read by PQconsumeInput.
-
-
-
-
-
-
-Using PQsendQuery and PQgetResult
-solves one of PQexec's problems:
-If a command string contains multiple
SQL commands, the results of those
-commands can be obtained individually. (This allows a simple form of
-overlapped processing, by the way: the client can be handling the
-results of one command while the server is still working on later
-queries in the same command string.) However, calling PQgetResult will
-still cause the client to block until the server completes the
-next
SQL command. This can be avoided by proper use of two
-more functions:
-
-
-
-
PQconsumeInputPQconsumeInput>>
-
- If input is available from the server, consume it.
-
-int PQconsumeInput(PGconn *conn);
-
-
-
-PQconsumeInput normally returns 1 indicating no error
,
-but returns 0 if there was some kind of trouble (in which case
-PQerrorMessage can be consulted). Note that the result
-does not say
-whether any input data was actually collected. After calling
-PQconsumeInput, the application can check
-PQisBusy and/or PQnotifies to see if
-their state has changed.
-
-PQconsumeInput can be called even if the application is not
-prepared to deal with a result or notification just yet. The
-function will read available data and save it in a buffer, thereby
-causing a select() read-ready indication to go away. The
-application can thus use PQconsumeInput to clear the
-select() condition immediately, and then examine the results at leisure.
-
-
-
-
-
-
-Returns 1 if a command is busy, that is, PQgetResult would block
-waiting for input. A 0 return indicates that PQgetResult can
-be called with assurance of not blocking.
-
-int PQisBusy(PGconn *conn);
-
-
-
-PQisBusy will not itself attempt to read data from the server;
-therefore PQconsumeInput must be invoked first, or the busy
-state will never end.
-
-
-
-
-
-
-A typical application using these functions will have a main loop that uses
-select() or poll()> to wait for all the
-conditions that it must
-respond to. One of the conditions will be input available from the server,
-which in terms of select() means readable data on the file
-descriptor identified by PQsocket.
-When the main loop detects input ready, it should call
-PQconsumeInput to read the input. It can then call
-PQisBusy, followed by PQgetResult
-if PQisBusy returns false (0). It can also call
-PQnotifies to detect NOTIFY> messages (see ).
-
-
-A client that uses
-PQsendQuery/PQgetResult can
-also attempt to cancel a command that is still being processed by the
-server; see . But regardless of the return value
-of PQcancel, the application must continue with the
-normal result-reading sequence using PQgetResult.
-A successful cancellation will simply cause the command to terminate
-sooner than it would have otherwise.
-
-
-By using the functions described above, it is possible to avoid blocking
-while waiting for input from the database server. However, it is still
-possible that the application will block waiting to send output to the
-server. This is relatively uncommon but can happen if very long SQL commands
-or data values are sent. (It is much more probable if the application
-sends data via COPY IN, however.) To prevent this possibility and achieve
-completely nonblocking database operation, the following additional
-functions can be used.
-
-
-
-
PQsetnonblockingPQsetnonblocking>>
-
- Sets the nonblocking status of the connection.
-
-int PQsetnonblocking(PGconn *conn, int arg);
-
-
-
- Sets the state of the connection to nonblocking if
- blocking if
arg is 0. Returns 0 if OK, -1 if error.
-
- In the nonblocking state, calls to
- PQsendQuery,
- PQputline, PQputnbytes,
- and PQendcopy
- will not block but instead return an error if they need to be called
- again.
-
- Note that PQexec does not honor nonblocking mode;
- if it is called, it will act in blocking fashion anyway.
-
-
-
-
-
-
PQisnonblockingPQisnonblocking>>
-
- Returns the blocking status of the database connection.
-
-int PQisnonblocking(const PGconn *conn);
-
-
-
- Returns 1 if the connection is set to nonblocking mode and
- 0 if blocking.
-
-
-
-
-
-
-Attempts to flush any queued output data to the server.
-Returns 0 if successful (or if the send queue is empty), -1 if it failed for
-some reason, or 1 if it was unable to send all the data in the send queue yet
-(this case can only occur if the connection is nonblocking).
-
-int PQflush(PGconn *conn);
-
-
-
-
-
-
-
-After sending any command or data on a nonblocking connection, call
-PQflush. If it returns 1, wait for the socket to be
-write-ready and call it again; repeat until it returns 0. Once
-PQflush returns 0, wait for the socket to be read-ready
-and then read the response as described above.
-
-
-
-
-
-
Cancelling Queries in Progress
-
-
- SQL command
-
-
-A client application can request cancellation of
-a command that is still being processed by the
-server, using the functions described in this section.
-
-
-
-
PQgetCancelPQgetCancel>>
-
- Creates a data structure containing the information needed to cancel
- a command issued through a particular database connection.
-
-PGcancel *PQgetCancel(PGconn *conn);
-
-
-
-PQgetCancel creates a
-
PGcancel>PGcancel>> object given
-a PGconn> connection object. It will return NULL if the
-given
conn> is NULL or an invalid connection. The
-PGcancel> object is an opaque structure that is not meant
-to be accessed directly by the application; it can only be passed to
-PQcancel or PQfreeCancel.
-
-
-
-
-
-
PQfreeCancelPQfreeCancel>>
-
- Frees a data structure created by PQgetCancel.
-
-void PQfreeCancel(PGcancel *cancel);
-
-
-
-PQfreeCancel frees a data object previously created
-by PQgetCancel.
-
-
-
-
-
-
- Requests that the server abandon
- processing of the current command.
-
-int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize);
-
-
-
-The return value is 1 if the cancel request was successfully
-dispatched and 0 if not. If not,
errbuf> is filled with an error
-message explaining why not.
errbuf> must be a char array of size
-
errbufsize> (the recommended size is 256 bytes).
-
-
-Successful dispatch is no guarantee that the request will have any effect,
-however. If the cancellation is effective, the current command will terminate
-early and return an error result. If the cancellation fails (say, because the
-server was already done processing the command), then there will be no visible
-result at all.
-
-
-PQcancel can safely be invoked from a signal handler,
-if the
errbuf> is a local variable in the signal handler. The
-PGcancel> object is read-only as far as
-PQcancel is concerned, so it can also be invoked from a
-thread that is separate from the one manipulating the PGconn>
-object.
-
-
-
-
-
-
-
-
PQrequestCancelPQrequestCancel>>
-
- Requests that the server abandon
- processing of the current command.
-
-int PQrequestCancel(PGconn *conn);
-
-
-
-PQrequestCancel is a deprecated variant of
-PQcancel. It operates directly on the
-PGconn> object, and in case of failure stores the
-error message in the PGconn> object (whence it can be
-retrieved by PQerrorMessage). Although the
-functionality is the same, this approach creates hazards for multiple-thread
-programs and signal handlers, since it is possible that overwriting the
-PGconn>'s error message will mess up the operation currently
-in progress on the connection.
-
-
-
-
-
-
-
-
-
-
The Fast-Path Interface
-
-
-
-
-
PostgreSQL provides a fast-path interface to send
-simple function calls to the server.
-
-
-
-This interface is somewhat obsolete, as one can achieve similar performance
-and greater functionality by setting up a prepared statement to define the
-function call. Then, executing the statement with binary transmission of
-parameters and results substitutes for a fast-path function call.
-
-
-
-requests execution of a server function via the fast-path interface:
-
-PGresult *PQfn(PGconn *conn,
- int fnid,
- int *result_buf,
- int *result_len,
- int result_is_int,
- const PQArgBlock *args,
- int nargs);
-
-typedef struct {
- int len;
- int isint;
- union {
- int *ptr;
- int integer;
- } u;
-} PQArgBlock;
-
-
-
- The
fnid> argument is the OID of the function to be
- executed.
args> and nargs> define the
- parameters to be passed to the function; they must match the declared
- function argument list. When the
isint> field of a
- parameter
- structure is true,
- the
u.integer> value is sent to the server as an integer
- of the indicated length (this must be 1, 2, or 4 bytes); proper
- byte-swapping occurs. When
isint> is false, the
- indicated number of bytes at
*u.ptr> are sent with no
- processing; the data must be in the format expected by the server for
- binary transmission of the function's argument data type.
-
result_buf is the buffer in which
- to place the return value. The caller must have allocated
- sufficient space to store the return value. (There is no check!)
- The actual result length will be returned in the integer pointed
- If a 1, 2, or 4-byte integer result is expected, set
-
result_is_int to 1, otherwise set it to 0.
- Setting
result_is_int to 1
- causes
libpq> to byte-swap the value if necessary, so that
- it is
- delivered as a proper int value for the client machine. When
-
result_is_int> is 0, the binary-format byte string sent by
- the server is returned unmodified.
-
-
-PQfn always returns a valid PGresult pointer. The result status
-should be checked before the result is used. The
-caller is responsible for freeing the PGresult with
-PQclear when it is no longer needed.
-
-
-Note that it is not possible to handle null arguments, null results, nor
-set-valued results when using this interface.
-
-
-
-
-
-
Asynchronous Notification
-
-
- in libpq
+ A sample LDAP entry that has been created with the LDIF file
+
+ version:1
+ dn:cn=mydatabase,dc=mycompany,dc=com
+ changetype:add
+ objectclass:top
+ objectclass:groupOfUniqueNames
+ cn:mydatabase
+ uniqueMember:host=dbserver.mycompany.com
+ uniqueMember:port=5439
+ uniqueMember:dbname=mydb
+ uniqueMember:user=mydb_user
+ uniqueMember:sslmode=require
+
+ might be queried with the following LDAP URL:
+
+ ldap://ldap.mycompany.com/dc=mycompany,dc=com?uniqueMember?one?(cn=mydatabase)
+
+
+
+
+
+
+
SSL Support
+
+
-
-
PostgreSQL offers asynchronous notification via the
-LISTEN and NOTIFY commands. A client session registers its interest in a particular
-notification condition with the LISTEN command (and can stop listening
-with the UNLISTEN command). All sessions listening on a
-particular condition will be notified asynchronously when a NOTIFY command with that
-condition name is executed by any session. No additional information is
-passed from the notifier to the listener. Thus, typically, any actual data
-that needs to be communicated is transferred through a database table.
-Commonly, the condition name is the same as the associated table, but it is
-not necessary for there to be any associated table.
-
-
-
libpq applications submit
-LISTEN and UNLISTEN commands as
-ordinary SQL commands. The arrival of NOTIFY
-messages can subsequently be detected by calling
-
-
-The function PQnotifies
- returns the next notification from a list of unhandled
- notification messages received from the server. It returns a null pointer if
- there are no pending notifications. Once a notification is
- returned from PQnotifies>, it is considered handled and will be
- removed from the list of notifications.
-
-PGnotify *PQnotifies(PGconn *conn);
-
-typedef struct pgNotify {
- char *relname; /* notification condition name */
- int be_pid; /* process ID of notifying server process */
- char *extra; /* notification parameter */
-} PGnotify;
-
-After processing a PGnotify object returned by
-PQnotifies, be sure to free it with
-PQfreemem. It is sufficient to free the
-PGnotify pointer; the
-relname and extra fields
-do not represent separate allocations.
-(At present, the extra field is unused and will
-always point to an empty string.)
-
-
- gives a sample program that illustrates the use
-of asynchronous notification.
-
-
-PQnotifies does not actually read data from the server; it just
-returns messages previously absorbed by another
libpq
-function. In prior releases of
libpq, the only way
-to ensure timely receipt of NOTIFY> messages was to constantly submit commands,
-even empty ones, and then check PQnotifies after each
-PQexec. While this still works, it is
-deprecated as a waste of processing power.
-
-
-A better way to check for NOTIFY>
-messages when you have no useful commands to execute is to call
-PQconsumeInput, then check
-PQnotifies.
-You can use select() to wait for data to
-arrive from the server, thereby using no
CPU power unless there is something
-to do. (See PQsocket to obtain the file descriptor
-number to use with select().)
-Note that this will work OK whether you submit commands with
-PQsendQuery/PQgetResult or simply
-use PQexec. You should, however, remember to
-check PQnotifies after each
-PQgetResult or PQexec, to see
-if any notifications came in during the processing of the command.
-
-
-
-
-
-
Functions Associated with the COPY Command
-
-
- with libpq
-
-
- The
COPY command in
PostgreSQL
- has options to read from or write to the network connection used by
-
libpq. The functions described in this section
- allow applications to take advantage of this capability by supplying or
- consuming copied data.
-
-
- The overall process is that the application first issues the SQL
- COPY command via PQexec or one
- of the equivalent functions. The response to this (if there is no error
- in the command) will be a PGresult> object bearing a status
- code of PGRES_COPY_OUT or PGRES_COPY_IN
- (depending on the specified copy direction). The application should then
- use the functions of this section to receive or transmit data rows.
- When the data transfer is complete, another PGresult> object
- is returned to indicate success or failure of the transfer. Its status
- will be PGRES_COMMAND_OK for success or
- PGRES_FATAL_ERROR if some problem was encountered.
- At this point further SQL commands can be issued via
- PQexec. (It is not possible to execute other SQL
- commands using the same connection while the COPY
- operation is in progress.)
-
-
- If a COPY command is issued via
- PQexec in a string that could contain additional
- commands, the application must continue fetching results via
- PQgetResult> after completing the COPY
- sequence. Only when PQgetResult> returns NULL is it certain
- that the PQexec command string is done and it is
- safe to issue more commands.
-
-
- The functions of this section should be executed only after obtaining a
- result status of PGRES_COPY_OUT or
- PGRES_COPY_IN from PQexec or
- PQgetResult.
-
-
- A PGresult> object bearing one of these status values
- carries some additional data about the COPY operation that
- is starting. This additional data is available using functions that are
- also used in connection with query results:
-
-
-
-
PQnfieldsPQnfields>with COPY>>
-
- Returns the number of columns (fields) to be copied.
-
-
-
-
-
-
PQbinaryTuplesPQbinaryTuples>with COPY>>
-
- 0 indicates the overall copy format is textual (rows
- separated by newlines, columns separated by separator
- characters, etc).
- 1 indicates the overall copy format is binary.
- See
- for more information.
-
-
-
-
-
-
PQfformatPQfformat>with COPY>>
-
- Returns the format code (0 for text, 1 for binary) associated
- with each column of the copy operation. The per-column format
- codes will always be zero when the overall copy format is textual,
- but the binary format can support both text and binary columns.
- (However, as of the current implementation of COPY>,
- only binary columns appear in a binary copy; so the per-column
- formats always match the overall format at present.)
-
-
-
-
-
-
-
-These additional data values are only available when using protocol 3.0.
-When using protocol 2.0, all these functions will return 0.
-
-
-
-
-
Functions for Sending COPY Data
-
- These functions are used to send data during COPY FROM STDIN>.
- They will fail if called when the connection is not in COPY_IN>
- state.
-
-
-
-
-
PQputCopyDataPQputCopyData>>
-
- Sends data to the server during COPY_IN> state.
-
-int PQputCopyData(PGconn *conn,
- const char *buffer,
- int nbytes);
-
-
-
-Transmits the
COPY data in the specified
buffer>, of length
-
nbytes>, to the server. The result is 1 if the data was sent,
-zero if it was not sent because the attempt would block (this case is only
-possible if the connection is in nonblocking mode), or -1 if an error occurred.
-(Use PQerrorMessage to retrieve details if the return
-value is -1. If the value is zero, wait for write-ready and try again.)
-
-
-The application can divide the COPY data stream into buffer loads of any
-convenient size. Buffer-load boundaries have no semantic significance when
-sending. The contents of the data stream must match the data format expected
-by the COPY> command; see
- for details.
-
-
-
-
-
-
PQputCopyEndPQputCopyEnd>>
-
- Sends end-of-data indication to the server during COPY_IN> state.
-
-int PQputCopyEnd(PGconn *conn,
- const char *errormsg);
-
-
-
-Ends the
COPY_IN> operation successfully if errormsg>
-is
NULL. If
errormsg> is not NULL then the COPY>
-is forced to fail, with the string pointed to by
errormsg>
-used as the error message. (One should not assume that this exact error
-message will come back from the server, however, as the server might have
-already failed the COPY> for its own reasons. Also note that the
-option to force failure does not work when using pre-3.0-protocol connections.)
-
-
-The result is 1 if the termination data was sent,
-zero if it was not sent because the attempt would block (this case is only
-possible if the connection is in nonblocking mode), or -1 if an error occurred.
-(Use PQerrorMessage to retrieve details if the return
-value is -1. If the value is zero, wait for write-ready and try again.)
-
-
-After successfully calling PQputCopyEnd>, call
-PQgetResult> to obtain the final result status of the
-COPY> command. One can wait for
-this result to be available in the usual way. Then return to normal
-operation.
-
-
-
-
-
-
-
-
-
Functions for Receiving COPY Data
-
- These functions are used to receive data during COPY TO STDOUT>.
- They will fail if called when the connection is not in COPY_OUT>
- state.
-
-
-
-
-
PQgetCopyDataPQgetCopyData>>
-
- Receives data from the server during COPY_OUT> state.
-
-int PQgetCopyData(PGconn *conn,
- char **buffer,
- int async);
-
-
-
-Attempts to obtain another row of data from the server during a COPY.
-Data is always returned one data row at a time; if only a partial row
-is available, it is not returned. Successful return of a data row
-involves allocating a chunk of memory to hold the data. The
-
buffer> parameter must be non-NULL. *buffer>
-is set to point to the allocated memory, or to NULL in cases where no
-buffer is returned. A non-NULL result buffer must be freed using
-PQfreemem> when no longer needed.
-
-
-When a row is successfully returned, the return value is the number of
-data bytes in the row (this will always be greater than zero). The
-returned string is always null-terminated, though this is probably only
-useful for textual COPY. A result of zero indicates that the COPY is
-still in progress, but no row is yet available (this is only possible
-result of -1 indicates that the COPY is done.
-A result of -2 indicates that an error occurred (consult
-PQerrorMessage> for the reason).
-
-
-When
async> is true (not zero), PQgetCopyData>
-will not block waiting for input; it will return zero if the COPY is still
-in progress but no complete row is available. (In this case wait for
-read-ready and then call PQconsumeInput> before calling
-
PQgetCopyData> again.) When async> is
-false (zero), PQgetCopyData> will block until data is available
-or the operation completes.
-
-
-After PQgetCopyData> returns -1, call
-PQgetResult> to obtain the final result status of the
-COPY> command. One can wait for
-this result to be available in the usual way. Then return to normal
-operation.
-
-
-
-
-
-
-
-
-
Obsolete Functions for COPY
-
- These functions represent older methods of handling COPY>.
- Although they still work, they are deprecated due to poor error handling,
- inconvenient methods of detecting end-of-data, and lack of support for binary
- or nonblocking transfers.
-
-
-
-
-
- Reads a newline-terminated line of characters
- (transmitted by the server) into a buffer
- string of size
length>.
-
-int PQgetline(PGconn *conn,
- char *buffer,
- int length);
-
-
-
-This function copies up to
length>-1 characters
-into the buffer and converts
-the terminating newline into a zero byte.
-PQgetline returns EOF at the end of input, 0 if the
-entire line has been read, and 1 if the buffer is full but the
-terminating newline has not yet been read.
-
-Note that the application must check to see if a
-new line consists of the two characters \.,
-which indicates that the server has finished sending
-the results of the COPY command.
-If the application might
-receive lines that are more than
length>-1 characters long,
-care is needed to be sure it recognizes the \. line correctly
-(and does not, for example, mistake the end of a long data line
-for a terminator line).
-
-
-
-
-
-
PQgetlineAsyncPQgetlineAsync>>
-
- Reads a row of COPY data
- (transmitted by the server) into a buffer
- without blocking.
-
-int PQgetlineAsync(PGconn *conn,
- char *buffer,
- int bufsize);
-
-
-
-This function is similar to PQgetline, but it can be used
-by applications
-that must read COPY data asynchronously, that is, without blocking.
-Having issued the COPY command and gotten a PGRES_COPY_OUT
-response, the
-application should call PQconsumeInput and
-PQgetlineAsync until the
-end-of-data signal is detected.
-
-Unlike PQgetline, this function takes
-responsibility for detecting end-of-data.
-
-On each call, PQgetlineAsync will return data if a
-complete data row is available in
libpq>'s input buffer.
-Otherwise, no data is returned until the rest of the row arrives.
-The function returns -1 if the end-of-copy-data marker has been recognized,
-or 0 if no data is available, or a positive number giving the number of
-bytes of data returned. If -1 is returned, the caller must next call
-PQendcopy, and then return to normal processing.
-
-The data returned will not extend beyond a data-row boundary. If possible
-a whole row will be returned at one time. But if the buffer offered by
-the caller is too small to hold a row sent by the server, then a partial
-data row will be returned. With textual data this can be detected by testing
-whether the last returned byte is \n or not. (In a binary
-COPY>, actual parsing of the COPY> data format will be needed to make the
-equivalent determination.)
-The returned string is not null-terminated. (If you want to add a
-terminating null, be sure to pass a
bufsize one smaller
-than the room actually available.)
-
-
-
-
-
-
-Sends a null-terminated string to the server.
-Returns 0 if OK and EOF if unable to send the string.
-
-int PQputline(PGconn *conn,
- const char *string);
-
-
-
-The COPY data stream sent by a series of calls to
-PQputline has the same format as that returned by
-PQgetlineAsync, except that applications are not
-obliged to send exactly one data row per PQputline
-call; it is okay to send a partial line or multiple lines per call.
-
-
-
-Before
PostgreSQL protocol 3.0, it was necessary
-for the application to explicitly send the two characters
-\. as a final line to indicate to the server that it had
-finished sending COPY> data. While this still works, it is deprecated and the
-special meaning of \. can be expected to be removed in a
-future release. It is sufficient to call PQendcopy after
-having sent the actual data.
-
-
-
-
-
-
-
PQputnbytesPQputnbytes>>
-
-Sends a non-null-terminated string to the server.
-Returns 0 if OK and EOF if unable to send the string.
-
-int PQputnbytes(PGconn *conn,
- const char *buffer,
- int nbytes);
-
-
-
-This is exactly like PQputline, except that the data
-buffer need not be null-terminated since the number of bytes to send is
-specified directly. Use this procedure when sending binary data.
-
-
-
-
-
-
- Synchronizes with the server.
-
-int PQendcopy(PGconn *conn);
-
- This function waits until
- the server has finished the copying. It should
- either be issued when the last string has been
- sent to the server using PQputline or when the
- last string has been received from the server
- using PGgetline. It must be issued or the server
- will get out of sync
with the client. Upon
- return from this function, the server is ready to
- receive the next SQL command.
- The return value is 0 on successful completion,
- nonzero otherwise. (Use PQerrorMessage to retrieve
- details if the return value is nonzero.)
-
-
-When using PQgetResult, the application should respond to
-a PGRES_COPY_OUT result by executing PQgetline
-repeatedly, followed by PQendcopy after the terminator line is seen.
-It should then return to the PQgetResult loop until
-PQgetResult returns a null pointer. Similarly a PGRES_COPY_IN
-result is processed by a series of PQputline calls followed by
-PQendcopy, then return to the PQgetResult loop.
-This arrangement will ensure that
-a
COPY command embedded in a series of
SQL commands
-will be executed correctly.
-
-
-Older applications are likely to submit a COPY
-via PQexec and assume that the transaction is done after
-PQendcopy.
-This will work correctly only if the COPY is the only
-
SQL command in the command string.
-
-
-
-
-
-
-
-
-
-
-
Control Functions
-
-These functions control miscellaneous details of
-
-
-
-
-
PQsetErrorVerbosityPQsetErrorVerbosity>>
-
-Determines the verbosity of messages returned by
-PQerrorMessage> and PQresultErrorMessage>.
-
-typedef enum {
- PQERRORS_TERSE,
- PQERRORS_DEFAULT,
- PQERRORS_VERBOSE
-} PGVerbosity;
-
-PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity);
-
-PQsetErrorVerbosity> sets the verbosity mode, returning
-the connection's previous setting. In TERSE> mode,
-returned messages include severity, primary text, and position only;
-this will normally fit on a single line. The default mode produces
-messages that include the above plus any detail, hint, or context
-fields (these might span multiple lines). The VERBOSE>
-mode includes all available fields. Changing the verbosity does not
-affect the messages available from already-existing
-PGresult> objects, only subsequently-created ones.
-
-
-
-
-
-
- Enables tracing of the client/server communication to a debugging file stream.
-
-void PQtrace(PGconn *conn, FILE *stream);
-
-
-
-On Windows, if the
libpq> library and an application are
-compiled with different flags, this function call will crash the
-application because the internal representation of the FILE>
-pointers differ. Specifically, multithreaded/single-threaded,
-release/debug, and static/dynamic flags should be the same for the
-library and all applications using that library.
-
-
-
-
-
-
-
- Disables tracing started by PQtrace.
-
-void PQuntrace(PGconn *conn);
-
-
-
-
-
-
-
-
-
-
Miscellaneous Functions
-
-As always, there are some functions that just don't fit anywhere.
-
-
-
-
-
PQencryptPasswordPQencryptPassword>>
-
-Prepares the encrypted form of a
PostgreSQL> password.
-
-char * PQencryptPassword(const char *passwd, const char *user);
-
-This function is intended to be used by client
-applications that wish to send commands like
-ALTER USER joe PASSWORD 'pwd'>.
-It is good practice not to send the original cleartext password in such a
-command, because it might be exposed in command logs, activity displays,
-and so on. Instead, use this function to convert the password to encrypted
-form before it is sent. The arguments are the cleartext password, and the SQL
-name of the user it is for. The return value is a string allocated by
-malloc, or NULL if out of memory.
-The caller can assume the string doesn't contain any special
-characters that would require escaping. Use PQfreemem> to free
-the result when done with it.
-
-
-
-
-
-
-
-
-
Notice Processing
-
-
- in libpq
-
-
-Notice and warning messages generated by the server are not returned by the
-query execution functions, since they do not imply failure of the query.
-Instead they are passed to a notice handling function, and execution continues
-normally after the handler returns. The default notice handling function
-prints the message on stderr, but the application can
-override this behavior by supplying its own handling function.
-
-
-For historical reasons, there are two levels of notice handling, called the
-notice receiver and notice processor. The default behavior is for the notice
-receiver to format the notice and pass a string to the notice processor
-for printing. However, an application that chooses to provide its own notice
-receiver will typically ignore the notice processor layer and just do all the
-work in the notice receiver.
-
-
-The function PQsetNoticeReceiver
-
notice receiver>>PQsetNoticeReceiver>>
-sets or examines the current notice receiver for a connection object.
-Similarly, PQsetNoticeProcessor
-
notice processor>>PQsetNoticeProcessor>>
-sets or examines the current notice processor.
-
-
-typedef void (*PQnoticeReceiver) (void *arg, const PGresult *res);
-
-PQnoticeReceiver
-PQsetNoticeReceiver(PGconn *conn,
- PQnoticeReceiver proc,
- void *arg);
-
-typedef void (*PQnoticeProcessor) (void *arg, const char *message);
-
-PQnoticeProcessor
-PQsetNoticeProcessor(PGconn *conn,
- PQnoticeProcessor proc,
- void *arg);
-
-
-Each of these functions returns the previous notice receiver or processor
-function pointer, and sets the new value.
-If you supply a null function pointer, no action is taken,
-but the current pointer is returned.
-
-
-When a notice or warning message is received from the server, or generated
-internally by
libpq, the notice receiver function
-is called. It is passed the message in the form of a
-PGRES_NONFATAL_ERROR PGresult.
-(This allows the receiver to extract individual fields using
-PQresultErrorField>, or the complete preformatted message using
-PQresultErrorMessage>.)
-The same void pointer passed to
-PQsetNoticeReceiver is also passed.
-(This pointer can be used to access application-specific state if needed.)
-
-
-The default notice receiver simply extracts the message (using
-PQresultErrorMessage>) and passes it to the notice processor.
-
-
-The notice processor is responsible for handling a notice or warning message
-given in text form. It is passed the string text of the message
-(including a trailing newline), plus
-a void pointer that is the same one passed to
-PQsetNoticeProcessor.
-(This pointer can be used to access application-specific state if needed.)
-
-
-The default notice processor is simply:
-static void
-defaultNoticeProcessor(void *arg, const char *message)
-{
- fprintf(stderr, "%s", message);
-}
-
-
-
-Once you have set a notice receiver or processor, you should expect that that
-function could be called as long as either the PGconn> object or
-PGresult> objects made from it exist. At creation of a
-PGresult>, the PGconn>'s current notice handling
-pointers are copied into the PGresult> for possible use by
-functions like PQgetvalue.
-
-
-
-
-
-
Environment Variables
-
-
-
-
-The following environment variables can be used to select default
-connection parameter values, which will be used by
-PQconnectdb>, PQsetdbLogin> and
-PQsetdb> if no value is directly specified by the calling
-code. These are useful to avoid hard-coding database connection
-information into simple client applications, for example.
-
-
-
-
-
-PGHOST sets the database server name.
-If this begins with a slash, it specifies Unix-domain communication
-rather than TCP/IP communication; the value is then the name of the
-directory in which the socket file is stored (in a default installation
-setup this would be /tmp).
-
-
-
-
-
-PGHOSTADDR specifies the numeric IP address of the database
-server. This can be set instead of or in addition to PGHOST
-to avoid DNS lookup overhead. See the documentation of
-these parameters, under PQconnectdb above, for details
-on their interaction.
-
-When neither PGHOST nor PGHOSTADDR is set,
-the default behavior is to connect using a local Unix-domain socket; or on
-machines without Unix-domain sockets,
libpq will
-attempt to connect to localhost>.
-
-
-
-
-
-PGPORT sets the TCP port number or Unix-domain
-socket file extension for communicating with the
-
-
-
-
-
-PGDATABASE sets the
-
PostgreSQL database name.
-
-
-
-
-
-PGUSER
-sets the user name used to connect to the database.
-
-
-
-
-
-PGPASSWORD
-sets the password used if the server demands password
-authentication. Use of this environment variable is not
-recommended for security reasons (some operating systems
-allow non-root users to see process environment variables via
-
ps>); instead consider using the
-~/.pgpass> file (see ).
-
-
-
-
-
-PGPASSFILE
-specifies the name of the password file to use for lookups.
-If not set, it defaults to ~/.pgpass>
-(see ).
-
-
-
-
-
-PGSERVICE
-sets the service name to be looked up in pg_service.conf.
-This offers a shorthand way of setting all the parameters.
-
-
-
-
-
-PGREALM sets the Kerberos realm to use with
-
PostgreSQL, if it is different from the local realm.
-If
PGREALM is set,
libpq
-applications will attempt authentication with servers for this realm and use
-separate ticket files to avoid conflicts with local
-ticket files. This environment variable is only
-used if Kerberos authentication is selected by the server.
-
-
-
-
-
-PGOPTIONS sets additional run-time options for
-
-
-
-
-
-PGSSLMODE determines whether and with what priority an
-
SSL> connection will be negotiated with the server. There are
-four modes: disable> will attempt only an unencrypted
-
SSL> connection; allow> will negotiate,
-trying first a non-
SSL> connection, then if that fails,
-trying an
SSL> connection; prefer>
-(the default) will negotiate, trying first an
SSL>
-connection, then if that fails, trying a regular non-
SSL>
-connection;
require> will try only an SSL>
-connection. If
PostgreSQL> is compiled without SSL support,
-using option require> will cause an error, while options
-allow> and prefer> will be accepted but
-
libpq> will not in fact attempt an SSL>
-connection.
-
-
-
-
-
-PGREQUIRESSL sets whether or not the connection must be
-made over
SSL. If set to
-will refuse to connect if the server does not accept
-an
SSL connection (equivalent to
sslmode>
-prefer>).
-This option is deprecated in favor of the sslmode>
-setting, and is only available if
-
PostgreSQL> is compiled with SSL support.
-
-
-
-
-
-PGSSLKEY
-specifies the hardware token that stores the secret key for the client
-certificate. The value of this variable should consist
-of a colon-separated engine name (engines are
OpenSSL>
-loadable modules) and an engine-specific key identifier. If this is not
-set, the secret key must be kept in a file.
-
-
-
-
-
-PGKRBSRVNAME sets the Kerberos service name to use when
-authenticating with Kerberos 5 or GSSAPI.
-
-
-
-
-
-PGGSSLIB sets the GSS library to use for GSSAPI
-authentication.
-
-
-
-
-
-PGCONNECT_TIMEOUT sets the maximum number of seconds
-that
libpq will wait when attempting to
-connect to the
PostgreSQL server. If unset
-or set to zero,
libpq will wait indefinitely.
-It is not recommended to set the timeout to less than 2 seconds.
-
-
-
-
-
-The following environment variables can be used to specify default
-behavior for each
PostgreSQL session.
-(See also the
- and
-
-commands for ways to set default behavior on a per-user or per-database
-basis.)
-
-
-
-
-
-PGDATESTYLE
-sets the default style of date/time representation.
-(Equivalent to SET datestyle TO ....)
-
-
-
-
-
-PGTZ
-sets the default time zone.
-(Equivalent to SET timezone TO ....)
-
-
-
-
-
-PGCLIENTENCODING
-sets the default client character set encoding.
-(Equivalent to SET client_encoding TO ....)
-
-
-
-
-
-PGGEQO
-sets the default mode for the genetic query optimizer.
-(Equivalent to SET geqo TO ....)
-
-
-
-
-Refer to the
SQL command
-
-for information on correct values for these environment variables.
-
-
-The following environment variables determine internal behavior of
-
libpq; they override compiled-in defaults.
-
-
-
-
-
-PGSYSCONFDIR
-sets the directory containing the pg_service.conf> file.
-
-
-
-
-
-PGLOCALEDIR
-sets the directory containing the locale> files for message
-internationalization.
-
-
-
-
-
-
-
-
-
-
The Password File
-
-
-
-
-
-
-The file .pgpass in a user's home directory or the
-file referenced by PGPASSFILE can contain passwords to
-be used if the connection requires a password (and no password has been
-specified otherwise). On Microsoft Windows the file is named
-%APPDATA%\postgresql\pgpass.conf> (where
-%APPDATA%> refers to the Application Data subdirectory in
-the user's profile).
-
-
-This file should contain lines of the following format:
-
-hostname:port:database:username:password
-
-Each of the first four fields can be a literal value, or *,
-which matches anything. The password field from the first line that matches the
-current connection parameters will be used. (Therefore, put more-specific
-entries first when you are using wildcards.)
-If an entry needs to contain : or
-\, escape this character with \.
-A host name of localhost> matches both TCP (hostname
-localhost>) and Unix domain socket (pghost> empty or the
-default socket directory) connections coming from the local machine.
-
-
-On Unix systems, the permissions on .pgpass must disallow
-any access to world or group; achieve this by the command
-chmod 0600 ~/.pgpass.
-If the permissions are less strict than this, the file will be ignored.
-On Microsoft Windows, it is assumed that the file is stored in a directory
-that is secure, so no special permissions check is made.
-
-
-
-
-
-
The Connection Service File
-
-
-
connection service file
-
-
-
-
-The connection service file allows libpq connection parameters to be
-associated with a single service name. That service name can then be
-specified by a libpq connection, and the associated settings will be
-used. This allows connection parameters to be modified without requiring
-a recompile of the libpq application. The service name can also be
-specified using the PGSERVICE environment variable.
-
-To use this feature, copy
-share/pg_service.conf.sample to
-etc/pg_service.conf and edit the file to add
-service names and parameters. This file can be used for client-only
-installs too. The file's location can also be specified by the
-PGSYSCONFDIR environment variable.
-
-
-
-
-
-
LDAP Lookup of Connection Parameters
-
-
-
LDAP connection parameter lookup
-
-
-If
libpq has been compiled with LDAP support (option
- for configure)
-it is possible to retrieve connection options like host
-or dbname via LDAP from a central server.
-The advantage is that if the connection parameters for a database change,
-the connection information doesn't have to be updated on all client machines.
-
-
-LDAP connection parameter lookup uses the connection service file
-pg_service.conf (see ).
-A line in a pg_service.conf stanza that starts with
-ldap:// will be recognized as an LDAP URL and an LDAP
-query will be performed. The result must be a list of keyword =
-value pairs which will be used to set connection options.
-The URL must conform to RFC 1959 and be of the form
-
-ldap://[hostname[:port]]/search_base?attribute?search_scope?filter
-
-where hostname
-defaults to localhost and
-port defaults to 389.
-
-
-Processing of pg_service.conf is terminated after
-a successful LDAP lookup, but is continued if the LDAP server cannot be
-contacted. This is to provide a fallback with
-further LDAP URL lines that point to different LDAP
-servers, classical keyword = value pairs, or
-default connection options.
-If you would rather get an error message in this case, add a
-syntactically incorrect line after the LDAP URL.
-
-
-A sample LDAP entry that has been created with the LDIF file
-
-version:1
-dn:cn=mydatabase,dc=mycompany,dc=com
-changetype:add
-objectclass:top
-objectclass:groupOfUniqueNames
-cn:mydatabase
-uniqueMember:host=dbserver.mycompany.com
-uniqueMember:port=5439
-uniqueMember:dbname=mydb
-uniqueMember:user=mydb_user
-uniqueMember:sslmode=require
-
-might be queried with the following LDAP URL:
-
-ldap://ldap.mycompany.com/dc=mycompany,dc=com?uniqueMember?one?(cn=mydatabase)
-
-
-
-
-
-
-
SSL Support
-
-
-
-
+
-
PostgreSQL> has native support for using
-
SSL> connections to encrypt client/server communications
- for increased security. See for details
-
about the server-side SSL> functionality.
+
PostgreSQL> has native support for using SSL>
+ connections to encrypt client/server communications for increased
+ security. See for details about the server-side
-
+
libpq reads the system-wide
OpenSSL configuration file. By default, this
file is named openssl.cnf and is located in the
- directory reported by openssl version -d>.
- This default can be overridden by setting environment variable
+ directory reported by openssl version -d>. This default
+ can be overridden by setting environment variable
OPENSSL_CONF to the name of the desired configuration
file.
-
+
- If the server demands a client certificate,
- will send the certificate stored in file
- ~/.postgresql/postgresql.crt> within the user's home directory.
- A matching private key file ~/.postgresql/postgresql.key>
- must also be present, unless the secret key for the certificate is stored
- in a hardware token, as specified by PGSSLKEY.
- (On Microsoft Windows these files are named
- %APPDATA%\postgresql\postgresql.crt and
- %APPDATA%\postgresql\postgresql.key.)
- The private key file must not be world-readable.
+ If the server demands a client certificate,
+
libpq will send the certificate stored in
+ file ~/.postgresql/postgresql.crt> within the user's home
+ directory. A matching private key file
+ ~/.postgresql/postgresql.key> must also be present, unless
+ the secret key for the certificate is stored in a hardware token, as
+ specified by PGSSLKEY. (On Microsoft Windows these
+ files are named %APPDATA%\postgresql\postgresql.crt
+ and %APPDATA%\postgresql\postgresql.key.) The
+ private key file must not be world-readable.
If the file ~/.postgresql/root.crt> is present in the user's
- home directory,
-
libpq will use the certificate list stored
- therein to verify the server's certificate.
+ home directory,
libpq will use the
+ certificate list stored therein to verify the server's certificate.
(On Microsoft Windows the file is named
- %APPDATA%\postgresql\root.crt.)
- The SSL connection will
- fail if the server does not present a certificate; therefore, to
+ %APPDATA%\postgresql\root.crt.) The SSL connection
+ will fail if the server does not present a certificate; therefore, to
use this feature the server must have a server.crt> file.
Certificate Revocation List (CRL) entries are also checked if the file
- ~/.postgresql/root.crl exists (%APPDATA%\postgresql\root.crl
- on Microsoft Windows).
+ ~/.postgresql/root.crl exists
+ (%APPDATA%\postgresql\root.crl on Microsoft
+ Windows).
- If you are using
SSL> inside your application (in addition to
- inside
libpq), you can use
PQinitSSL(int)>
- to tell
libpq that the
SSL> library
- has already been initialized by your application.
+ If you are using
SSL> inside your application (in addition
+ to inside
libpq), you can use
+
PQinitSSL(int)> to tell libpq
+ that the
SSL> library has already been initialized by your
+ application.
-
-
-
-
-
Behavior in Threaded Programs
-
-
- with libpq
-
-
-
libpq is reentrant and thread-safe if the
-configure command-line option
---enable-thread-safety> was used when the
-
PostgreSQL distribution was built. In
-addition, you might need to use additional compiler command-line
-options when you compile your application code. Refer to your
-system's documentation for information about how to build
-thread-enabled applications, or look in
-src/Makefile.global for PTHREAD_CFLAGS>
-and PTHREAD_LIBS>. This function allows the querying of
-
libpq's thread-safe status:
-
-
-
-
-
PQisthreadsafePQisthreadsafe>>
-
- Returns the thread safety status of the
libpq
- library.
-
-int PQisthreadsafe();
-
-
-
- Returns 1 if the
libpq is thread-safe and
- 0 if it is not.
-
-
-
-
-
-One thread restriction is that no two threads attempt to manipulate the same
-PGconn> object at the same time. In particular, you cannot
-issue concurrent commands from different threads through the same
-connection object. (If you need to run concurrent commands, use
-multiple connections.)
-
-
-PGresult> objects are read-only after creation, and so can be
-passed around freely between threads.
-
-
-The deprecated functions
-PQrequestCancel and
-PQoidStatus
-are not thread-safe and should not be used in multithread programs.
-PQrequestCancel can be replaced by
-PQcancel.
-PQoidStatus can be replaced by
-PQoidValue.
-
-
-If you are using Kerberos inside your application (in addition to inside
-
libpq), you will need to do locking around
-Kerberos calls because Kerberos functions are not thread-safe. See
-function PQregisterThreadLock> in the
-
libpq source code for a way to do cooperative
-locking between
libpq and your application.
-
-
-If you experience problems with threaded applications, run
-the program in src/tools/thread> to see if your
-platform has thread-unsafe functions. This program is run
-by configure, but for binary distributions
-your library might not match the library used to build the binaries.
-
-
-
+
+
+
+
+
Behavior in Threaded Programs
+
+
+ with libpq
+
+
+
libpq is reentrant and thread-safe if the
+ configure command-line option
+ --enable-thread-safety> was used when the
+
PostgreSQL distribution was built. In
+ addition, you might need to use additional compiler command-line
+ options when you compile your application code. Refer to your
+ system's documentation for information about how to build
+ thread-enabled applications, or look in
+ src/Makefile.global for PTHREAD_CFLAGS>
+ and PTHREAD_LIBS>. This function allows the querying of
+
libpq's thread-safe status:
+
+
+
+
+
+ PQisthreadsafe
+
+
+
+
+ Returns the thread safety status of the
+
+ int PQisthreadsafe();
+
+
+
+ Returns 1 if the
libpq is thread-safe
+ and 0 if it is not.
+
+
+
+
+
+ One thread restriction is that no two threads attempt to manipulate
+ the same PGconn> object at the same time. In particular,
+ you cannot issue concurrent commands from different threads through
+ the same connection object. (If you need to run concurrent commands,
+ use multiple connections.)
+
+
+ PGresult> objects are read-only after creation, and so
+ can be passed around freely between threads.
+
+
+ The deprecated functions PQrequestCancel and
+ PQoidStatus are not thread-safe and should not be
+ used in multithread programs. PQrequestCancel
+ can be replaced by PQcancel.
+ PQoidStatus can be replaced by
+ PQoidValue.
+
+
+ If you are using Kerberos inside your application (in addition to inside
+
libpq), you will need to do locking around
+ Kerberos calls because Kerberos functions are not thread-safe. See
+ function PQregisterThreadLock> in the
+
libpq source code for a way to do cooperative
+ locking between
libpq and your application.
+
+
+ If you experience problems with threaded applications, run the program
+ in src/tools/thread> to see if your platform has
+ thread-unsafe functions. This program is run by
+ configure, but for binary distributions your
+ library might not match the library used to build the binaries.
+
+
+
+
-
+
libpq applications
-
+
To build (i.e., compile and link) a program using
- do all of the following things:
-
+
libpq you need to
do all of the following
+ things:
+
#include <libpq-fe.h>
- If you failed to do that then you will normally get error
- messages from your compiler similar to
+ If you failed to do that then you will normally get error messages
+ from your compiler similar to
foo.c: In function `main':
foo.c:34: `PGconn' undeclared (first use in this function)
-
+
Point your compiler to the directory where the
PostgreSQL> header
CPPFLAGS += -I/usr/local/pgsql/include
-
+
If there is any chance that your program might be compiled by
other users then you should not hardcode the directory location
/usr/local/include
-
+
Failure to specify the correct option to the compiler will
result in an error message such as
-
+
When linking the final program, specify the option
-
-lpq so that the
libpq library gets pulled
- in, as well as the option
- -Ldirectory to
- point the compiler to the directory where the
libpq library resides. (Again, the
+ library gets pulled in, as well as the option
+ -Ldirectory to point
+ the compiler to the directory where the
+
libpq library resides. (Again, the
compiler will search some directories by default.) For maximum
portability, put the option before the
option. For example:
cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq
-
+
You can find out the library directory using
pg_config as well:
/usr/local/pgsql/lib
-
+
- Error messages that point to problems in this area could look
- like the following.
+ Error messages that point to problems in this area could look like
+ the following.
testlibpq.o: In function `main':
testlibpq.o(.text+0x60): undefined reference to `PQsetdbLogin'
/usr/bin/ld: cannot find -lpq
- This means you forgot the option or did not specify
- the right directory.
+ This means you forgot the option or did not
+ specify the right directory.
-
+
-
-
+
+
Example Programs
-
+
These examples and others can be found in the
directory src/test/examples in the source code