Wraps the optional sqlite3_snapshot* API to capture consistent read views of WAL databases and to manage journal modes programmatically.

Use cases

  • Guarantees long-running readers never block writers—pin a snapshot and finish work at your own pace.
  • Explicitly flip between WAL and rollback journal modes during integration tests to mimic production settings.
  • Feature-detect snapshots at runtime; older system SQLite builds may not include the extension.

enum class wal_mode

  • rollback, truncate, persist, memory, wal, wal2

Example usage

if (!sqlite::snapshots_supported()) {
    return;
}

sqlite::enable_wal(db);

auto snap = sqlite::snapshot::take(db);
sqlite::transaction reader{db};
snap.open(db); // pin read view

sqlite::query q{db, "SELECT * FROM ledger ORDER BY created_at"};
for (auto & row : q.each()) {
    consume(row);
}

reader.end(); // releasing the snapshot allows checkpoints again

I often grab a savepoint and a snapshot at the same time—if the check fails I roll back to the savepoint and reopen the exact same read view.

struct snapshot

MemberDescription
snapshot()Creates an empty snapshot handle.
snapshot(snapshot const&)=delete, snapshot& operator=(snapshot const&)=deleteSnapshots cannot be copied.
snapshot(snapshot&&) noexcept, snapshot& operator=(snapshot&&) noexceptTransfer ownership of the underlying sqlite3_snapshot*.
~snapshot()Releases the snapshot if held.
bool valid() const, explicit operator bool() constChecks whether a snapshot is currently owned.
void reset() noexceptReleases ownership.
static snapshot take(connection&, std::string_view schema = "main")Captures a snapshot for schema.
void open(connection&, std::string_view schema = "main") constMoves the connection's read transaction back to the captured snapshot.
sqlite3_snapshot* native_handle() const noexceptExposes the raw pointer for advanced use cases.

Journal helpers

FunctionDescription
wal_mode set_wal_mode(connection&, wal_mode mode)Forces a specific PRAGMA journal_mode.
wal_mode enable_wal(connection&, bool prefer_wal2 = false)Turns on WAL (or WAL2 when supported).
wal_mode get_wal_mode(connection&)Returns the current journal mode.
std::string_view to_string(wal_mode)Converts an enum value to its PRAGMA string.
constexpr bool snapshots_supported() noexceptIndicates whether SQLITE_ENABLE_SNAPSHOT is available.