PostgreSQL 7.1.3 Documentation
Prev |  | Next

# Chapter 1. libpq - C Library

`libpq` is the C application programmer's interface to Postgres. `libpq` is a set of library routines that allow client programs to pass queries to the Postgres backend server and to receive the results of these queries. `libpq` is also the underlying engine for several other Postgres application interfaces, including `libpq++` (C++), `libpgtcl` (Tcl), Perl, and `ecpg`. So some aspects of libpq's behavior will be important to you if you use one of those packages.

Three short programs are included at the end of this section to show how to write programs that use `libpq`. There are several complete examples of `libpq` applications in the following directories:

    ../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.

# 1.1. Database Connection Functions

The following routines deal with making a connection to a Postgres backend server. The application program can have several backend connections open at one time. (One reason to do that is to access more than one database.) Each connection is represented by a `PGconn` object which is obtained from `PQconnectdb` or `PQsetdbLogin`. Note that these functions will always return a non-null object pointer, unless perhaps there is too little memory even to allocate the `PGconn` object. The `PQstatus` function should be called to check whether a connection was successfully made before queries are sent via the connection object.

- `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`. Unlike PQsetdbLogin() below, the parameter set can be extended without changing the function signature, so use either of this routine or the non-blocking analogues PQconnectStart / PQconnectPoll is prefered for application programming. 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, e.g., `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 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 numbers-and-dots form, as used by the BSD functions inet_aton et al. 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. The following therefore applies. 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 will connect using a local Unix domain socket.

  `port`

    Port number to connect to at the server host, or 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 will then refuse to connect if the server does not support SSL. Set to '0' (default) to negotiate with server.

  If any parameter is unspecified, then the corresponding environment variable (see "Environment Variables" section) is checked. If the environment variable is not set either, then hardwired defaults are used. The return value is a pointer to an abstract struct representing the connection to the backend.

- `PQsetdbLogin` Makes a new connection to the database server.

      PGconn *PQsetdbLogin(const char *pghost,
                           const char *pgport,
                           const char *pgoptions,
                           const char *pgtty,
                           const char *dbName,
                           const char *login,
                           const char *pwd)

  This is the predecessor of `PQconnectdb` with a fixed number of parameters but the same functionality.

- `PQsetdb` Makes a new connection to the database server.

      PGconn *PQsetdb(char *pghost,
                      char *pgport,
                      char *pgoptions,
                      char *pgtty,
                      char *dbName)

  This is a macro that calls `PQsetdbLogin()` with null pointers for the login and pwd parameters. It is provided primarily for backward compatibility with old programs.

- `PQconnectStart`, `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 are used to open a connection to a database server such that your application's thread of execution is not blocked on remote I/O whilst doing so.

  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 a number of restrictions are met:

  - The hostaddr and host parameters are used appropriately to ensure that name and reverse name queries are not made. See the documentation of these parameters under PQconnectdb above for details.

  - If you call PQtrace, ensure that the stream object into which you trace will not block.

  - You ensure for yourself that the socket is in the appropriate state before calling PQconnectPoll, as described below.

  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). 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 so that it may proceed with the connection sequence. Loop thus: Consider a connection 'inactive' by default. If PQconnectPoll last returned PGRES_POLLING_ACTIVE, consider it 'active' instead. If PQconnectPoll(conn) last returned PGRES_POLLING_READING, perform a select for reading on PQsocket(conn). If it last returned PGRES_POLLING_WRITING, perform a select for writing on PQsocket(conn). If you have yet to call PQconnectPoll, i.e. 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 a (likely) example; those with other facilities available, such as a poll() call, may of course use that instead.

  At any time during connection, the status of the connection may be checked, by calling PQstatus. If this is CONNECTION_BAD, then the connection procedure has failed; if this is 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 for example. These statuses 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.

  Note that, although these constants will remain (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 that if PQconnectStart returns a non-NULL pointer, you must call PQfinish when you are finished with it, in order to dispose of the structure and any associated memory blocks. This must be done 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.

  PQconnectPoll will currently block under Windows, unless libpq is compiled with WIN32_NON_BLOCKING_CONNECTIONS defined. This code has not yet been tested under Windows, and so it is currently off by default. This may be changed in the future.

  These functions leave the socket in a non-blocking state as if `PQsetnonblocking` had been called.

- `PQconndefaults` Returns the default connection options.

      PQconninfoOption *PQconndefaults(void)

      struct PQconninfoOption
      {
          char   *keyword;   /* The keyword of the option */
          char   *envvar;    /* Fallback environment variable name */
          char   *compiled;  /* Fallback compiled in default value */
          char   *val;       /* Option's current value, or NULL */
          char   *label;     /* Label for field in connect dialog */
          char   *dispchar;  /* Character to display for this field
                                in a connect dialog. Values are:
                                ""        Display entered value as is
                                "*"       Password field - hide value
                                "D"       Debug option - don't show by default */
          int     dispsize;  /* Field size in characters for dialog */
      }

  Returns a connection options array. This may be used to determine all possible PQconnectdb options and their current default values. The return value points to an array of PQconninfoOption structs, which ends with an entry having a NULL keyword pointer. Note that the default values ("val" fields) will depend on environment variables and other context. Callers must treat the connection options data as read-only.

  After processing the options array, free it by passing it to PQconninfoFree(). If this is not done, a small amount of memory is leaked for each call to PQconndefaults().

  In Postgres versions before 7.0, PQconndefaults() returned a pointer to a static array, rather than a dynamically allocated array. That wasn't thread-safe, so the behavior has been changed.

- `PQfinish` Close the connection to the backend. Also frees memory used by the PGconn object.

      void PQfinish(PGconn *conn)

  Note that even if the backend connection attempt fails (as indicated by PQstatus), the application should call PQfinish to free the memory used by the PGconn object. The PGconn pointer should not be used after PQfinish has been called.

- `PQreset` Reset the communication port with the backend.

      void PQreset(PGconn *conn)

  This function will close the connection to the backend and attempt to reestablish a new connection to the same postmaster, using all the same parameters previously used. This may be useful for error recovery if a working connection is lost.

- `PQresetStart` `PQresetPoll` Reset the communication port with the backend, in a non-blocking manner.

      int PQresetStart(PGconn *conn);

      PostgresPollingStatusType PQresetPoll(PGconn *conn);

  These functions will close the connection to the backend and attempt to reestablish a new connection to the same postmaster, using all the same parameters previously used. This may be useful for error recovery if a working connection is lost. They differ from PQreset (above) in that they act in a non-blocking manner. These functions suffer from the same restrictions as PQconnectStart and PQconnectPoll.

  Call PQresetStart. If it returns 0, the reset has failed. If it returns 1, poll the reset using PQresetPoll in exactly the same way as you would create the connection using PQconnectPoll.

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. (Beginning in Postgres release 6.4, 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` too, but you are encouraged to fix the code soon.)

- `PQdb` Returns the database name of the connection.

      char *PQdb(const PGconn *conn)

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

- `PQuser` Returns the user name of the connection.

      char *PQuser(const PGconn *conn)

- `PQpass` Returns the password of the connection.

      char *PQpass(const PGconn *conn)

- `PQhost` Returns the server host name of the connection.

      char *PQhost(const PGconn *conn)

- `PQport` Returns the port of the connection.

      char *PQport(const PGconn *conn)

- `PQtty` Returns the debug tty of the connection.

      char *PQtty(const PGconn *conn)

- `PQoptions` Returns the backend options used in the connection.

      char *PQoptions(const PGconn *conn)

- `PQstatus` Returns the status of the connection.

      ConnStatusType PQstatus(const PGconn *conn)

  The status can be one of a number of values. However, only two of these are seen outside of an asynchronous connection procedure - `CONNECTION_OK` or `CONNECTION_BAD`. A good connection to the database has the status CONNECTION_OK. A failed connection attempt is signaled by status `CONNECTION_BAD`. Ordinarily, an OK status will remain so until `PQfinish`, but a communications failure might result in the status changing to `CONNECTION_BAD` prematurely. In that case the application could try to recover by calling `PQreset`.

  See the entry for PQconnectStart and PQconnectPoll with regards to other status codes that might be seen.

- `PQerrorMessage` Returns the error message most recently generated by an operation on the connection.

      char *PQerrorMessage(const PGconn* conn);

  Nearly all libpq functions will set `PQerrorMessage` if they fail. Note that by libpq convention, a non-empty `PQerrorMessage` will include a trailing newline.

- `PQbackendPID` Returns the process ID of the backend server handling this connection.

      int PQbackendPID(const PGconn *conn);

  The backend PID is useful for debugging purposes and for comparison to NOTIFY messages (which include the PID of the notifying backend). Note that the PID belongs to a process executing on the database server host, not the local host!

- `PQgetssl` Returns the SSL structure used in the connection, or NULL if SSL is not in use.

      SSL *PQgetssl(const PGconn *conn);

  This structure can be used to verify encryption levels, check server certificate and more. Refer to the OpenSSL documentation for information about this structure.

  You must define `USE_SSL` in order to get the prototype for this function. Doing this will also automatically include `ssl.h` from OpenSSL.

- `PQgetssl` Returns the SSL structure used in the connection, or NULL if SSL is not in use.

      SSL *PQgetssl(const PGconn *conn);

  This structure can be used to verify encryption levels, check server certificate and more. Refer to the OpenSSL documentation for information about this structure.

  You must define `USE_SSL` in order to get the prototype for this function. Doing this will also automatically include `ssl.h` from OpenSSL.

Prev | Home | Next
Client Interfaces | Up | Query Execution Functions