/* * This file is a part of Winix * and is not publicly distributed * * Copyright (c) 2010-2013, Tomasz Sowa * All rights reserved. * */ #include #include "dbconn.h" #include "core/log.h" #include "core/error.h" DbConn::DbConn() { pg_conn = 0; } DbConn::~DbConn() { Close(); } PGconn * DbConn::GetPgConn() { return pg_conn; } void DbConn::SetConnParam(const std::string & d, const std::string & u, const std::string & p) { db_database = d; db_user = u; db_pass = p; } void DbConn::Connect() { Close(); conn_info.Clear(); conn_info.SetExtented(false); conn_info << R("dbname=") << db_database << R(" user=") << db_user << R(" password=") << db_pass; pg_conn = PQconnectdb(conn_info.CStr()); // warning! pg_conn can be not null but there cannnot be a connection established // use PQstatus(pg_conn) to check whether the connection works fine } void DbConn::LogConnectionSocket() { log << log2 << "Db: connection to the database works fine" << logend; log << log3 << "Db: connection socket: " << PQsocket(pg_conn) << logend; } void DbConn::WaitForConnection() { if( !pg_conn || PQstatus(pg_conn) != CONNECTION_OK ) { log << log3 << "Db: waiting for the db to be ready...." << logend << logsave; while( !AssertConnection(false, false) ) sleep(5); LogConnectionSocket(); } } void DbConn::Close() { if( pg_conn ) { PQfinish(pg_conn); pg_conn = 0; } } bool DbConn::AssertConnection(bool put_log, bool throw_if_no_connection) { bool was_connection = true; if( !pg_conn ) { was_connection = false; Connect(); } else if( PQstatus(pg_conn) != CONNECTION_OK ) { if( put_log ) log << log2 << "Db: connection to the database is lost, trying to recover" << logend; was_connection = false; PQreset(pg_conn); } if( pg_conn && PQstatus(pg_conn) == CONNECTION_OK ) { if( !was_connection ) { if( put_log ) LogConnectionSocket(); SetDbParameters(); } return true; } else { if( put_log ) log << log1 << "Db: connection to db server cannot be established" << logend; if( throw_if_no_connection ) throw Error(WINIX_ERR_DB_FATAL_ERROR_DURING_CONNECTING); return false; } } void DbConn::SetDbParameters() { if( PQsetClientEncoding(pg_conn, "UTF8") == -1 ) log << log1 << "Db: Can't set the proper client encoding" << logend; }