Fix behaviour of fetch() without any data with PostgreSQL

If execute() didn't bring any data from the server, all statement member
variables remained uninitialized, resulting in problems (UB, infinite
loops, ...) if fetch() is called later.

Fix this by initializing numberOfRows_ and checking for it in fetch()
and simply not doing anything there if it is 0.

Closes #1328.
This commit is contained in:
Vadim Zeitlin
2026-02-06 00:15:54 +01:00
parent b2e4cf3c27
commit da49415352
2 changed files with 31 additions and 0 deletions

View File

@@ -544,6 +544,7 @@ postgresql_statement_backend::execute(int number)
}
else
{
numberOfRows_ = 0;
return ef_no_data;
}
}
@@ -556,6 +557,13 @@ postgresql_statement_backend::fetch(int number)
throw soci_error("Bulk operations are not supported with single-row mode.");
}
if (numberOfRows_ == 0)
{
// There is nothing to fetch and normally we shouldn't be even called
// in this case, but don't do anything stupid if we are.
return ef_no_data;
}
// Note:
// In the multi-row mode this function does not actually fetch anything from anywhere
// - the data was already retrieved from the server in the execute()

View File

@@ -410,6 +410,29 @@ TEST_CASE_METHOD(common_tests, "NULL expected exception", "[core][exception][nul
CHECK_THROWS_AS( std::for_each(rs.begin(), rs.end(), THelper()), soci_error );
}
// See #1328: this used to misbehave at least with PostgreSQL backend.
TEST_CASE_METHOD(common_tests, "Fetch into a row without result", "[core][row]")
{
soci::session sql(backEndFactory_, connectString_);
auto_table_creator tableCreator(tc_.table_creator_1(sql));
sql << "insert into soci_test(val) values(1)";
soci::row row;
soci::statement
st = (sql.prepare << "update soci_test set val=2", soci::into(row));
REQUIRE_NOTHROW( st.execute(false) );
std::size_t count = 0;
while (st.fetch())
{
++count;
}
CHECK( row.size() == 0 );
CHECK( count == 0 );
}
} // namespace tests
} // namespace soci