Add a Transaction::rollback() method

This commit is contained in:
Sébastien Rombauts 2022-12-15 19:00:04 +01:00
parent fc92d9cf92
commit cc0044a603
3 changed files with 138 additions and 121 deletions

View File

@ -86,6 +86,11 @@ public:
*/
void commit();
/**
* @brief Rollback the transaction
*/
void rollback();
private:
Database& mDatabase; ///< Reference to the SQLite Database Connection
bool mbCommited = false; ///< True when commit has been called

View File

@ -44,7 +44,7 @@ Transaction::Transaction(Database& aDatabase, TransactionBehavior behavior) :
Transaction::Transaction(Database &aDatabase) :
mDatabase(aDatabase)
{
mDatabase.exec("BEGIN");
mDatabase.exec("BEGIN TRANSACTION");
}
// Safely rollback the transaction if it has not been committed.
@ -54,7 +54,7 @@ Transaction::~Transaction()
{
try
{
mDatabase.exec("ROLLBACK");
mDatabase.exec("ROLLBACK TRANSACTION");
}
catch (SQLite::Exception&)
{
@ -68,7 +68,7 @@ void Transaction::commit()
{
if (false == mbCommited)
{
mDatabase.exec("COMMIT");
mDatabase.exec("COMMIT TRANSACTION");
mbCommited = true;
}
else
@ -77,5 +77,17 @@ void Transaction::commit()
}
}
// Rollback the transaction
void Transaction::rollback()
{
if (false == mbCommited)
{
mDatabase.exec("ROLLBACK TRANSACTION");
}
else
{
throw SQLite::Exception("Transaction already committed.");
}
}
} // namespace SQLite

View File

@ -99,8 +99,8 @@ TEST(Transaction, commitRollback)
EXPECT_EQ(1, db.exec("INSERT INTO test VALUES (NULL, \"third\")"));
EXPECT_EQ(2, db.getLastInsertRowid());
// Execute a manual rollback (no real use case I can think of, so no rollback() method)
db.exec("ROLLBACK");
// Execute a manual rollback
transaction.rollback();
// end of scope: the automatic rollback should not raise an error because it is harmless
}