Ejemplo n.º 1
0
/* check the PQStatus and try to 'select 1' to confirm good connection */
bool
is_pgup(PGconn *conn, int timeout)
{
	char		sqlquery[QUERY_STR_LEN];

	/* Check the connection status twice in case it changes after reset */
	bool		twice = false;

	/* Check the connection status twice in case it changes after reset */
	for (;;)
	{
		if (PQstatus(conn) != CONNECTION_OK)
		{
			if (twice)
				return false;
			PQreset(conn);		/* reconnect */
			twice = true;
		}
		else
		{
			/*
			 * Send a SELECT 1 just to check if the connection is OK
			 */
			if (!cancel_query(conn, timeout))
				goto failed;
			if (wait_connection_availability(conn, timeout) != 1)
				goto failed;

			sqlquery_snprintf(sqlquery, "SELECT 1");
			if (PQsendQuery(conn, sqlquery) == 0)
			{
				log_warning(_("PQsendQuery: Query could not be sent to primary. %s\n"),
							PQerrorMessage(conn));
				goto failed;
			}
			if (wait_connection_availability(conn, timeout) != 1)
				goto failed;

			break;

	failed:

			/*
			 * we need to retry, because we might just have lost the
			 * connection once
			 */
			if (twice)
				return false;
			PQreset(conn);		/* reconnect */
			twice = true;
		}
	}
	return true;
}
Ejemplo n.º 2
0
PGresult * do_postgres_cCommand_execute_sync(VALUE self, VALUE connection, PGconn *db, VALUE query) {
  char *str = StringValuePtr(query);
  PGresult *response;

  while ((response = PQgetResult(db))) {
    PQclear(response);
  }

  struct timeval start;

  gettimeofday(&start, NULL);
  response = PQexec(db, str);

  if (!response) {
    if (PQstatus(db) != CONNECTION_OK) {
      PQreset(db);

      if (PQstatus(db) == CONNECTION_OK) {
        response = PQexec(db, str);
      }
      else {
        do_postgres_full_connect(connection, db);
        response = PQexec(db, str);
      }
    }

    if(!response) {
      rb_raise(eDO_ConnectionError, PQerrorMessage(db));
    }
  }

  data_objects_debug(connection, query, &start);
  return response;
}
Ejemplo n.º 3
0
/* Guckt ob Verbindung da und versucht aufzubauen. 
 * gibt 1 zurueck, wenn erfolgreich, sonst 0 */
static int pg_connect(){
  if (PQstatus(connection) == CONNECTION_OK){
    PQexec(connection,"SELECT 1");				/* Status neusetzen erzwingen */
  }
  if(PQstatus(connection) != CONNECTION_OK){
    if (connection == NULL){
      if(conn_string == NULL){
	conn_string = malloc(sizeof(char)*512);
	snprintf(conn_string, 512, "host=%s dbname=%s user=%s password=%s connect_timeout=%s", global_opts.pg_host, global_opts.pg_database, global_opts.pg_user, global_opts.pg_pass, global_opts.pg_timeout);
      }
      connection = PQconnectdb(conn_string);			/* Connection aufbauen */
      add_clean(clean_write, connection);			/* Callbackfunktion zum Aufraeumen registrieren */
    } else {
      PQreset(connection);					/* Connecion resetten */
    }
    if(PQstatus(connection) != CONNECTION_OK){
      DEBUGOUT2("\nFehler beim Aufbau der Datenbankverbindung\n%s\n", PQerrorMessage(connection));
      #ifndef NO_LOGING
      snprintf(get_error_buffer(), ERR_BUFFERSIZE, "Fehler beim Aufbau der Datenbankverbindung: %s", PQerrorMessage(connection));
      log_error(get_error_buffer());
      #endif
      return 0;
    }
    DEBUGOUT1("\nDatenbankverbindung erfolgreich hergestellt\n");
  } 
  return 1;
}
Ejemplo n.º 4
0
PGresult * do_postgres_cCommand_execute_async(VALUE self, VALUE connection, PGconn *db, VALUE query) {
  PGresult *response;
  char* str = StringValuePtr(query);

  while ((response = PQgetResult(db))) {
    PQclear(response);
  }

  struct timeval start;
  int retval;

  gettimeofday(&start, NULL);
  retval = PQsendQuery(db, str);

  if (!retval) {
    if (PQstatus(db) != CONNECTION_OK) {
      PQreset(db);

      if (PQstatus(db) == CONNECTION_OK) {
        retval = PQsendQuery(db, str);
      }
      else {
        do_postgres_full_connect(connection, db);
        retval = PQsendQuery(db, str);
      }
    }

    if (!retval) {
      rb_raise(eDO_ConnectionError, "%s", PQerrorMessage(db));
    }
  }

  int socket_fd = PQsocket(db);
  fd_set rset;

  while (1) {
    FD_ZERO(&rset);
    FD_SET(socket_fd, &rset);
    retval = rb_thread_select(socket_fd + 1, &rset, NULL, NULL, NULL);

    if (retval < 0) {
      rb_sys_fail(0);
    }

    if (retval == 0) {
      continue;
    }

    if (PQconsumeInput(db) == 0) {
      rb_raise(eDO_ConnectionError, "%s", PQerrorMessage(db));
    }

    if (PQisBusy(db) == 0) {
      break;
    }
  }

  data_objects_debug(connection, query, &start);
  return PQgetResult(db);
}
Ejemplo n.º 5
0
/* Functions we export for modules to use:
	- open acquires a connection from the pool (opens one if necessary)
	- close releases it back in to the pool
*/
PGconn* pgasp_pool_open(server_rec* s) {
  PGconn* ret = NULL ;
  pgasp_config* pgasp = (pgasp_config*)
	ap_get_module_config(s->module_config, &pgasp_module) ;
  apr_uint32_t acquired_cnt ;

  if (pgasp->dbpool == NULL) {
    pgasp = apr_hash_get(pgasp_pool_config, pgasp->key, APR_HASH_KEY_STRING);
  }
  if ( apr_reslist_acquire(pgasp->dbpool, (void**)&ret) != APR_SUCCESS ) {
    ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, "mod_pgasp: Failed to acquire PgSQL connection from pool!") ;
    return NULL ;
  }
  if (PQstatus(ret) != CONNECTION_OK) {
    PQreset(ret);
    if (PQstatus(ret) != CONNECTION_OK) {
      ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
	"PgSQL Error: %s", PQerrorMessage(ret) ) ;
      apr_reslist_release(pgasp->dbpool, ret) ;
      return NULL ;
    }
  }
  if (pgasp->nkeep < (acquired_cnt = apr_reslist_acquired_count	( pgasp->dbpool	))) {
    ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, "mod_pgasp: %d connections in the %s pool acquired (%d,%d,%d)",
		 acquired_cnt, pgasp->key, pgasp->nmin, pgasp->nkeep, pgasp->nmax
		 ) ;
  }
  return ret ;
}
Ejemplo n.º 6
0
static int aPGSQL_reset(struct cw_channel *chan, void *data) {

    char *s1,*s3;
    int l;
    PGconn *karoto;
    int id;
    char *stringp=NULL;


    l=strlen(data)+2;
    s1=malloc(l);
    strncpy(s1, data, l - 1);
    stringp=s1;
    strsep(&stringp," "); /* eat the first token, we already know it :P  */
    s3=strsep(&stringp," ");
    id=atoi(s3);
    if ((karoto=find_identifier(id,CW_PGSQL_ID_CONNID))==NULL) {
        cw_log(LOG_WARNING,"Invalid connection identifier %d passed in aPGSQL_reset\n",id);
    } else {
        PQreset(karoto);
    }
    free(s1);
    return(0);

}
Ejemplo n.º 7
0
static PGresult* cCommand_execute_sync(VALUE self, PGconn *db, VALUE query) {
  PGresult *response;
  struct timeval start;
  char* str = StringValuePtr(query);

  while ((response = PQgetResult(db)) != NULL) {
    PQclear(response);
  }

  gettimeofday(&start, NULL);

  response = PQexec(db, str);

  if (response == NULL) {
    if(PQstatus(db) != CONNECTION_OK) {
      PQreset(db);
      if (PQstatus(db) == CONNECTION_OK) {
        response = PQexec(db, str);
      } else {
        VALUE connection = rb_iv_get(self, "@connection");
        full_connect(connection, db);
        response = PQexec(db, str);
      }
    }

    if(response == NULL) {
      rb_raise(eConnectionError, PQerrorMessage(db));
    }
  }

  data_objects_debug(query, &start);
  return response;
}
Ejemplo n.º 8
0
Archivo: common.c Proyecto: GisKook/Gis
/* CheckConnection
 *
 * Verify that we still have a good connection to the backend, and if not,
 * see if it can be restored.
 *
 * Returns true if either the connection was still there, or it could be
 * restored successfully; false otherwise.	If, however, there was no
 * connection and the session is non-interactive, this will exit the program
 * with a code of EXIT_BADCONN.
 */
static bool
CheckConnection(void)
{
	bool		OK;

	OK = ConnectionUp();
	if (!OK)
	{
		if (!pset.cur_cmd_interactive)
		{
			psql_error("connection to server was lost\n");
			exit(EXIT_BADCONN);
		}

		fputs(_("The connection to the server was lost. Attempting reset: "), stderr);
		PQreset(pset.db);
		OK = ConnectionUp();
		if (!OK)
		{
			fputs(_("Failed.\n"), stderr);
			PQfinish(pset.db);
			pset.db = NULL;
			ResetCancelConn();
			UnsyncVariables();
		}
		else
			fputs(_("Succeeded.\n"), stderr);
	}

	return OK;
}
Ejemplo n.º 9
0
static int c_psql_check_connection (c_psql_database_t *db)
{
	/* "ping" */
	PQclear (PQexec (db->conn, "SELECT 42;"));

	if (CONNECTION_OK != PQstatus (db->conn)) {
		PQreset (db->conn);

		/* trigger c_release() */
		if (0 == db->conn_complaint.interval)
			db->conn_complaint.interval = 1;

		if (CONNECTION_OK != PQstatus (db->conn)) {
			c_complain (LOG_ERR, &db->conn_complaint,
					"Failed to connect to database %s: %s",
					db->database, PQerrorMessage (db->conn));
			return -1;
		}

		db->proto_version = PQprotocolVersion (db->conn);
		if (3 > db->proto_version)
			log_warn ("Protocol version %d does not support parameters.",
					db->proto_version);
	}

	db->server_version = PQserverVersion (db->conn);

	c_release (LOG_INFO, &db->conn_complaint,
			"Successfully reconnected to database %s", PQdb (db->conn));
	return 0;
} /* c_psql_check_connection */
Ejemplo n.º 10
0
void DatabasePostgreSQL::UpdateLSAccountData(unsigned int id, string ip_address)
{
	if(!db)
	{
		return;
	}

	/**
	* PostgreSQL doesn't have automatic reconnection option like mysql
	* but it's easy to check and reconnect
	*/
	if(PQstatus(db) != CONNECTION_OK)
	{
		PQreset(db);
		if(PQstatus(db) != CONNECTION_OK)
		{
			return;
		}
	}

	stringstream query(stringstream::in | stringstream::out);
	query << "UPDATE " << server.options.GetAccountTable() << " SET LastIPAddress = '";
	query << ip_address;
	query << "', LastLoginDate = current_date where LoginServerID = ";
	query << id;
	PGresult *res = PQexec(db, query.str().c_str());

	char *error = PQresultErrorMessage(res);
	if(strlen(error) > 0)
	{
		server_log->Log(log_database, "Database error in DatabasePostgreSQL::GetLoginDataFromAccountName(): %s", error);
	}
	PQclear(res);
}
Ejemplo n.º 11
0
static int c_psql_check_connection (c_psql_database_t *db)
{
	_Bool init = 0;

	if (! db->conn) {
		init = 1;

		/* trigger c_release() */
		if (0 == db->conn_complaint.interval)
			db->conn_complaint.interval = 1;

		c_psql_connect (db);
	}

	/* "ping" */
	PQclear (PQexec (db->conn, "SELECT 42;"));

	if (CONNECTION_OK != PQstatus (db->conn)) {
		PQreset (db->conn);

		/* trigger c_release() */
		if (0 == db->conn_complaint.interval)
			db->conn_complaint.interval = 1;

		if (CONNECTION_OK != PQstatus (db->conn)) {
			c_complain (LOG_ERR, &db->conn_complaint,
					"Failed to connect to database %s (%s): %s",
					db->database, db->instance,
					PQerrorMessage (db->conn));
			return -1;
		}

		db->proto_version = PQprotocolVersion (db->conn);
	}

	db->server_version = PQserverVersion (db->conn);

	if (c_would_release (&db->conn_complaint)) {
		char *server_host;
		int   server_version;

		server_host    = PQhost (db->conn);
		server_version = PQserverVersion (db->conn);

		c_do_release (LOG_INFO, &db->conn_complaint,
				"Successfully %sconnected to database %s (user %s) "
				"at server %s%s%s (server version: %d.%d.%d, "
				"protocol version: %d, pid: %d)", init ? "" : "re",
				PQdb (db->conn), PQuser (db->conn),
				C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
				C_PSQL_SERVER_VERSION3 (server_version),
				db->proto_version, PQbackendPID (db->conn));

		if (3 > db->proto_version)
			log_warn ("Protocol version %d does not support parameters.",
					db->proto_version);
	}
	return 0;
} /* c_psql_check_connection */
Ejemplo n.º 12
0
void Database_PostgreSQL::verifyDatabase()
{
	if (PQstatus(m_conn) == CONNECTION_OK)
		return;

	PQreset(m_conn);
	ping();
}
Ejemplo n.º 13
0
/* {{{ */
static int pdo_pgsql_check_liveness(pdo_dbh_t *dbh)
{
	pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
	if (PQstatus(H->server) == CONNECTION_BAD) {
		PQreset(H->server);
	}
	return (PQstatus(H->server) == CONNECTION_OK) ? SUCCESS : FAILURE;
}
Ejemplo n.º 14
0
	bool open() {
		if (_connection != NULL) {
			PQreset(_connection);
			if (PQstatus(_connection) != CONNECTION_OK) {
				_error = true;
				_errorMsg.assign(PQerrorMessage(_connection));
				_errorMsg.resize(_errorMsg.size() - 1);
				return false;
			}

			return true;
		}

		std::string connStr;
		if (!_host.empty()) {
			connStr.append("host = '" + _host + "' ");
		}
		if (!_hostaddr.empty()) {
			connStr.append("hostaddr = '" + _hostaddr + "' ");
		}
		if (!_port.empty()) {
			connStr.append("port = '" + _port + "' ");
		}
		if (!_dbname.empty()) {
			connStr.append("dbname = '" + _dbname + "' ");
		}
		if (!_user.empty()) {
			connStr.append("user = '******' ");
		}
		if (!_password.empty()) {
			connStr.append("password = '******' ");
		}
		if (!_connect_timeout.empty()) {
			connStr.append("connect_timeout = '" + _connect_timeout + "' ");
		}
		if (!_options.empty()) {
			connStr.append("options = '" + _options + "' ");
		}
		if (!_sslmode.empty()) {
			connStr.append("sslmode = '" + _sslmode + "' ");
		}
		if (!_requiressl.empty()) {
			connStr.append("requiressl = '" + _requiressl + "' ");
		}
		if (!_service.empty()) {
			connStr.append("service = '" + _service + "' ");
		}

		_connection = PQconnectdb(connStr.c_str());
		if (PQstatus(_connection) != CONNECTION_OK) {
			_error = true;
			_errorMsg.assign(PQerrorMessage(_connection));
			_errorMsg.resize(_errorMsg.size() - 1);
			return false;
		}

		return true;
	}
Ejemplo n.º 15
0
int CHttpThread::PgExecuteSQL(PGconn *conn,
                              PGresult * &dataset,
                              const char * szSQL,
                              int nParams,
                              const char * const *paramValues,
                              char * szErrMsg)
{
    int retrycnt=0;

sqlexecretry:
    dataset = PQexecParams(m_pq,
                       szSQL,
                       nParams,       /* 参数个数 */
                       NULL,    /* 让后端推出参数类型 */
                       paramValues,
                       NULL,    /* 因为是文本,所以必须要参数长度 */
                       NULL,    /* 缺省是全部文本参数 */
                       0);      /* 是否是二进制结果 */

    if(  (PQresultStatus(dataset) == PGRES_COMMAND_OK ) ||(PQresultStatus(dataset) == PGRES_TUPLES_OK))
    {
         printf("Successfully execute SQL : %s\n",szSQL);
         return 0;
    }
    else
    {
        sprintf(szErrMsg,"%s",PQerrorMessage(m_pq));
        printf("%s\n",szErrMsg);

        PQclear(dataset);
        if(PQstatus(m_pq) != CONNECTION_OK)
        {
            if(retrycnt > 3)
            {
                return -1;
            }
            sleep(1);
            PQreset(m_pq);
            retrycnt++;

            if(PQstatus(m_pq)!=CONNECTION_OK)
            {
                printf("Thread %d reconnect database fail!\n",m_id);
                PQclear(dataset);
                goto sqlexecretry;
            }
            else
            {
                printf("Thread %d reconnect database success!\n",m_id);
            }
        }
        else //非连接性错误,可能是SQL语句错误等原因
        {
            return -1;
        }
    }

}
Ejemplo n.º 16
0
//-----------------------------------------------------------
void ConexaoBD::reiniciar(void)
{
//Dispara um erro caso o usuário tente reiniciar uma conexão não iniciada
    if(!conexao)
        throw Excecao(ERR_CONEXBD_OPRCONEXNAOALOC, __PRETTY_FUNCTION__, __FILE__, __LINE__);

//Reinicia a conexão
    PQreset(conexao);
}
Ejemplo n.º 17
0
CAMLprim value PQreset_stub(value v_conn)
{
  CAMLparam1(v_conn);
  PGconn *conn = get_conn(v_conn);
  caml_enter_blocking_section();
    PQreset(conn);
  caml_leave_blocking_section();
  CAMLreturn(Val_unit);
}
Ejemplo n.º 18
0
bool DatabasePostgreSQL::GetWorldRegistration(string long_name, string short_name, unsigned int &id, string &desc, unsigned int &list_id,
		unsigned int &trusted, string &list_desc, string &account, string &password)
{
	if(!db)
	{
		return false;
	}

	/**
	* PostgreSQL doesn't have automatic reconnection option like mysql
	* but it's easy to check and reconnect
	*/
	if(PQstatus(db) != CONNECTION_OK)
	{
		PQreset(db);
		if(PQstatus(db) != CONNECTION_OK)
		{
			return false;
		}
	}

	stringstream query(stringstream::in | stringstream::out);
	query << "SELECT WSR.ServerID, WSR.ServerTagDescription, WSR.ServerTrusted, SLT.ServerListTypeID, ";
	query << "SLT.ServerListTypeDescription, SAR.AccountName, SAR.AccountPassword FROM " << server.options.GetWorldRegistrationTable();
	query << " AS WSR JOIN " << server.options.GetWorldServerTypeTable() << " AS SLT ON WSR.ServerListTypeID = SLT.ServerListTypeID JOIN ";
	query << server.options.GetWorldAdminRegistrationTable() << " AS SAR ON WSR.ServerAdminID = SAR.ServerAdminID WHERE WSR.ServerShortName";
	query << " = '";
	query << short_name;
	query << "'";

	PGresult *res = PQexec(db, query.str().c_str());

	char *error = PQresultErrorMessage(res);
	if(strlen(error) > 0)
	{
		server_log->Log(log_database, "Database error in DatabasePostgreSQL::GetWorldRegistration(): %s", error);
		PQclear(res);
		return false;
	}

	if(PQntuples(res) > 0)
	{
		id = atoi(PQgetvalue(res, 0, 0));
		desc = PQgetvalue(res, 0, 1);
		trusted = atoi(PQgetvalue(res, 0, 2));
		list_id = atoi(PQgetvalue(res, 0, 3));
		list_desc = PQgetvalue(res, 0, 4);
		account = PQgetvalue(res, 0, 5);
		password = PQgetvalue(res, 0, 6);

		PQclear(res);
		return true;
	}

	PQclear(res);
	return false;
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool PostgreSQLDatabase::isConnected() const {
	if ( _handle == NULL ) return false;
	ConnStatusType stat = PQstatus(_handle);
	if ( stat == CONNECTION_OK ) return true;

	SEISCOMP_ERROR("connection bad (%d) -> reconnect", stat);
	PQreset(_handle);
	return PQstatus(_handle) == CONNECTION_OK;
}
Ejemplo n.º 20
0
void pgConn::Reset()
{
	PQreset(conn);

	// Reset any vars that need to be in a defined state before connecting
	needColQuoting = false;

	Initialize();
}
Ejemplo n.º 21
0
void DBConnection::reset(void)
{
	//Raise an erro in case the user try to reset a not opened connection
	if(!connection)
		throw Exception(ERR_OPR_NOT_ALOC_CONN, __PRETTY_FUNCTION__, __FILE__, __LINE__);

	//Reinicia a conexão
	PQreset(connection);
}
Ejemplo n.º 22
0
void postgresql_connection_impl::reconnect()
{
  if (PQstatus(conn)==CONNECTION_OK)
    return;

  PQreset(conn);

  if (PQstatus(conn)!=CONNECTION_OK)
    throw database_error("fail to reconnect");
}
Ejemplo n.º 23
0
static apr_status_t dbd_pgsql_check_conn(apr_pool_t *pool,
                                         apr_dbd_t *handle)
{
    if (PQstatus(handle->conn) != CONNECTION_OK) {
        PQreset(handle->conn);
        if (PQstatus(handle->conn) != CONNECTION_OK) {
            return APR_EGENERAL;
        }
    }
    return APR_SUCCESS;
}
Ejemplo n.º 24
0
int be_pg_superuser(void *handle, const char *username)
{
	struct pg_backend *conf = (struct pg_backend *)handle;
	char *v = NULL;
	long nrows;
	int issuper = BACKEND_DEFER;
	PGresult *res = NULL;

	_log(LOG_DEBUG, "SUPERUSER: %s", username);

	if (!conf || !conf->superquery || !username || !*username)
		return BACKEND_DEFER;

	//query for postgres $1 instead of % s
	const char *values[1] = {username};
	int lengths[1] = {strlen(username)};
	int binary[1] = {0};

	res = PQexecParams(conf->conn, conf->superquery, 1, NULL, values, lengths, binary, 0);

	if (PQresultStatus(res) != PGRES_TUPLES_OK) {
		fprintf(stderr, "%s\n", PQresultErrorMessage(res));
		issuper = BACKEND_ERROR;
		//try to reset connection if failing because of database connection lost
		if(PQstatus(conf->conn) == CONNECTION_BAD){
			_log(LOG_NOTICE, "Noticed a postgres connection loss. Trying to reconnect ...\n");
			//try to reinitiate the database connection
			PQreset(conf->conn);
		}

		goto out;
	}
	if ((nrows = PQntuples(res)) != 1) {
		goto out;
	}
	if (PQnfields(res) != 1) {
		//DEBUG fprintf(stderr, "numfields not ok\n");
		goto out;
	}
	if ((v = PQgetvalue(res, 0, 0)) == NULL) {
		goto out;
	}
	issuper = (atoi(v)) ? BACKEND_ALLOW : BACKEND_DEFER;


out:
	_log(LOG_DEBUG, "user is %d", issuper);

	PQclear(res);

	return (issuper);
}
Ejemplo n.º 25
0
//! check if the connection is ok
QuillErrCode
PGSQLDatabase::resetConnection()
{
	PQreset(connection);

	if (PQstatus(connection) == CONNECTION_OK) {
		dprintf(D_FULLDEBUG, "DB Connection Ok\n");
		return QUILL_SUCCESS;
	}
	else {
		dprintf(D_FULLDEBUG, "DB Connection BAD\n");
		return QUILL_FAILURE;
	}
}
Ejemplo n.º 26
0
int be_pg_getuser(void *handle, const char *username, const char *password, char **phash, const char *clientid)
{
	struct pg_backend *conf = (struct pg_backend *)handle;
	char *value = NULL, *v = NULL;
	long nrows;
	PGresult *res = NULL;

	_log(LOG_DEBUG, "GETTING USERS: %s", username);

	if (!conf || !conf->userquery || !username || !*username)
		return BACKEND_DEFER;

	const char *values[1] = {username};
	int lengths[1] = {strlen(username)};
	int binary[1] = {0};

	res = PQexecParams(conf->conn, conf->userquery, 1, NULL, values, lengths, binary, 0);

	if (PQresultStatus(res) != PGRES_TUPLES_OK) {
		_log(LOG_DEBUG, "%s\n", PQresultErrorMessage(res));
		if(PQstatus(conf->conn) == CONNECTION_BAD){
			_log(LOG_NOTICE, "Noticed a postgres connection loss. Trying to reconnect ...\n");
			//try to reinitiate the database connection
			PQreset(conf->conn);
		}
		
		goto out;
	}
	if ((nrows = PQntuples(res)) != 1) {
		//DEBUG fprintf(stderr, "rowcount = %ld; not ok\n", nrows);
		goto out;
	}
	if (PQnfields(res) != 1) {
		//DEBUG fprintf(stderr, "numfields not ok\n");
		goto out;
	}
	if ((v = PQgetvalue(res, 0, 0)) == NULL) {
		goto out;
	}	
	value = (v) ? strdup(v) : NULL;


out:

	PQclear(res);

	*phash = value;
	return BACKEND_DEFER;
}
Ejemplo n.º 27
0
bool
pgConnection::reconnect()
{
  if (m_pgConn) {
    PQreset(m_pgConn);
    if (PQstatus(m_pgConn)!=CONNECTION_OK)
      return false;
  }
  for (int i=0; i<m_listeners.size(); i++) {
    /* Reinitialize listeners. It is necessary if the db backend
       process went down, and if the socket changed */
    m_listeners.at(i)->setup_notification();
    m_listeners.at(i)->setup_db();
  }
  return true;
}
Ejemplo n.º 28
0
void PostgreSQLConnection::connect()
{
	bool reconnecting = false;
	if (_pgConn != nullptr) //reconnection attempt
	{
		if (!_ConnectionLost())
			return;
		else
			reconnecting = true;
	}

	//remove any state from previous session
	this->clear();

	Poco::Logger& logger = _dbEngine->getLogger();
	for(;;)
	{
		if (reconnecting)
			PQreset(_pgConn);
		else
		{
			if (_host == ".")
				_pgConn = PQsetdbLogin(nullptr, _port == "." ? nullptr : _port.c_str(), nullptr, nullptr, _database.c_str(), _user.c_str(), _password.c_str());
			else
				_pgConn = PQsetdbLogin(_host.c_str(), _port.c_str(), nullptr, nullptr, _database.c_str(), _user.c_str(), _password.c_str());
		}
		
		//check to see that the backend connection was successfully made
		if (_ConnectionLost())
		{
			const char* actionToDo = "connect";
			if (reconnecting)
				actionToDo = "reconnect";

			static const long sleepTime = 1000;
			logger.warning(Poco::format("Could not %s to Postgre database at %s: %s, retrying in %d seconds",
				string(actionToDo),_host,lastErrorDescr(),static_cast<int>(sleepTime/1000)));
			Poco::Thread::sleep(sleepTime);

			continue;
		}
		break;
	}

	string actionDone = (reconnecting)?string("Reconnected"):string("Connected");
	poco_information(logger,Poco::format("%s to Postgre database %s:%s/%s server ver: %d",actionDone,_host,_port,_database,PQserverVersion(_pgConn)));
}
Ejemplo n.º 29
0
/**
 *  Reset the database conenction.
 *
 *  Error messages from this function are sent to the message
 *  handler (see msngr_init_log() and msngr_init_mail()).
 *
 *  @param  dbconn - pointer to the database connection
 *
 *  @return database status:
 *    - DB_NO_ERROR
 *    - DB_MEM_ERROR
 *    - DB_ERROR
 *
 *  @see DBStatus
 */
DBStatus pgsql_reset(DBConn *dbconn)
{
    PGconn *pgconn;

    if (dbconn->dbh) {

        pgconn = (PGconn *)dbconn->dbh;

        PQreset(pgconn);

        if (PQstatus(pgconn) == CONNECTION_OK) {
            return(DB_NO_ERROR);
        }
    }

    return(pgsql_connect(dbconn));
}
Ejemplo n.º 30
0
bool DatabasePostgreSQL::GetLoginDataFromAccountName(string name, string &password, unsigned int &id)
{
	if(!db)
	{
		return false;
	}

	/**
	* PostgreSQL doesn't have automatic reconnection option like mysql
	* but it's easy to check and reconnect
	*/
	if(PQstatus(db) != CONNECTION_OK)
	{
		PQreset(db);
		if(PQstatus(db) != CONNECTION_OK)
		{
			return false;
		}
	}

	stringstream query(stringstream::in | stringstream::out);
	query << "SELECT LoginServerID, AccountPassword FROM " << server.options.GetAccountTable() << " WHERE AccountName = '";
	query << name;
	query << "'";

	PGresult *res = PQexec(db, query.str().c_str());

	char *error = PQresultErrorMessage(res);
	if(strlen(error) > 0)
	{
		server_log->Log(log_database, "Database error in DatabasePostgreSQL::GetLoginDataFromAccountName(): %s", error);
		PQclear(res);
		return false;
	}

	if(PQntuples(res) > 0)
	{
		id = atoi(PQgetvalue(res, 0, 0));
		password = PQgetvalue(res, 0, 1);
		PQclear(res);
		return true;
	}

	PQclear(res);
	return false;
}