/*
** SellaNMS
** $Id: connection_pool.h,v 1.10 2006/01/24 07:08:10 sella Exp $
** Copyright (c) 2001-2004 Digital Genesis Software, LLC. All Rights Reserved.
** Released under the GPL Version 2 License.
** http://www.digitalgenesis.com
*/

#ifndef __DGS_LIBS_STORAGE_CONNECTION_POOL_H
#define __DGS_LIBS_STORAGE_CONNECTION_POOL_H

#ifdef HAVE_CONFIG_H
	#include "config.h"
#endif

#include "defaults.h"
#include "configuration/confignode.h"
#include <dbi/dbi.h>
#include <pthread.h>
#include <stl/slist>

#define LIBS_STORAGE_CONNECTIONPOOL_TIMEOUT_DEF 300
#define LIBS_STORAGE_CONNECTIONPOOL_TIMEOUT_MIN 1
#define LIBS_STORAGE_CONNECTIONPOOL_TIMEOUT_MAX 21600
#define LIBS_STORAGE_CONNECTIONPOOL_TRIMDELAY_DEF 30
#define LIBS_STORAGE_CONNECTIONPOOL_TRIMDELAY_MIN 1
#define LIBS_STORAGE_CONNECTIONPOOL_TRIMDELAY_MAX 3600
#define LIBS_STORAGE_CONNECTIONPOOL_MINSIZE_DEF 2
#define LIBS_STORAGE_CONNECTIONPOOL_MINSIZE_MIN 1
#define LIBS_STORAGE_CONNECTIONPOOL_MINSIZE_MAX 256
#define LIBS_STORAGE_CONNECTIONPOOL_MAXSIZE_DEF 32
#define LIBS_STORAGE_CONNECTIONPOOL_MAXSIZE_MAX 256

typedef struct conn_pool_t {
	slist<dbi_conn> list;
	pthread_mutex_t* mutex;
	time_t last; // when the connection was last used.
	bool exclusive; // true = owner requested exclusive lock.
	unsigned int users; //Count of current users.
	bool failed; // conneciton believed failed.
};

class ConnectionPool {
	public:
		ConnectionPool();
		ConnectionPool(ConnectionPool const &);
		~ConnectionPool();

		RESULT setConfig(ConfigNode &config);
		bool isConfigured();
		RESULT requestConnection(conn_pool_t *& connection, bool exclusive);
		RESULT releaseConnection(conn_pool_t *& connection);

	protected:
		RESULT initialize();
		void setDebug(bool debug = true);
		void closeAllConnections();
		RESULT connect(conn_pool_t *connections);
		void disconnect(conn_pool_t *connections);
		void printOptions(dbi_conn conn);

	private:
		ConfigNode config;
		bool debug;
		unsigned long timeout;
		unsigned long trimDelay;
		unsigned long maxSize;
		unsigned long minSize;

		slist<conn_pool_t> pool;
};

#endif

/*
** Local Variables:
** c-basic-offset: 3
** tab-width: 3
** End:
** vim:
** vim: noet ts=3 sw=3
*/
