Manages explicit transactions using RAII. Transactions can be started with different
locking modes, and support capturing/re-opening WAL snapshots similar to
sqlite::savepoint.
Use cases
- Constructor starts the transaction immediately to minimize the “opened but unused”
window; call
begin()manually if you need deferred start. - Destructor rolls back automatically, making it safe to throw exceptions anywhere in the guarded scope.
- Combines nicely with
savepointfor chunked work and withsnapshotfor deterministic reads in WAL mode.
enum class transaction_type
undefined— defers to SQLite's default (deferred).deferredimmediateexclusive
Example usage
void persist(std::span<event> events) {
sqlite::transaction tx{db, sqlite::transaction_type::immediate};
sqlite::execute insert{db, "INSERT INTO events VALUES(?, ?, ?)"};
for (auto const & e : events) {
insert % e.id % e.type % e.payload;
insert();
}
tx.commit();
}
Need repeatable reads? grab a snapshot inside the transaction with
tx.take_snapshot() and call tx.open_snapshot(snap) whenever you
have to re-run the validation step.
Public API
| Member | Description |
|---|---|
transaction(connection& con, transaction_type type = transaction_type::undefined) | Begins a transaction immediately. |
~transaction() | Rolls back automatically if end() or commit() was not called. |
void begin(transaction_type type = transaction_type::undefined) | Starts a new transaction if one is not already active. |
void end() | Ends the current transaction by committing; alias for commit(). |
void commit() | Commits changes. |
void rollback() | Rolls back changes. |
bool isActive() const | Indicates whether the transaction is currently open. |
snapshot take_snapshot(std::string_view schema = "main") | Captures a WAL snapshot during the transaction. |
void open_snapshot(snapshot const&, std::string_view schema = "main") | Reverts to the supplied snapshot. |