Client 1—Connecting to the Server

The libpqxx class library includes a number of public classes you use to interact with the PostgreSQL server. libpqxx also includes a number of private classes you aren't supposed to peek at. All the public components are defined in the pqxx namespace (private classes are defined in a separate namespace). That means you must prefix all libpqxx class names with pqxx:: or include a using namespace pqxx; directive near the top of your source files.

Every libpqxx client includes at least one object of class connection (or a class derived from connection). The connection class, as you might expect, represents a connection to a server. Class connection offers three constructors:

connection();
connection( const std::string & options );
connection( const char options[] );

The first constructor builds a connection using default values and environment variables (see Table 5.2 for details). The second and third constructors let you specify connection properties with a string (either a std::string or a C-style null-terminated string) of the form:

keyword1=value1 keyword2=value2 ...

For example, to connect to a database named accounting on a host named jersey, construct a connection object like this:

connection myConnection( "dbname=accounting host=jersey" );

Or, if you've defined a service named accountingService, (see the section titled “Connection Properties” in Chapter 5, “Introduction to PostgreSQL Programming,” for more information about services), you could create a connection object like this:

connection myConnection( "service=accountingService" );

If you don't supply a full set of connection properties in the constructor, libpqxx will search for the missing values using the environment variables (and hard-wired defaults) shown in Table 5.2.

Listing 10.1 shows a simple client that establishes a connection to a server and then exits.

Listing 10.1. client1.cc
 1 /* client1.cc */
 2
 3 #include <stdlib.h>        // Required for exit()
 4 #include <iostream>      // Required for cerr
 5 #include <pqxx/pqxx>   // libpqxx definitions
 6
 7 using namespace pqxx;
 8 using namespace std;
 9
10 int main( int argc, const char * argv[] )
11 {
12
13   try
14   {
15     connection    myConnection( argv[1] );
16
17     myConnection.activate();
18   }
19   catch( ... )
20   {
21     cerr << "Unknown exception caught" << endl;
22     exit( EXIT_FAILURE );
23   }
24
25   exit( EXIT_SUCCESS );
26
27 }

Any C++ program that uses the libpqxx library should #include <pqxx/pqxx> (see line 5). (Or, if you are a minimalist, you can selectively #include the bits and pieces you need; I'll show you how to find the header files in a moment.) Remember that all the libpqxx public classes are defined in namespace pqxx, so line 8 tells the compiler to search that namespace for unqualified classnames. At line 15 you see a call to the connection constructor. In this case, myConnection is built using the first command-line argument, which should be a connection string such as "service=accountingService".

Contrary to the current version of the libpqxx documentation, the connection constructors do not complete the connection to the server. Instead, the connection object connects to the server (or at least makes the attempt) the first time you use it to interact with the server. If you don't want to wait that long (maybe you want to report a connection error right away), you can call the connection::activate() member function (see line 17) to force the connection attempt.

You've probably noticed that the calls to the connection constructor and connection::activate() are wrapped in a try/catch block. libpqxx follows the STL philosophy that an error should be reported by throwing an exception. See the section “Client 2—Adding Error Checking” later in this chapter for detailed information about the exceptions defined by libpqxx.

Using pqxx-config to Create a Simple Makefile

The libpqxx package includes a handy utility that makes short work of the usually tedious (and error-prone) task of creating Makefiles. The pqxx-config program is currently a shell script and can display the compiler and linker flags required to build a libpqxx client application. pqxx-config is built and installed when you run the configure/make/make install three-step described earlier (see the section titled “Prerequisites” earlier in this chapter). If you chose the default install prefix at that time, pqxx-config ends up in /usr/local/bin; if you chose a different prefix, you'll find pqxx-config in $prefix/bin.

To see a summary of the command-line options supported by pqxx-config, type /usr/local/bin/pqxx-config --help. You'll see a list similar to the following:

$ /usr/local/bin/pqxx-config --help
Usage: pqxx-config [OPTION]

Known values for OPTION are:

  --prefix=DIR          change libpqxx prefix [default /usr/local/pg800b2/]
  --libs                     print library linking information
  --cflags                 print pre-processor and compiler flags
  --help                    display this help and exit
  --version               output version information

To see the preprocess/compiler flags required to build a libpqxx client application, use the command pqxx-config --cflags, like this:

$ /usr/local/bin/pqxx-config --cflags
-I/usr/local/include -I/usr/local/postgresql/include

To see the linker flags required to build a libpqxx client application, use the --libs option:

$ /usr/local/bin/pqxx-config --libs
-L/usr/local/lib -lpqxx -L/usr/local/postgresql/lib -lpq

Don't bother writing down the information displayed by pqxx-config because you can invoke it directly from your Makefile to ensure that the flags are always up-to-date (even if you install a new version of PostgreSQL or libpqxx). Listing 10.2 shows a Makefile that compiles and links the client1.cc client application.

Listing 10.2. libpqxx Client Makefile
1 # Filename: Makefile
2
3 CXXFLAGS  = $(shell /usr/local/bin/pqxx-config --cflags)
4 LDLIBS         = $(shell /usr/local/bin/pqxx-config --libs)
5
6 client1:  client1.cc

Because the GNU make program knows how to build an executable from a .cc (C++) source code file, this Makefile is very simple. Line 3 uses pqxx-config to define the CXXFLAGS variable. make uses CXXFLAGS to build the C++ compiler command line. Line 4 defines LDLIBS, which make uses to build the linker command line. Line 6 simply states that the client1.cc is the one and only prerequisite for client1. After you have the Makefile in place, simply type make client1 to compile and link the client1 program:

$ make client1
g++ -I/usr/local/include -I/usr/local/postgresql/include client1.cc 
    -L/usr/local/lib -lpqxx -L/usr/local/postgresql/lib -lpq

When you run client1, you won't see much in the way of interesting and exciting output. In fact, unless something goes wrong, you won't see any output at all:

$ ./client1 "dbname=test"
$

If client1 can't connect to the database you've specified, you'll see an error message:

$ ./client1 "dbname=neverland"
Unknown exception caught

connection Member Functions

After you have a connection object, you can use a number of member functions to interrogate the status of the connection. The connection::is_open() function returns TRUE if the connection is up and running and FALSE if the connection has been broken or is not yet established. To find the process ID of the server process (see the section titled “LISTEN/NOTIFY” later in this chapter for an example of why you might want to know this), call the connection::backedpid() function. You can also retrieve the database name, username, hostname, port number, and connection options from a connection object using the functions shown here:

const char * connection::dbname();
const char * connection::username();
const char * connection::hostname();
const char * connection::port();
const char * connection::options();
						

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset