SOCI
SOCI is a C++ database access library with a stream-like API (sql << "select ...", soci::into(x)). One frontend, several backends: PostgreSQL, SQLite, MySQL, Oracle, ODBC. You write C++ types; the backend talks to the driver.
Detailed Explanation
Raw libpq and sqlite3 look different. SOCI is the adapter: soci::session sql(soci::postgresql, "dbname=app"); or soci::sqlite3, "file.db". Statements use << to send SQL and use / into to bind. Transactions are soci::transaction tr(sql).
The library is not an ORM. You still write SQL. You still own schema. You get type conversion (int, string, boost::optional / std::optional depending on version), rowsets, and a connection pool (connection_pool).
Why people pick it: one API across SQLite in tests and Postgres in production (the SQL dialect still differs — SERIAL vs AUTOINCREMENT). Why people skip it: the stream API is unusual, Boost shows up in older releases, and a thin wrapper over libpqxx or sqlite3 can be smaller.
Backends are separate libraries you link (libsoci_postgresql). A missing backend is a link error, not a runtime surprise if you do not instantiate it.
Sessions are not thread-safe. Use one session per thread or a pool. RAII: session closes on destroy. Do not keep a session after the pool recycled it.
Error handling: SOCI throws soci_error (or you configure a different policy in some versions). Catch at the service boundary. Check sql.got_data() after a select into a single variable.
Prepared statements: statement st = (sql.prepare << "select name from t where id = :id", use(id), into(name)); st.execute(true);. Named parameters (:id) are SOCI's portable bind style. The backend translates them.
Do not concatenate SQL. use exists so you do not.
Code Examples
#include <soci/soci.h>
#include <soci/sqlite3/soci-sqlite3.h>
#include <iostream>
#include <string>
int main() {
soci::session sql(soci::sqlite3, ":memory:");
sql << "create table t(id integer, name text)";
sql << "insert into t(id, name) values(1, 'ada')";
std::string name;
sql << "select name from t where id = :id", soci::use(1), soci::into(name);
std::cout << name << '\n'; // prints: ada
}Common Gotchas
SQL is not fully portable
SOCI will not rewrite `RETURNING` for SQLite. Keep dialect-specific strings behind a seam.
Sharing a `session` across threads
undefined. Pool or thread-local.
`into` on an empty result
`got_data()` is false; the variable may be unchanged. Check.
Link the backend you construct
`soci::postgresql` needs the postgres backend .so/.lib.