Pgsql::Connection::connect functions now all report connection errors

by throwing exception.
This commit is contained in:
eelke 2019-11-03 07:58:48 +01:00
parent 05bca069e3
commit c5f6da48ce
5 changed files with 35 additions and 39 deletions

View file

@ -43,32 +43,16 @@ Canceller Connection::getCancel()
return c;
}
bool Connection::connect(const char *params)
void Connection::connect(const char *params)
{
bool result = false;
conn = PQconnectdb(params);
if (conn) {
ConnStatusType status = PQstatus(conn);
result = (status == CONNECTION_OK);
}
return result;
testForConnectionError(conn);
}
void Connection::connect(const char *const * keywords, const char* const * values, int expand_dbname)
{
conn = PQconnectdbParams(keywords, values, expand_dbname);
std::string error_msg;
if (conn) {
ConnStatusType status = PQstatus(conn);
if (status == CONNECTION_OK)
return;
error_msg = PQerrorMessage(conn);
}
else {
error_msg = "Unknown connection failure (maybe out of memory?)";
}
throw PgException(error_msg);
testForConnectionError(conn);
}
bool Connection::connectStart(const char* params)
@ -247,6 +231,22 @@ QString Connection::getDBName() const
return QString::fromUtf8(PQdb(conn));
}
void Connection::testForConnectionError(PGconn *conn)
{
std::string error_msg;
if (conn) {
ConnStatusType status = PQstatus(conn);
if (status == CONNECTION_OK)
return;
error_msg = PQerrorMessage(conn);
}
else {
error_msg = "Unknown connection failure (maybe out of memory?)";
}
throw PgConnectionError(error_msg);
}
void Connection::throwError(PGresult *result) const
{
auto state = PQresultStatus(result);

View file

@ -44,10 +44,10 @@ namespace Pgsql {
Connection(Connection &&rhs);
Connection& operator=(Connection &&rhs);
bool connect(const char *params);
bool connect(const QString &params)
void connect(const char *params);
void connect(const QString &params)
{
return connect(params.toUtf8().data());
connect(params.toStdString().c_str());
}
void connect(const char *const * keywords, const char* const * values, int expand_dbname);
@ -115,6 +115,7 @@ namespace Pgsql {
PGconn *conn = nullptr;
std::function<void(const PGresult *)> notifyReceiver;
static void testForConnectionError(PGconn *conn);
void throwError(PGresult *result) const;
static void notifyReceiveFunc(void *arg, const PGresult *result);
};

View file

@ -34,15 +34,14 @@ namespace Pgsql {
Pgsql::ErrorDetails m_details;
};
// class PgConnectionError: public PgException {
// public:
// PgConnectionError(const std::string &msg, std::string result_code)
// : PgResultError(msg, std::move(result_code))
// {}
// private:
class PgConnectionError: public PgException {
public:
PgConnectionError(const std::string &msg)
: PgException(msg)
{}
private:
// };
};