RAII connections
A RAII connection is a C++ object that opens a database handle in its constructor and closes it in its destructor. Statements and transactions get the same treatment. You do not call sqlite3_close on a dozen error paths by hand.
Detailed Explanation
The C APIs (sqlite3_open, PQconnectdb) return raw handles. Every early return and every exception must close them. The C++ habit is a small class — or unique_ptr with a deleter — that owns the handle.
SQLite:
struct Sqlite {
sqlite3* db = nullptr;
explicit Sqlite(const char* path) {
if (sqlite3_open(path, &db) != SQLITE_OK) throw ...;
}
~Sqlite() { if (db) sqlite3_close(db); }
Sqlite(const Sqlite&) = delete;
Sqlite& operator=(const Sqlite&) = delete;
};
Statements: a Stmt type that finalizes. libpqxx already is this: connection and work are RAII. SOCI session is RAII. Do not wrap those again unless you are pooling.
Move-only is the right default. Copying a connection is not a second session; it is two owners of one socket. unique_ptr<sqlite3, closer> is enough if you do not want a named class.
Order: destroy statements before the connection. Destroy the transaction before the connection (commit or rollback first). Declare the connection first so it dies last.
Pools: the RAII object you hand to a request may be a checkout guard: constructor takes a connection from the pool, destructor returns it. The underlying socket stays open. That is still RAII; the resource is "the checkout", not "the TCP connection".
Thread: the RAII object does not make the handle thread-safe. Do not check out one SQLite connection to two threads.
Failure to open: throw from the constructor (or return optional). A half-open object with a boolean ok is how people forget to close the failure path. If sqlite3_open fails it may still return a handle that must be sqlite3_closed — check the SQLite docs and close on error too.
Code Examples
#include <memory>
#include <sqlite3.h>
#include <stdexcept>
struct SqliteClose {
void operator()(sqlite3* db) const { if (db) sqlite3_close(db); }
};
using Sqlite = std::unique_ptr<sqlite3, SqliteClose>;
Sqlite openMemory() {
sqlite3* raw = nullptr;
int rc = sqlite3_open(":memory:", &raw);
Sqlite db(raw);
if (rc != SQLITE_OK) throw std::runtime_error(sqlite3_errmsg(raw));
return db;
}
int main() {
auto db = openMemory();
return db ? 0 : 1;
}#include <pqxx/pqxx>
void insert(pqxx::connection& c, int id) {
pqxx::work txn(c); // begin
txn.exec_params("insert into t(id) values ($1)", id);
txn.commit(); // without this, ~work rolls back
}Common Gotchas
`sqlite3_open` error still needs `close`
the API can return a handle plus an error code. RAII should own whatever was returned.
Statement after connection in declaration order
`~Stmt` then `~Conn` is what you want. Reverse them and finalize hits a closed db.
libpqxx `work` rollback on destroy
forgetting `commit` is silent data loss, not a leak.