--- pgAgent-NG/connection.cpp	2013-09-11 11:36:09.184167113 +0200
+++ pgagent/connection.cpp	2013-09-11 12:02:08.411191500 +0200
@@ -11,35 +11,45 @@
 
 #include "pgAgent.h"
 
-DBconn::DBconn(connInfo *cInfo)
+#include <wx/regex.h>
+#include <wx/tokenzr.h>
+
+DBconn *DBconn::primaryConn = NULL;
+wxString DBconn::basicConnectString;
+static wxMutex s_PoolLock;
+
+
+DBconn::DBconn(const wxString &connectString, const wxString &db)
 {
-    inUse = false;
-    next = 0;
-    prev = 0;
-    majorVersion = 0;
-    minorVersion = 0;
-    dbname = cInfo->dbname;
-    connStr = cInfo->getConnectionString();
-    cnInfo = cInfo;
-
-    LogMessage( std::string("DBconn(connInfo *cInfo): ") + connStr, LOG_DEBUG);
-    if (!connStr.empty())
-    {
-        Connect(connStr);
-    } else {
-        LogMessage( std::string("Can not create DB connection: ") + cInfo->getConnectionString(), LOG_ERROR);
-    }
-}
-
-bool DBconn::Connect(const std::string &connectString)
-{
-    LogMessage( std::string("DBconn::Connect - Creating DB connection: ") + connectString, LOG_DEBUG);
-    //wxCharBuffer cstrUTF = connectString.mb_str(wxConvUTF8);
-    conn = PQconnectdb(connectString.c_str());
+	inUse = false;
+	next = 0;
+	prev = 0;
+	majorVersion = 0;
+	minorVersion = 0;
+	dbname = db;
+	connStr = connectString;
+
+	if (connectString.IsEmpty())
+	{
+		// This is a sql call to a local database.
+		// No connection string found. Use basicConnectString.
+		Connect(basicConnectString  + wxT(" dbname=") + dbname);
+	}
+	else
+	{
+		Connect(connectString);
+	}
+}
 
+
+bool DBconn::Connect(const wxString &connectString)
+{
+	LogMessage(wxString::Format(_("Creating DB connection: %s"), connectString.c_str()), LOG_DEBUG);
+	wxCharBuffer cstrUTF = connectString.mb_str(wxConvUTF8);
+	conn = PQconnectdb(cstrUTF);
 	if (PQstatus(conn) != CONNECTION_OK)
 	{
-        lastError = std::string(PQerrorMessage(conn));
+		lastError = wxString::FromAscii(PQerrorMessage(conn));
 		PQfinish(conn);
 		conn = 0;
 	}
@@ -57,53 +67,208 @@
 	}
 }
 
-std::string DBconn::qtDbString(const std::string &value)
+
+wxString DBconn::qtDbString(const wxString &value)
 {
-    std::string result = value;
+	wxString result = value;
 
-    ReplaceString(result, std::string("\\"), std::string("\\\\"));
-    ReplaceString(result, std::string("'"), std::string("''"));
-    result.append(std::string("'"));
+	result.Replace(wxT("\\"), wxT("\\\\"));
+	result.Replace(wxT("'"), wxT("''"));
+	result.Append(wxT("'"));
 
 	if (BackendMinimumVersion(8, 1))
 	{
-        if (result.find_first_of(std::string("\\")))
-            result.insert(0,std::string("E'"));
+		if (result.Contains(wxT("\\")))
+			result.Prepend(wxT("E'"));
 		else
-            result.insert(0, std::string("'"));
+			result.Prepend(wxT("'"));
 	}
 	else
-        result.insert(0, std::string("'"));
+		result.Prepend(wxT("'"));
 
 	return result;
 }
 
+
 bool DBconn::BackendMinimumVersion(int major, int minor)
 {
 	if (!majorVersion)
 	{
-        std::string version = ExecuteScalar(std::string("SELECT version();")) ;
-        sscanf(version.c_str(), "%*s %d.%d", &majorVersion, &minorVersion);
+		wxString version = ExecuteScalar(wxT("SELECT version();")) ;
+		sscanf(version.ToAscii(), "%*s %d.%d", &majorVersion, &minorVersion);
 	}
 	return majorVersion > major || (majorVersion == major && minorVersion >= minor);
 }
 
+
+DBconn *DBconn::InitConnection(const wxString &connectString)
+{
+	wxMutexLocker lock(s_PoolLock);
+
+	basicConnectString = connectString;
+	wxString dbname;
+
+	connInfo cnInfo = connInfo::getConnectionInfo(connectString);
+	if (cnInfo.isValid)
+	{
+		dbname = cnInfo.dbname;
+		basicConnectString = cnInfo.getConnectionString();
+		primaryConn = new DBconn(cnInfo.getConnectionString(), dbname);
+
+		if (!primaryConn)
+			LogMessage(_("Failed to create primary connection!"), LOG_ERROR);
+		primaryConn->dbname = dbname;
+		primaryConn->inUse = true;
+	}
+	else
+	{
+		primaryConn = NULL;
+		LogMessage(wxT("Primary connection string is not valid!"), LOG_ERROR);
+	}
+
+	return primaryConn;
+}
+
+
+DBconn *DBconn::Get(const wxString &connStr, const wxString &db)
+{
+	if (db.IsEmpty() && connStr.IsEmpty())
+	{
+		LogMessage(_("Cannot allocate connection - no database or connection string specified!"), LOG_WARNING);
+		return NULL;
+	}
+
+	wxMutexLocker lock(s_PoolLock);
+
+	DBconn *thisConn = primaryConn, *lastConn;
+
+	// find an existing connection
+	do
+	{
+		if (thisConn && ((!db.IsEmpty() && db == thisConn->dbname && connStr.IsEmpty()) || (!connStr.IsEmpty() && connStr == thisConn->connStr)) && !thisConn->inUse)
+		{
+			LogMessage(wxString::Format(_("Allocating existing connection to database %s"), thisConn->dbname.c_str()), LOG_DEBUG);
+			thisConn->inUse = true;
+			return thisConn;
+		}
+
+		lastConn = thisConn;
+		thisConn = thisConn->next;
+
+	}
+	while (thisConn != 0);
+
+
+	// No suitable connection was found, so create a new one.
+	DBconn *newConn = NULL;
+	newConn = new DBconn(connStr, db);
+
+	if (newConn->conn)
+	{
+		LogMessage(wxString::Format(_("Allocating new connection to database %s"), newConn->dbname.c_str()), LOG_DEBUG);
+		newConn->inUse = true;
+		newConn->prev = lastConn;
+		lastConn->next = newConn;
+	}
+	else
+	{
+		wxString warnMsg;
+		if (connStr.IsEmpty())
+			warnMsg = wxString::Format(_("Failed to create new connection to database '%s':'%s'"),
+			                           db.c_str(), newConn->GetLastError().c_str());
+		else
+			warnMsg = wxString::Format(_("Failed to create new connection for connection string '%s':%s"),
+			                           connStr.c_str(), newConn->GetLastError().c_str());
+		LogMessage(warnMsg, LOG_STARTUP);
+		return NULL;
+	}
+
+	return newConn;
+}
+
+
 void DBconn::Return()
 {
-    // Cleanup
-    this->ExecuteVoid(std::string("RESET ALL"));
-    this->lastError.clear();
+	wxMutexLocker lock(s_PoolLock);
+
+	// Cleanup
+	this->ExecuteVoid(wxT("RESET ALL"));
+	this->lastError.Empty();
 
-    LogMessage(std::string("Returning connection to database ") + dbname, LOG_DEBUG);
+	LogMessage(wxString::Format(_("Returning connection to database %s"), dbname.c_str()), LOG_DEBUG);
 	inUse = false;
 }
 
-connInfo* DBconn::getConnInfo()
+
+void DBconn::ClearConnections(bool all)
 {
-    return this->cnInfo;
+	wxMutexLocker lock(s_PoolLock);
+
+	if (all)
+		LogMessage(_("Clearing all connections"), LOG_DEBUG);
+	else
+		LogMessage(_("Clearing inactive connections"), LOG_DEBUG);
+
+	DBconn *thisConn = primaryConn, *deleteConn;
+	int total = 0, free = 0, deleted = 0;
+
+	if (thisConn)
+	{
+
+		total++;
+
+		// Find the last connection
+		while (thisConn->next != 0)
+		{
+			total++;
+
+			if (!thisConn->inUse)
+				free++;
+
+			thisConn = thisConn->next;
+		}
+		if (!thisConn->inUse)
+			free++;
+
+		// Delete connections as required
+		// If a connection is not in use, delete it, and reset the next and previous
+		// pointers appropriately. If it is in use, don't touch it.
+		while (thisConn->prev != 0)
+		{
+			if ((!thisConn->inUse) || all)
+			{
+				deleteConn = thisConn;
+				thisConn = deleteConn->prev;
+				thisConn->next = deleteConn->next;
+				if (deleteConn->next)
+					deleteConn->next->prev = deleteConn->prev;
+				delete deleteConn;
+				deleted++;
+			}
+			else
+			{
+				thisConn = thisConn->prev;
+			}
+		}
+
+		if (all)
+		{
+			delete thisConn;
+			deleted++;
+		}
+
+		wxString tmp;
+		tmp.Printf(_("Connection stats: total - %d, free - %d, deleted - %d"), total, free, deleted);
+		LogMessage(tmp, LOG_DEBUG);
+
+	}
+	else
+		LogMessage(_("No connections found!"), LOG_DEBUG);
+
 }
 
-DBresult *DBconn::Execute(const std::string &query)
+
+DBresult *DBconn::Execute(const wxString &query)
 {
 	DBresult *res = new DBresult(this, query);
 	if (!res->IsValid())
@@ -117,23 +282,23 @@
 }
 
 
-std::string DBconn::ExecuteScalar(const std::string &query)
+wxString DBconn::ExecuteScalar(const wxString &query)
 {
-//	int rows = -1;
+	int rows = -1;
 	DBresult *res = Execute(query);
-    std::string data;
+	wxString data;
 	if (res)
 	{
 		data = res->GetString(0);
-        //rows = res->RowsAffected();
+		rows = res->RowsAffected();
 		delete res;
 		return data;
 	}
-    return std::string("");
+	return wxEmptyString;
 }
 
 
-int DBconn::ExecuteVoid(const std::string &query)
+int DBconn::ExecuteVoid(const wxString &query)
 {
 	int rows = -1;
 	DBresult *res = Execute(query);
@@ -146,66 +311,75 @@
 }
 
 
-std::string DBconn::GetLastError()
+wxString DBconn::GetLastError()
 {
 	// Return the last error message, minus any trailing line ends
-    return rtrim(lastError);
+	if (lastError.substr(lastError.length() - 2, 2) == wxT("\r\n")) // DOS
+		return lastError.substr(0, lastError.length() - 2);
+	else if (lastError.substr(lastError.length() - 1, 1) == wxT("\n")) // Unix
+		return lastError.substr(0, lastError.length() - 1);
+	else if (lastError.substr(lastError.length() - 1, 1) == wxT("\r")) // Mac
+		return lastError.substr(0, lastError.length() - 1);
+	else
+		return lastError;
 }
 
 ///////////////////////////////////////////////////////7
 
-DBresult::DBresult(DBconn *conn, const std::string &query)
+DBresult::DBresult(DBconn *conn, const wxString &query)
 {
-    //wxCharBuffer cstrUTF = query.mb_str(wxConvUTF8);
-    result = PQexec(conn->conn, query.c_str());
+	wxCharBuffer cstrUTF = query.mb_str(wxConvUTF8);
+	result = PQexec(conn->conn, cstrUTF);
 	currentRow = 0;
 	maxRows = 0;
 
 	if (result)
 	{
 		int rc = PQresultStatus(result);
+		conn->SetLastResult(rc);
 		if (rc == PGRES_TUPLES_OK)
 			maxRows = PQntuples(result);
 		else if (rc != PGRES_COMMAND_OK)
 		{
-            conn->lastError = std::string(PQerrorMessage(conn->conn));
-            LogMessage(("Query error: ") + conn->lastError, LOG_WARNING);
+			conn->lastError = wxString::FromAscii(PQerrorMessage(conn->conn));
+			LogMessage(wxT("Query error: ") + conn->lastError, LOG_WARNING);
 			PQclear(result);
 			result = 0;
 		}
 	}
 	else
-        conn->lastError = std::string(PQerrorMessage(conn->conn));
-    std::ostringstream oss;
-    oss << "Query: " << query << " currentRow: " << currentRow << " maxRow: " << maxRows;
-    LogMessage(oss.str(), LOG_DEBUG);
+		conn->lastError = wxString::FromAscii(PQerrorMessage(conn->conn));
+
 }
 
+
 DBresult::~DBresult()
 {
 	if (result)
 		PQclear(result);
 }
 
-std::string DBresult::GetString(int col) const
+
+wxString DBresult::GetString(int col) const
 {
-    std::string str;
+	wxString str;
 
 	if (result && currentRow < maxRows && col >= 0)
 	{
-        str = std::string(PQgetvalue(result, currentRow, col));
+		str = wxString::FromAscii(PQgetvalue(result, currentRow, col));
 	}
 	return str;
 }
 
-std::string DBresult::GetString(const std::string &colname) const
+
+wxString DBresult::GetString(const wxString &colname) const
 {
-    //wxCharBuffer cstrUTF = colname.mb_str(wxConvUTF8);
-    int col = PQfnumber(result, colname.c_str());
+	wxCharBuffer cstrUTF = colname.mb_str(wxConvUTF8);
+	int col = PQfnumber(result, cstrUTF);
 	if (col < 0)
 	{
 		// fatal: not found
-        return std::string("");
+		return wxT("");
 	}
 	return GetString(col);
 }
@@ -214,46 +388,41 @@
 
 bool connInfo::IsValidIP()
 {
-    if (host.empty())
+	if (host.IsEmpty())
 		return false;
 
 	// check for IPv4 format
-    std::string token;
-
-    std::istringstream tkip(host);
+	wxStringTokenizer tkip4(host, wxT("."));
 	int count = 0;
 
-    // Unix Domain Sockets a la '/tmp/._socket_5432'
-    if( host.find_first_of('/') != std::string::npos) return false;
-
-    while (std::getline(tkip, token, '.'))
+	while (tkip4.HasMoreTokens())
 	{
 		unsigned long val = 0;
-        std::istringstream conv(token);
-        if (!(conv >> val)) 	break;
-
-        if (count == 0 || count == 3) {
-            if (val > 0 && val < 255)  	count++;
-            else break;
-        } else {
-            //if (val >= 0 && val < 255) count++;
-            if (val < 255) count++;
-            else break;
-        }
+		if (!tkip4.GetNextToken().ToULong(&val))
+			break;
+		if (count == 0 || count == 3)
+			if (val > 0 && val < 255)
+				count++;
+			else
+				break;
+		else if (val >= 0 && val < 255)
+			count++;
+		else
+			break;
 	}
 
 	if (count == 4)
 		return true;
 
 	// check for IPv6 format
+	wxStringTokenizer tkip6(host, wxT(":"));
 	count = 0;
 
-    while (std::getline(tkip, token, ':'))
+	while (tkip6.HasMoreTokens())
 	{
-// TODO make it better
-//		unsigned long val = 0;
-        //std::string strVal = tkip6.GetNextToken();
-        if (token.size() > 4 ) //|| !strVal.ToULong(&val, 16))
+		unsigned long val = 0;
+		wxString strVal = tkip6.GetNextToken();
+		if (strVal.Length() > 4 || !strVal.ToULong(&val, 16))
 			return false;
 		count++;
 	}
@@ -265,159 +434,122 @@
 	return false;
 }
 
-std::string connInfo::getConnectionString()
+
+wxString connInfo::getConnectionString()
 {
-    std::ostringstream connStr, str_port, str_connection_timeout;
+	wxString connStr;
 
 	// Check if it has valid connection info
-    //if (!isValid) return connStr.str();
+	if (!isValid)
+		return connStr;
 
 	// User
-    connStr << "user=" << user;
+	connStr = wxT("user=") + user;
 
-    // Port as INT ??? Why
-    if (port != "0")
+	// Port
+	if (port != 0)
 	{
-        str_port << port;
-        connStr <<" port=" << port;
+		wxString portStr;
+		portStr.Printf(wxT("%ld"), port);
+		connStr += wxT(" port=") + portStr;
 	}
 
 	// host or hostaddr
-    if (!host.empty()) {
-        if (IsValidIP())   {
-            connStr << " hostaddr=" << host;
-            //LogMessage(std::string("     ValidIP      : "), LOG_DEBUG);
-        } else {
-            connStr << " host=" << host;
-            //LogMessage(std::string("    NON ValidIP   : "), LOG_DEBUG);
-        }
-    }
+	if (!host.IsEmpty())
+		if (IsValidIP())
+			connStr += wxT(" hostaddr=") + host;
+		else
+			connStr += wxT(" host=") + host;
+
 	// connection timeout
-    if (connection_timeout != "0")
+	if (connection_timeout != 0)
 	{
-        str_connection_timeout << connection_timeout;
-        connStr << " connection_timeout=" << connection_timeout;
+		wxString val;
+		val.Printf(wxT("%ld"), connection_timeout);
+		connStr += wxT(" connection_timeout=") + val;
 	}
 
 	// password
-    if (!password.empty())
-        connStr << " password=" << password;
+	if (!password.IsEmpty())
+		connStr += wxT(" password=") + password;
+
+	if (!dbname.IsEmpty())
+		connStr += wxT(" dbname=") + dbname;
 
-    if (!dbname.empty())
-        connStr << " dbname=" << dbname;
-/*
-    LogMessage(std::string("Connection Information:"), LOG_DEBUG);
-    LogMessage(std::string("     user         : ") + user, LOG_DEBUG);
-    LogMessage(std::string("     port         : ") + str_port.str(), LOG_DEBUG);
-    LogMessage(std::string("     host         : ") + host, LOG_DEBUG);
-    LogMessage(std::string("     hostaddr     : ") + hostaddr, LOG_DEBUG);
-    LogMessage(std::string("     dbname       : ") + dbname, LOG_DEBUG);
-    LogMessage(std::string("     password     : ") + password, LOG_DEBUG);
-    LogMessage(std::string("     conn timeout : ") + str_connection_timeout.str(), LOG_DEBUG);
-    LogMessage(std::string("     conn string  : ") + connStr.str(), LOG_DEBUG);
-*/
-    return connStr.str();
-}
-
-bool connInfo::setConnectionString(std::string str_conn)
-{
-    std::string key;
-    std::string val;
-    bool ret = false, valtrim = false;
-    std::size_t anf;
-
-    // example key-value connect string: host = AAA password = "dasd d asd as" password = 'a aa' user= thst
-    // parse from left to right
-    std::size_t pos = str_conn.find_first_of('=');
-    while(pos != std::string::npos) {
-
-        // extract key part
-        key = str_conn.substr(0, pos);
-        trim(key);
-        //LogMessage("KEY: "+key,LOG_DEBUG);
-        // cut key part off from connect string
-        str_conn = str_conn.substr(pos+1, str_conn.size()-pos-1);
-        ltrim(str_conn);
-        //LogMessage("CS: "+str_conn,LOG_DEBUG);
-        if(str_conn[0] == '"') {
-            pos = str_conn.find_first_of('"',1);
-            anf = 1;
-            valtrim = false;
-        } else if(str_conn[0] == '\'') {
-            pos = str_conn.find_first_of("'",1);
-            anf = 1;
-            valtrim = false;
-        } else {
-            pos = str_conn.find_first_of(" ",0);
-            anf = 0;
-            valtrim = true;
-        }
-        // extract value part
-        val = str_conn.substr(anf, pos-anf);
-        if(valtrim) trim(val);
-        //LogMessage("VAL: "+val,LOG_DEBUG);
-        // cut val part off from connect string
-        str_conn = str_conn.substr(pos+1, str_conn.size()-pos-1);
-        ltrim(str_conn);
-        //LogMessage("CS: "+str_conn,LOG_DEBUG);
-        // set next position
-        pos = str_conn.find_first_of('=');
-
-        // set option
-        ret = setKeyValue(key,val);
-    }
-    return ret;
-}
-
-bool connInfo::setKeyValue(std::string key, std::string val)
-{
-    trim(key);
-    trim(val);
-
-    if (std::string("user") == key) {
-        user = val;
-        return true;
-    } else if(std::string("host") == key) {
-        host = val;
-        return true;
-    } else if(std::string("hostAddr") == key) {
-        hostaddr = val;
-        return true;
-    } else if(std::string("port") == key) {
-        port = val;
-        return true;
-    } else if ((std::string("password")) == key) {
-        password = val;
-        return true;
-    } else if (std::string("connection_timeout") == key) {
-        connection_timeout = val;
-        return true;
-    }
-    else if(std::string("dbname") == key) {
-        dbname = val;
-        return true;
-    }
-    return false;
+	LogMessage(wxString::Format(_("Connection Information:")), LOG_DEBUG);
+	LogMessage(wxString::Format(_("     user         : %s"), user.c_str()), LOG_DEBUG);
+	LogMessage(wxString::Format(_("     port         : %ld"), port), LOG_DEBUG);
+	LogMessage(wxString::Format(_("     host         : %s"), host.c_str()), LOG_DEBUG);
+	LogMessage(wxString::Format(_("     dbname       : %s"), dbname.c_str()), LOG_DEBUG);
+	LogMessage(wxString::Format(_("     password     : %s"), password.c_str()), LOG_DEBUG);
+	LogMessage(wxString::Format(_("     conn timeout : %ld"), connection_timeout), LOG_DEBUG);
+
+	return connStr;
 }
 
-connInfo connInfo::getConnectionInfo()
+
+connInfo connInfo::getConnectionInfo(wxString connStr)
 {
 	connInfo cnInfo;
 
-    cnInfo.user = user;
-    cnInfo.host = host;
-    cnInfo.password = password;
-    cnInfo.dbname = dbname;
-    cnInfo.host = host;
-    cnInfo.hostaddr = hostaddr;
+	wxRegEx propertyExp;
+
+	// Remove the white-space(s) to match the following format
+	// i.e. prop=value
+	bool res = propertyExp.Compile(wxT("(([ ]*[\t]*)+)="));
+
+	propertyExp.ReplaceAll(&connStr, wxT("="));
+
+	res = propertyExp.Compile(wxT("=(([ ]*[\t]*)+)"));
+	propertyExp.ReplaceAll(&connStr, wxT("="));
+
+	// Seperate all the prop=value patterns
+	wxArrayString tokens = wxStringTokenize(connStr, wxT("\t \n\r"));
+
+	unsigned int index = 0;
+	while (index < tokens.Count())
+	{
+		wxString prop, value;
+
+		wxArrayString pairs = wxStringTokenize(tokens[index++], wxT("="));
+
+		if (pairs.GetCount() != 2)
+			return cnInfo;
+
+		prop = pairs[0];
+		value = pairs[1];
+
+		if (prop.CmpNoCase(wxT("user")) == 0)
+			cnInfo.user = value;
+		else if (prop.CmpNoCase(wxT("host")) == 0 || prop.CmpNoCase(wxT("hostAddr")) == 0)
+			cnInfo.host = value;
+		else if (prop.CmpNoCase(wxT("port")) == 0)
+		{
+			if (!value.ToULong(&cnInfo.port))
+				// port must be an unsigned integer
+				return cnInfo;
+		}
+		else if (prop.CmpNoCase(wxT("password")) == 0)
+			cnInfo.password = value;
+		else if (prop.CmpNoCase(wxT("connection_timeout")) == 0)
+		{
+			if (!value.ToULong(&cnInfo.connection_timeout))
+				// connection timeout must be an unsigned interger
+				return cnInfo;
+		}
+		else if (prop.CmpNoCase(wxT("dbname")) == 0)
+			cnInfo.dbname = value;
+		else
+			// Not valid property found
+			return cnInfo;
+	}
 
 	// If user, dbname & host all are blank than we will consider this an invalid connection string
-    if (cnInfo.user.empty() && cnInfo.dbname.empty() && cnInfo.host.empty())
-        cnInfo.isValid = false;
+	if (cnInfo.user.IsEmpty() && cnInfo.dbname.IsEmpty() && cnInfo.host.IsEmpty())
+		cnInfo.isValid = false;
 	else
-        cnInfo.isValid = true;
+		cnInfo.isValid = true;
 
 	return cnInfo;
 }
 
-
