I'm using this nice C++ wrapper to work with SQLite3 in my project. I wanted to handle errors gracefully and automatically rollback if piece of code fails, so wrote this simple helper class:
class SqlTransaction { // RAII class to rollback on error
public:
SqlTransaction(std::shared_ptr<sqlite::database> db_): db(db_) { *db << "begin;"; };
~SqlTransaction() { if (!finished) rollback(); };
void commit() { if (!finished) { *db << "commit;"; finished = true; } };
void rollback() { if (!finished) { *db << "rollback;"; finished = true; } };
// Disable both copying and moving
SqlTransaction(const SqlTransaction&) = delete;
SqlTransaction& operator=(const SqlTransaction&) = delete;
SqlTransaction(SqlTransaction&&) = delete;
private:
std::shared_ptr<sqlite::database> db;
bool finished = false;
};
It's to be used like this:
SqlTransaction trans(db);
// work with db here, may throw if something goes wrong
trans.commit();