Modern C++ RAII wrapper around PostgreSQL libpq.
This repository is prepared as a reusable module that can be integrated into a different project, while still being executable standalone for local integration testing.
src/db/pg.hpp/src/db/pg.cpp: Core wrapper (PgConn,Result,Tx,PgError)examples/basic_usage.cpp: Example executabletests/integration_smoke.cpp: Integration smoke test (runs against real PostgreSQL)docker-compose.yml: Local PostgreSQL service.env.example: Environment template
- CMake 3.20+
- C++17 compiler
- Windows: MSVC (Visual Studio 2022) or MinGW
- Linux/macOS: GCC/Clang
- PostgreSQL client development package (
libpq)
vcpkg install libpq:x64-windowsThen configure CMake with the vcpkg toolchain:
cmake -S . -B build `
-DCMAKE_TOOLCHAIN_FILE=C:/path/to/vcpkg/scripts/buildsystems/vcpkg.cmakesudo apt-get update
sudo apt-get install -y build-essential cmake libpq-devsudo dnf install -y gcc-c++ cmake postgresql-devel- Copy
.env.exampleto.envand adjust credentials if needed. - Start database:
docker compose up -d- Verify health:
docker compose pscmake -S . -B build -DLIBPQ_CPP_BUILD_EXAMPLES=ON -DLIBPQ_CPP_BUILD_TESTS=ONcmake --build build --config ReleaseSet connection info first:
$env:PG_CONNINFO="host=127.0.0.1 port=5432 dbname=mydb user=myuser password=mypass"export PG_CONNINFO="host=127.0.0.1 port=5432 dbname=mydb user=myuser password=mypass"Run:
./build/example_basicOn multi-config generators (Visual Studio), binary can be under build/Release/.
ctest --test-dir build --output-on-failureIntegration test behavior:
- Creates table if needed
- Inserts one row
- Validates query output
- Rolls back transaction for deterministic state
cmake --install build --prefix installInstalled items:
include/db/pg.hpplib/<library files>- CMake export targets under
lib/cmake/libpq_cpp
add_subdirectory(external/libpq_cpp)
target_link_libraries(your_app PRIVATE libpq_cpp::libpq_cpp)In your source:
#include "db/pg.hpp"After cmake --install ...:
list(APPEND CMAKE_PREFIX_PATH "/path/to/libpq_cpp/install")
find_package(libpq_cpp REQUIRED CONFIG)
target_link_libraries(your_app PRIVATE libpq_cpp::libpq_cpp)host=127.0.0.1 port=5432 dbname=mydb user=myuser password=mypass
If PG_CONNINFO is not set, example and tests use this default.
Could NOT find PostgreSQL:- Install
libpqdev package. - On Windows with vcpkg, pass
CMAKE_TOOLCHAIN_FILE.
- Install
- Linker errors for
PQ*symbols:- Ensure your target links to
libpq_cpp::libpq_cpp. - Ensure
find_package(PostgreSQL REQUIRED)succeeds.
- Ensure your target links to
- Runtime connection failure:
- Check
docker compose ps. - Check credentials in
.envandPG_CONNINFO.
- Check