From e93aba2bae8e76d1b1d2d9493742aa93c2b1b27b Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Sun, 8 Oct 2023 16:02:30 +0100 Subject: Use unique_ptr for handling unescaped bytea column buffer --- libpqpp/pq-column.cpp | 21 +++++---------------- libpqpp/pq-column.h | 13 +++++++++++-- 2 files changed, 16 insertions(+), 18 deletions(-) (limited to 'libpqpp') diff --git a/libpqpp/pq-column.cpp b/libpqpp/pq-column.cpp index cd0d60c..f78863c 100644 --- a/libpqpp/pq-column.cpp +++ b/libpqpp/pq-column.cpp @@ -9,22 +9,13 @@ #include #include #include -#include #include PQ::Column::Column(const SelectBase * s, unsigned int i) : - DB::Column(PQfname(s->execRes, static_cast(i)), i), sc(s), oid(PQftype(sc->execRes, static_cast(colNo))), - buf(nullptr) + DB::Column(PQfname(s->execRes, static_cast(i)), i), sc(s), oid(PQftype(sc->execRes, static_cast(colNo))) { } -PQ::Column::~Column() -{ - if (buf) { - PQfreemem(buf); - } -} - bool PQ::Column::isNull() const { @@ -97,12 +88,10 @@ PQ::Column::apply(DB::HandleField & h) const h.timestamp(boost::posix_time::time_from_string(value())); break; case BYTEAOID: { - if (buf) { - PQfreemem(buf); - } - size_t len; - buf = PQunescapeBytea(reinterpret_cast(value()), &len); - h.blob(DB::Blob(buf, len)); + size_t len = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + buf = BufPtr {PQunescapeBytea(reinterpret_cast(value()), &len)}; + h.blob(DB::Blob(buf.get(), len)); break; } } diff --git a/libpqpp/pq-column.h b/libpqpp/pq-column.h index f86958e..d3400bf 100644 --- a/libpqpp/pq-column.h +++ b/libpqpp/pq-column.h @@ -11,7 +11,6 @@ namespace PQ { class Column : public DB::Column { public: Column(const SelectBase *, unsigned int field); - ~Column() override; [[nodiscard]] bool isNull() const override; void apply(DB::HandleField &) const override; @@ -31,8 +30,18 @@ namespace PQ { const SelectBase * sc; const Oid oid; + // Buffer for PQunescapeBytea - mutable unsigned char * buf; + struct pq_deleter { + void + operator()(unsigned char * p) + { + PQfreemem(p); + } + }; + + using BufPtr = std::unique_ptr; + mutable BufPtr buf; }; } -- cgit v1.2.3