Page MenuHomec4science

sql_connection_manager.hh
No OneTemporary

File Metadata

Created
Tue, May 21, 06:40

sql_connection_manager.hh

/*
author : Nicolas RICHART <nicolas.richart@epfl.ch>
*/
#ifndef __BLACKDYNAMITE_SQL_CONNECTION_MANAGER_HH__
#define __BLACKDYNAMITE_SQL_CONNECTION_MANAGER_HH__
#include "common_types.hh"
#include <pqxx/pqxx>
namespace BlackDynamite {
class SQLConnectionManager {
public:
SQLConnectionManager(const std::string & dbname,
const std::string & user,
const std::string & host,
const std::string & schema,
const std::string & password) {
if(this->connection_counter == 0) {
std::string options("");
if (this->sql_connection == NULL) {
options += request_increment("dbname", dbname);
options += request_increment("user" , user );
if (password != "")
options += request_increment("password" , password );
if (host != "localhost" && host != "") {
options += request_increment("host", host );
}
try {
this->sql_connection = new pqxx::connection(options);
this->sql_connection->activate();
} catch (std::runtime_error & e) {
FATAL ("Database connection failed : " << e.what());
} catch (std::exception & e) {
FATAL (e.what());
} catch (...) {
FATAL ("Unknown exception during connection to database");
}
}
}
this->connection_counter++;
this->sql_mode = false;
}
virtual ~SQLConnectionManager() {
this->connection_counter--;
if (this->connection_counter == 0) {
delete this->sql_connection;
this->sql_connection = NULL;
}
}
pqxx::connection & getConnection() { return *sql_connection; }
UInt getInstanceCounter() { return connection_counter; }
private:
//! simple function to concatenate the keyword and parameter for forging a request
inline std::string request_increment(std::string keyword, std::string parameter) {
if (!keyword.empty())
return keyword + "=" + parameter + " ";
return "";
}
public:
static pqxx::connection * sql_connection;
static unsigned int connection_counter;
bool sql_mode;
};
}
#endif /* __BLACKDYNAMITE_SQL_CONNECTION_MANAGER_HH__ */

Event Timeline