Re: libpq usage from C++

From: Dominique Devienne <ddevienne(at)gmail(dot)com>
To: Igor Korot <ikorot01(at)gmail(dot)com>
Cc: "pgsql-generallists(dot)postgresql(dot)org" <pgsql-general(at)lists(dot)postgresql(dot)org>
Subject: Re: libpq usage from C++
Date: 2026-03-16 10:25:15
Message-ID: CAFCRh-8+GXA+j0qyccc+Yj3TWZy7Uy1v8V_ohqC8D9u7+j3ZUg@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Sat, Mar 14, 2026 at 5:41 AM Igor Korot <ikorot01(at)gmail(dot)com> wrote:
> Does anybody use libpq from C++?

Yes

> C++ introduces STL.
> C++ introduces smart-pointers.
> Is there a simple way of using those writing libpq communication?
> Or should I just forget about them and use good old "dump pointers"?

Using an existing wrapper is simplest, of course.
We wrote our own. To each its own. E.g.

PS: Avoid the fwd-decl by using the actual libpq headers instead.

extern "C" {

struct pg_conn;
struct pg_result;
typedef struct pg_conn PGconn;
typedef struct pg_result PGresult;
typedef struct _PQconninfoOption PQconninfoOption;
typedef struct pgNotify PGnotify;
void PQfreemem(void *ptr);
void PQclear(PGresult* res);
void PQfinish(PGconn* conn);
void PQconninfoFree(PQconninfoOption* conn);

} // extern "C"

namespace acme::postgresql {

struct PGDeleterFunctor {
void operator()(PGresult* r) {
if (r != nullptr) {
PQclear(r);
}
}
void operator()(PGconn* c) {
if (c != nullptr) {
PQfinish(c);
}
}
void operator()(PQconninfoOption* c) {
if (c != nullptr) {
PQconninfoFree(c);
}
}
void operator()(PGnotify* n) {
if (n != nullptr) {
PQfreemem(n);
}
}
};
using PGresult_uptr = std::unique_ptr<PGresult, PGDeleterFunctor>;
using PGconn_uptr = std::unique_ptr<PGconn, PGDeleterFunctor>;
using PGconninfo_uptr = std::unique_ptr<PQconninfoOption, PGDeleterFunctor>;
using PGnotify_uptr = std::unique_ptr<PGnotify, PGDeleterFunctor>;

...
}

Then we have higher-level wrappers that compose those RAII low-level ones. --DD

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Greg Sabino Mullane 2026-03-16 13:53:11 Re: Does included columns part of the PK
Previous Message Ishan joshi 2026-03-16 06:04:51 Re: Replication to standby broke with WAL file corruption