Merge pull request #4239 from pocoproject/4231-PostgreSQL-leaks-memory-for-failed-connections

4231 postgre sql leaks memory for failed connections
This commit is contained in:
Aleksandar Fabijanic 2023-11-10 12:51:36 +01:00 committed by GitHub
commit 9e90fcbcea
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 44 additions and 3 deletions

View File

@ -83,12 +83,24 @@ void SessionHandle::connect(const std::string& aConnectionString)
{
throw ConnectionFailedException("Already Connected");
}
else if (_pConnection)
{
// free bad connection
PQfinish(_pConnection);
_pConnection = 0;
}
_pConnection = PQconnectdb(aConnectionString.c_str());
if (!isConnectedNoLock())
{
throw ConnectionFailedException(std::string("Connection Error: ") + lastErrorNoLock());
std::string msg = std::string("Connection Error: ") + lastErrorNoLock();
if (_pConnection)
{
PQfinish(_pConnection);
_pConnection = 0;
}
throw ConnectionFailedException(msg);
}
_connectionString = aConnectionString;
@ -137,7 +149,7 @@ void SessionHandle::disconnect()
{
Poco::FastMutex::ScopedLock mutexLocker(_sessionMutex);
if (isConnectedNoLock())
if (_pConnection)
{
PQfinish(_pConnection);

View File

@ -140,6 +140,32 @@ void PostgreSQLTest::testConnectNoDB()
}
}
void PostgreSQLTest::testFailedConnect()
{
std::string dbConnString;
dbConnString += "host=" + getHost();
dbConnString += " user=invalid";
dbConnString += " password=invalid";
dbConnString += " port=" + getPort();
try
{
std::cout << "Attempting to Connect to [" << dbConnString << "] with invalid credentials: " << std::endl;
Session session(PostgreSQL::Connector::KEY, dbConnString);
fail ("must fail");
}
catch (ConnectionFailedException& ex)
{
std::cout << ex.displayText() << std::endl;
}
catch (ConnectionException& ex)
{
std::cout << ex.displayText() << std::endl;
}
}
void PostgreSQLTest::testPostgreSQLOIDs()
{
if (!_pSession) fail ("Test not available.");
@ -309,6 +335,7 @@ void PostgreSQLTest::testBarebonePostgreSQL()
}
void PostgreSQLTest::testSimpleAccess()
{
if (!_pSession) fail ("Test not available.");
@ -775,7 +802,7 @@ void PostgreSQLTest::testSqlState()
}
catch (const Poco::Data::PostgreSQL::PostgreSQLException & exception)
{
assertTrue(exception.sqlState() == std::string("42601"));
assertTrue(exception.sqlState() == std::string("42601"));
}
}
@ -1236,6 +1263,7 @@ CppUnit::Test* PostgreSQLTest::suite()
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("PostgreSQLTest");
CppUnit_addTest(pSuite, PostgreSQLTest, testConnectNoDB);
CppUnit_addTest(pSuite, PostgreSQLTest, testFailedConnect);
CppUnit_addTest(pSuite, PostgreSQLTest, testPostgreSQLOIDs);
//CppUnit_addTest(pSuite, PostgreSQLTest, testBarebonePostgreSQL);
CppUnit_addTest(pSuite, PostgreSQLTest, testSimpleAccess);

View File

@ -36,6 +36,7 @@ public:
~PostgreSQLTest();
void testConnectNoDB();
void testFailedConnect();
void testPostgreSQLOIDs();
void testBarebonePostgreSQL();