Transaction.cc
Go to the documentation of this file.
3 
4 #include "sqlite3.h"
5 
6 #include <cassert>
7 #include <iostream>
8 
9 namespace {
10  class set_to_null_when_done {
11  public:
12  explicit set_to_null_when_done(sqlite3*& db) noexcept : db_{db} {}
13  ~set_to_null_when_done() noexcept { db_ = nullptr; }
14 
15  private:
16  sqlite3*& db_;
17  };
18 }
19 
20 cet::sqlite::Transaction::Transaction(sqlite3* db) noexcept(false) : db_{db}
21 {
22  assert(db_);
23  int const rc{sqlite3_exec(db_, "BEGIN;", nullptr, nullptr, nullptr)};
24  if (rc != SQLITE_OK) {
26  << "Failed to start SQLite transaction due to status code " << rc << ":\n"
27  << sqlite3_errmsg(db_) << '\n';
28  }
29 }
30 
32 {
33  // We can't throw an exception from our destructor, so we just emit
34  // an error message.
35  if (db_) {
36  sqlite3_exec(db_, "ROLLBACK;", nullptr, nullptr, nullptr);
37  std::cerr << "Transaction d'tor called before commit was called.\n";
38  }
39 }
40 
41 void
43 {
44  assert(db_);
45  set_to_null_when_done sentry{db_};
46  int const rc{sqlite3_exec(db_, "COMMIT;", nullptr, nullptr, nullptr)};
47  if (rc != SQLITE_OK) {
49  << "Failed to commit SQLite transaction due to status code " << rc
50  << ":\n"
51  << sqlite3_errmsg(db_) << '\n';
52  }
53 }
cet::coded_exception< errors::ErrorCodes, ExceptionDetail::translate > Exception
Definition: Exception.h:27
Transaction(sqlite3 *db) noexcept(false)
Definition: Transaction.cc:20
struct sqlite3 sqlite3
void commit() noexcept(false)
Definition: Transaction.cc:42