Macros | Typedefs | Functions | Variables
ConnectionPool.h File Reference

Detailed Description

A ConnectionPool represent a database connection pool.

A connection pool can be used to get a connection to a database and execute statements. This class opens a number of database connections and allow callers to obtain and use a database connection in a reentrant manner. Applications can instantiate as many ConnectionPool objects as needed and against as many different database systems as needed. The following diagram gives an overview of the library's components and their method-associations:

The method ConnectionPool_getConnection() is used to obtain a new connection from the pool. If there are no connections available a new connection is created and returned. If the pool has already handed out maxConnections Connections, the next call to ConnectionPool_getConnection() will return NULL. Use Connection_close() to return a connection to the pool so it can be reused.

A connection pool is created default with 5 initial connections and with 20 maximum connections. These values can be changed by the property methods ConnectionPool_setInitialConnections() and ConnectionPool_setMaxConnections().

Supported database systems:

This library may be built with support for many different database systems. To test if a particular system is supported use the method Connection_isSupported().

Life-cycle methods:

Clients should call ConnectionPool_start() to establish the connection pool against the database server before using the pool. To shutdown connections from the database server use ConnectionPool_stop(). Set preferred properties before calling ConnectionPool_start(). Some properties can also be changed dynamically after the pool was started such as changing the maximum number of connections or the number of initial connections. Changing and tuning these properties at runtime is most useful if the pool was started with a reaper-thread (see below) since the reaper dynamically change the size of the pool

Connection URL:

The URL given to a Connection Pool at creation time specify a database connection on the standard URL format. The format of the connection URL is defined as:

database://[user:password@][host][:port]/database[?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...

The property names user and password are always recognized and specify how to login to the database. Other properties depends on the database server in question. User name and password can alternatively be specified in the auth-part of the URL. If port number is omitted, the default port number for the database server is used.

MySQL:

Here is an example on how to connect to a MySQL database server:

mysql://localhost:3306/test?user=root&password=swordfish

In this case the username, root and password, swordfish are specified as properties to the URL. An alternative is to use the auth-part of the URL to specify authentication information:

mysql://root:swordfish@localhost:3306/test

See mysql options for all properties that can be set for a mysql connection URL.

SQLite:

For a SQLite database the connection URL should simply specify a database file, since a SQLite database is just a file in the filesystem. SQLite uses pragma commands for performance tuning and other special purpose database commands. Pragma syntax on the form, name=value can be added as properties to the URL and will be set when the Connection is created. In addition to pragmas, the following properties are supported:

An URL for connecting to a SQLite database might look like:

sqlite:///var/sqlite/test.db?synchronous=normal&heap_limit=8000&foreign_keys=on

PostgreSQL:

The URL for connecting to a PostgreSQL database server might look like:

postgresql://localhost:5432/test?user=root&password=swordfish

As with the MySQL URL, the username and password are specified as properties to the URL. Likewise, the auth-part of the URL can be used instead to specify the username and the password:

postgresql://root:swordfish@localhost/test?use-ssl=true

In this example we have also omitted the port number to the server, in which case the default port number, 5432, for PostgreSQL is used. In addition we have added an extra parameter to the URL, so connection to the server is done over a secure SSL connection.

See postgresql options for all properties that can be set for a postgresql connection URL.

Oracle:

The URL for connecting to an Oracle database server might look like:

oracle://localhost:1521/test?user=scott&password=tiger

The auth-part of the URL can be used instead to specify the username and the password. In addition, you may specify a service name in the URL instead if you have setup a tnsnames.ora configuration file.

oracle:///servicename?user=scott&password=tiger

Example:

To obtain a connection pool for a MySQL database, the code below can be used. The exact same code can be used for PostgreSQL, SQLite and Oracle, the only change needed is to modify the Connection URL. Here we connect to the database test on localhost and start the pool with the default 5 initial connections.

URL_T url = URL_new("mysql://localhost/test?user=root&password=swordfish");
ConnectionPool_T pool = ConnectionPool_new(url);
ConnectionPool_start(pool);
[..]
Connection_T con = ConnectionPool_getConnection(pool);
ResultSet_T result = Connection_executeQuery(con, "select id, name, image from employee where salary>%d", anumber);
while (ResultSet_next(result)) 
{
     int id = ResultSet_getInt(result, 1);
     const char *name = ResultSet_getString(result, 2);
     int blobSize;
     const void *image = ResultSet_getBlob(result, 3, &blobSize);
     [..]
}
Connection_close(con);
[..]
ConnectionPool_free(&pool);
URL_free(&url);

Optimizing the pool size:

The pool can be setup to dynamically change the number of active Connections in the pool depending on the load. A single reaper thread can be activated at startup to sweep through the pool at a regular interval and close Connections that have been inactive for a specified time or for some reasons no longer respond. Only inactive Connections will be closed and no more than the initial number of Connections the pool was started with are closed. The property method, ConnectionPool_setReaper(), is used to specify that a reaper thread should be started when the pool is started. This method must be called before ConnectionPool_start(), otherwise the pool will not start with a reaper thread.

Clients can also call the method, ConnectionPool_reapConnections(), to bonsai the pool directly if the reaper thread is not activated.

It is recommended to start the pool with a reaper-thread, especially if the pool maintains TCP/IP Connections.

Realtime inspection:

Two methods can be used to inspect the pool at runtime. The method ConnectionPool_size() returns the number of connections in the pool, that is, both active and inactive connections. The method ConnectionPool_active() returns the number of active connections, i.e. those connections in current use by your application.

This ConnectionPool is thread-safe.

See Also
Connection.h ResultSet.h URL.h PreparedStatement.h SQLException.h

Macros

#define T   ConnectionPool_T
 

Typedefs

typedef struct ConnectionPool_S * T
 

Functions

T ConnectionPool_new (URL_T url)
 Create a new ConnectionPool. More...
 
void ConnectionPool_free (T *P)
 Disconnect and destroy the pool and release allocated resources. More...
 
void ConnectionPool_start (T P)
 Prepare for the beginning of active use of this component. More...
 
void ConnectionPool_stop (T P)
 Gracefully terminate the active use of the public methods of this component. More...
 
Connection_T ConnectionPool_getConnection (T P)
 Get a connection from the pool. More...
 
void ConnectionPool_returnConnection (T P, Connection_T connection)
 Returns a connection to the pool. More...
 
int ConnectionPool_reapConnections (T P)
 Close all inactive Connections in the pool, down to initial connections. More...
 
Properties
URL_T ConnectionPool_getURL (T P)
 Returns this Connection Pool URL. More...
 
void ConnectionPool_setInitialConnections (T P, int connections)
 Set the number of initial connections to start the pool with. More...
 
int ConnectionPool_getInitialConnections (T P)
 Get the number of initial connections to start the pool with. More...
 
void ConnectionPool_setMaxConnections (T P, int maxConnections)
 Set the maximum number of connections this connection pool will create. More...
 
int ConnectionPool_getMaxConnections (T P)
 Get the maximum number of connections this Connection pool will create. More...
 
void ConnectionPool_setConnectionTimeout (T P, int connectionTimeout)
 Set a Connection inactive timeout value in seconds. More...
 
int ConnectionPool_getConnectionTimeout (T P)
 Returns the connection timeout value in seconds. More...
 
void ConnectionPool_setAbortHandler (T P, void(*abortHandler)(const char *error))
 Set the function to call if a fatal error occurs in the library. More...
 
void ConnectionPool_setReaper (T P, int sweepInterval)
 Specify that a reaper thread should be used by the pool. More...
 
int ConnectionPool_size (T P)
 Returns the current number of connections in the pool. More...
 
int ConnectionPool_active (T P)
 Returns the number of active connections in the pool. More...
 
Class methods
const char * ConnectionPool_version (void)
 Class method, returns this library version information More...
 

Variables

int ZBDEBUG
 Library Debug flag. More...
 

Macro Definition Documentation

#define T   ConnectionPool_T

Typedef Documentation

typedef struct ConnectionPool_S* T

Function Documentation

T ConnectionPool_new ( URL_T  url)

Create a new ConnectionPool.

The pool is created with default 5 initial connections. Maximum connections is set to 20. Property methods in this interface can be used to change the default values.

Parameters
urlThe database connection url. It is a checked runtime error for the url parameter to be NULL.
Returns
A new ConnectionPool object
See Also
URL.h
void ConnectionPool_free ( T P)

Disconnect and destroy the pool and release allocated resources.

Parameters
PA ConnectionPool object reference
URL_T ConnectionPool_getURL ( T  P)

Returns this Connection Pool URL.

Parameters
PA ConnectionPool object
Returns
This Connection Pool URL
See Also
URL.h
void ConnectionPool_setInitialConnections ( T  P,
int  connections 
)

Set the number of initial connections to start the pool with.

Parameters
PA ConnectionPool object
connectionsThe number of initial pool connections
See Also
Connection.h
int ConnectionPool_getInitialConnections ( T  P)

Get the number of initial connections to start the pool with.

Parameters
PA ConnectionPool object
Returns
The number of initial pool connections
See Also
Connection.h
void ConnectionPool_setMaxConnections ( T  P,
int  maxConnections 
)

Set the maximum number of connections this connection pool will create.

If max connections has been served, ConnectionPool_getConnection() will return NULL on the next call.

Parameters
PA ConnectionPool object
maxConnectionsThe maximum number of connections this connection pool will create. It is a checked runtime error for maxConnections to be less than initialConnections.
See Also
Connection.h
int ConnectionPool_getMaxConnections ( T  P)

Get the maximum number of connections this Connection pool will create.

Parameters
PA ConnectionPool object
Returns
The maximum number of connections this connection pool will create.
See Also
Connection.h
void ConnectionPool_setConnectionTimeout ( T  P,
int  connectionTimeout 
)

Set a Connection inactive timeout value in seconds.

The method, ConnectionPool_reapConnections(), if called will close inactive Connections in the pool which has not been in use since connectionTimeout seconds. Default connectionTimeout is 30 seconds. The reaper thread if in use, see ConnectionPool_setReaper(), also use this value when closing inactive Connections. It is a checked runtime error for connectionTimeout to be less than, or equal to zero.

Parameters
PA ConnectionPool object
connectionTimeoutThe number of seconds a Connection can be inactive, i.e. not in use, before the reaper close the Connection. (value > 0)
int ConnectionPool_getConnectionTimeout ( T  P)

Returns the connection timeout value in seconds.

Parameters
PA ConnectionPool object
Returns
The time an inactive Connection may live before it is closed
void ConnectionPool_setAbortHandler ( T  P,
void(*)(const char *error)  abortHandler 
)

Set the function to call if a fatal error occurs in the library.

In practice this means Out-Of-Memory errors or uncatched exceptions. Clients may optionally provide this function. If not provided the library will call abort(3) upon encountering a fatal error if ZBDEBUG is set, otherwise exit(1) is called. This method provide clients with means to close down execution gracefully. It is an unchecked runtime error to continue using the library after the abortHandler was called.

Parameters
PA ConnectionPool object
abortHandlerThe handler function to call should a fatal error occur during processing. An explanatory error message is passed to the handler function in the string error
See Also
Exception.h
void ConnectionPool_setReaper ( T  P,
int  sweepInterval 
)

Specify that a reaper thread should be used by the pool.

This thread will close all inactive Connections in the pool, down to initial connections. An inactive Connection is closed if and only if its connectionTimeout has expired or if the Connection failed the ping test. Active Connections, that is, connections in current use by your application are never closed by this thread. This method sets the reaper thread sweep property, but does not start the thread. This is done in ConnectionPool_start(). So, if the pool should use a reaper thread, remember to call this method before ConnectionPool_start(). It is a checked runtime error for sweepInterval to be less than, or equal to zero.

Parameters
PA ConnectionPool object
sweepIntervalNumber of seconds between sweeps of the reaper thread (value > 0)
int ConnectionPool_size ( T  P)

Returns the current number of connections in the pool.

The number of both active and inactive connections are returned.

Parameters
PA ConnectionPool object
Returns
The number of connections in the pool
int ConnectionPool_active ( T  P)

Returns the number of active connections in the pool.

I.e. connections in use by clients.

Parameters
PA ConnectionPool object
Returns
The number of active connections in the pool
void ConnectionPool_start ( T  P)

Prepare for the beginning of active use of this component.

This method must be called before the pool is used and will connect to the database server and create the initial connections for the pool. This method will also start the reaper thread if specified via ConnectionPool_setReaper().

Parameters
PA ConnectionPool object
Exceptions
SQLExceptionIf a database error occurs.
See Also
SQLException.h
void ConnectionPool_stop ( T  P)

Gracefully terminate the active use of the public methods of this component.

This method should be the last one called on a given instance of this component. Calling this method close down all connections in the pool, disconnect the pool from the database server and stop the reaper thread if it was started.

Parameters
PA ConnectionPool object
Connection_T ConnectionPool_getConnection ( T  P)

Get a connection from the pool.

Parameters
PA ConnectionPool object
Returns
A connection from the pool or NULL if maxConnection is reached
See Also
Connection.h
void ConnectionPool_returnConnection ( T  P,
Connection_T  connection 
)

Returns a connection to the pool.

The same as calling Connection_close()

Parameters
PA ConnectionPool object
connectionA Connection object
See Also
Connection.h
int ConnectionPool_reapConnections ( T  P)

Close all inactive Connections in the pool, down to initial connections.

Inactive Connection are closed if and only if its connectionTimeout has expired or if the Connection failed the ping test against the database. Active Connections are not closed by this method.

Parameters
PA ConnectionPool object
Returns
The number of Connections that was closed
const char* ConnectionPool_version ( void  )

Class method, returns this library version information

Returns
Library version information

Variable Documentation

int ZBDEBUG

Library Debug flag.

If set to true, emit debug output

Copyright © Tildeslash Ltd. All rights reserved.