Chapter 1. libpq - C Library

libpq is a set of library routines that enable client programs to pass queries to the Red Hat Database backend server and to receive the results of these queries. libpq is also the underlying engine for several other Red Hat Database client interfaces, including libpq++ (C++), libpgtcl (Tcl), libpgeasy, and ecpg. If you use one of those packages, the behavior of libpq will be important to you.

This chapter describes the following libpq functions:

Database Connection:

the Section called Establishing and Closing Connections

  • PQconnectdb

  • PQsetdbLogin

  • PQsetdb

  • PQconnectStart

  • PQconndefaults

  • PQfinish

  • PQreset

  • PQresetStart, PQresetPoll

the Section called Using Accessor Functions

  • PQdb

  • PQuser

  • PQpass

  • PQhost

  • PQport

  • PQtty

  • PQoptions

  • PQstatus

  • PQerrorMessage

  • PQbackendPID

  • PQgetssl

Query Execution:

the Section called Main Routines

  • PQexec

  • PQresultStatus

  • PQresStatus

  • PQresultErrorMessage

  • PQclear

  • PQmakeEmptyPGresult

the Section called Retrieving SELECT Result Information

  • PQntuples

  • PQnfields

  • PQfname

  • PQfnumber

  • PQftype

  • PQfmod

  • PQfsize

  • PQbinaryTuples

the Section called Retrieving SELECT Result Values

  • PQgetvalue

  • PQgetisnull

  • PQgetlength

  • PQprint

the Section called Retrieving Non-SELECT Result Information

  • PQcmdStatus

  • PQcmdTuples

  • PQoidValue

Asynchronous Query:

the Section called Asynchronous Query Processing

  • PQsetnonblocking

  • PQisnonblocking

  • PQsendQuery

  • PQgetResult

  • PQconsumeInput

  • PQisBusy

  • PQflush

  • PQsocket

  • PQrequestCancel

Fast Path:

the Section called Fast Path Functions

  • PQfn

Asynchronous Notification:

the Section called Asynchronous Notification Functions

  • PQnotifies

COPY Command:

the Section called COPY-Related Functions

  • PQgetline

  • PQgetlineAsync

  • PQputline

  • PQputnbytes

  • PQendcopy

libpq Tracing:

the Section called libpq Tracing Functions

  • PQtrace

  • PQuntrace

libpq Control:

the Section called libpq Control Functions

  • PQsetNoticeProcessor

Three short programs are included in the Section called Example Programs to show how to write programs that use libpq. There are several complete examples of libpq applications in the following directories of the Red Hat Database source tree:
src/test/regress
src/test/examples
src/bin/psql

Frontend programs that use libpq must include the header file libpq-fe.h and must link with the libpq library (by using the -lpq linker option).

Database Connection Functions

Database-connection functions are routines that connect to a Red Hat Database backend server.

An application program can have several connections to the backend server open at one time. Each connection is represented by a PGconn object, which is obtained from PQconnectdb or PQsetdbLogin.

In normal operation PQconnectdb and PQsetdbLogin always return a non-NULL object pointer. Before sending queries via the PGconn connection object, call the PQstatus function to confirm that a connection was made successfully.

Establishing and Closing Connections

PQconnectdb

PQconnectdb makes a new connection to the database server.
PGconn *PQconnectdb(const char *conninfo)
This routine opens a new database connection using the parameters taken from the string conninfo and blocks until the connection attempt operation has completed. This routine has non-blocking analogs, PQconnectStart and PQconnectPoll.

To make a connection, a PQconn object is obtained by calling PQconnectdb or PQsetdbLogin. The PQstatus function can then be called. The passed string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace.

Each parameter setting is in the form keyword = value. (To write a NULL value or a value containing spaces, surround it with single quotes, for example, keyword = 'a value'. Single quotes within the value must be written as \'. Spaces around the equal sign are optional.) The currently recognized parameter keywords are:

host

Name of the host to connect to. If this begins with a slash ('/'), it specifies Unix domain communication rather than TCP/IP communication. The value is the name of the directory in which the socket file is stored. The default is to connect to a Unix-domain socket in /tmp.

hostaddr

IP address of host to connect to. This should be in standard dotted-quad notation (for example, 127.0.0.1). If a non-zero-length string is specified, TCP/IP communication is used.

Using hostaddr instead of host allows the application to avoid a host name look-up, which may be important in applications with time constraints. However, Kerberos authentication requires the host name.

If host is specified without hostaddr, a hostname look-up is forced. If hostaddr is specified without host, the value for hostaddr gives the remote address; if Kerberos is used, this causes a reverse name query. If both host and hostaddr are specified, the value for hostaddr gives the remote address; the value for host is ignored, unless Kerberos is used, in which case that value is used for Kerberos authentication. Note that authentication is likely to fail if libpq is passed a host name that is not the name of the machine at hostaddr.

Without either a host name or host address, libpq connects using a local Unix domain socket.

port

The port number to connect to at the server host, or the socket filename extension for Unix-domain connections.

dbname

The database name.

user

User name to connect as.

password

Password to be used if the server demands password authentication.

options

Trace/debug options to be sent to the server.

tty

A file or tty for optional debug output from the backend.

requiressl

Set to 1 to require SSL connection to the backend. libpq refuses to connect if the server does not support SSL. Set to 0 (default) to negotiate with server.

If any parameter is unspecified, the corresponding environment variable (see the the Section called Environment Variables section) is checked. If the environment variable is also not set, hardwired defaults are used.

The return value is a pointer to an abstract struct that represents the connection to the backend.

PQconnectStart, PQconnectPoll

PQconnectStart and PQconnectPoll make a connection to the database server in a non-blocking manner.
PGconn *PQconnectStart(const char *conninfo)

PostgresPollingStatusType PQconnectPoll(PGconn *conn)
These two routines open a connection to a database server that prevents your application's thread of execution from being blocked on remote I/O.

The database connection is made using the parameters taken from the string conninfo, passed to PQconnectStart. This string is in the same format as described above for PQconnectdb.

Neither PQconnectStart nor PQconnectPoll will block as long as the following restrictions are met:

  1. To begin, call conn=PQconnectStart("connection_info_string").

    • If conn is NULL, then libpq has been unable to allocate a new PGconn structure.

    • Otherwise, a valid PGconn pointer is returned (though not yet representing a valid connection to the database).

  2. On return from PQconnectStart, call status=PQstatus(conn).

    • If status equals CONNECTION_BAD, PQconnectStart has failed.

    • If PQconnectStart succeeds, the next stage is to poll libpq using PQconnectPoll(conn) so that it may proceed with the connection sequence. Loop in this way, considering the connection "inactive" by default.

PQconnectPoll Return Values

  • If PQconnectPoll last returned PGRES_POLLING_ACTIVE, consider it "active" instead.

  • If PQconnectPoll last returned PGRES_POLLING_READING, perform a select for reading on PQsocket(conn).

  • If PQconnectPoll last returned PGRES_POLLING_WRITING, perform a select for writing on PQsocket(conn).

  • If you have yet to call PQconnectPoll, for example, after the call to PQconnectStart, behave as if it last returned PGRES_POLLING_WRITING.

  • If the Select() shows that the socket is ready, consider it "active".

  • If it has been decided that this connection is "active", call PQconnectPoll(conn) again.

  • If this call returns PGRES_POLLING_FAILED, the connection procedure has failed.

  • If this call returns PGRES_POLLING_OK, the connection has been successfully made.

Note that the use of select() to ensure that the socket is ready is merely an example; if you have other facilities available, such as poll(), you can use those instead.

At any time during connection, you can check the status of the connection by calling PQstatus. This function returns a value of type ConnStatusType and may then be checked to determine status. If it returns CONNECTION_BAD, then the connection procedure has failed; if it returns CONNECTION_OK, then the connection is ready. Either of these states should be equally detectable from the return value of PQconnectPoll, as above. Other states may be shown during (and only during) an asynchronous connection procedure. These indicate the current stage of the connection procedure, and may be useful to provide feedback to the user. The status may include:

  • CONNECTION_STARTED: Waiting for connection to be made.

  • CONNECTION_MADE: Connection OK; waiting to send.

  • CONNECTION_AWAITING_RESPONSE: Waiting for a response from the postmaster.

  • CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up.

  • CONNECTION_SETENV: Negotiating environment.

Although these constants will probably continue to exist (in order to maintain compatibility), an application should never rely upon these appearing in a particular order, or at all, or on the status always being one of these documented values. An application may do something like this:
    switch(PQstatus(conn))
    {
        case CONNECTION_STARTED:
            feedback = "Connecting...";
            break;

        case CONNECTION_MADE:
            feedback = "Connected to server...";
            break;
.
.
.
        default:
            feedback = "Connecting...";
    }

Note

If PQconnectStart returns a non-NULL pointer, you must call PQfinish when you are finished with it to dispose of the structure and any associated memory blocks. You must do this even if a call to PQconnectStart or PQconnectPoll failed.

PQconnectPoll will currently block if libpq is compiled with USE_SSL defined. This restriction may be removed in the future.

PQconnectStart and PQconnectPoll leave the socket in a non-blocking state as if PQsetnonblocking had been called.

Using Accessor Functions

PQdb and the next several functions return the values established at connection. These values are fixed for the life of the PGconn object.

Note

libpq application programmers should be careful to maintain the PGconn abstraction. Use the accessor functions below to get at the contents of PGconn. Avoid directly referencing the fields of the PGconn structure because they are subject to change in the future. (The definition of struct PGconn is not even provided in libpq-fe.h. If you have old code that accesses PGconn fields directly, you can keep using it by including libpq-int.h as well, but you should fix the code.)