A sqlite::connection is the one-stop RAII wrapper around a raw
sqlite3* handle. Opening or closing a database, checking the last inserted
rowid, attaching extra files, or tweaking the shared statement cache all flow through
this type. The wrapper enforces the project’s threading guideline: keep a connection
bound to a single thread unless you explicitly opt into connection_pool.
Use cases
- Guarantees the handle is closed in the destructor, even if you forget to call
close. - Implements the “open modes” (read-only, existing-only, create, always-create) so
failures are surfaced as rich
database_exceptionvariants. - Owns the LRU statement cache; higher-level helpers such as
queryandexecutereuse prepared statements by default. - Provides attach/detach utilities that mirror SQLite’s SQL primitives but still honor filesystem adapters and error handling.
Example usage
sqlite::connection db{"/var/data/app.db",
sqlite::open_mode::open_or_create};
// Guarded by the destructor: transactions roll back when scope exits.
sqlite::transaction tx{db, sqlite::transaction_type::immediate};
sqlite::execute ddl{db, R\"SQL(
CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY, value TEXT)
)SQL\", true};
sqlite::execute upsert{db, "INSERT OR REPLACE INTO settings VALUES(?, ?)"};
upsert % "timezone" % "UTC";
upsert();
tx.commit();
In tests I usually flip to open_mode::always_create and hand in a temp
filesystem adapter so every run starts from an empty file.
enum class open_mode
open_readonly— open an existing database for reads.open_existing— fail if the database is missing.open_or_create— create the database if it does not exist.always_create— remove any existing file before creating a new database.
Constructors & basic operations
| Member | Description |
|---|---|
connection(std::string const& db) | Opens or creates db using default flags. |
connection(std::string const& db, filesystem_adapter_ptr fs) | Injects a custom filesystem adapter. |
connection(std::string const& db, open_mode mode) | Opens the database with the desired behavior. |
connection(std::string const& db, open_mode mode, filesystem_adapter_ptr fs) | Combines both customizations. |
connection(connection const&)=delete, connection& operator=(connection const&)=delete | Connections cannot be copied. |
~connection() | Closes the database handle. |
void attach(std::string const& db, std::string const& alias) | Executes ATTACH DATABASE. |
void detach(std::string const& alias) | Executes DETACH DATABASE. |
std::int64_t get_last_insert_rowid() | Returns sqlite3_last_insert_rowid. |
Statement cache
| Member | Description |
|---|---|
void configure_statement_cache(statement_cache_config const& cfg) | Adjusts capacity/enabled flags. |
statement_cache_config statement_cache_settings() const | Returns current cache configuration. |
void clear_statement_cache() | Flushes all cached statements. |