M. XX.
M. XX.

Reputation: 61

How to read an array of pairs result from libpqxx into C++

I have a Postgres function returning the type tp_m_info which contains an array of pairs (see below). And I'm using libpqxx to connecting to Postgres.

CREATE TYPE public.tp_m_set_id AS
(
    m_id integer,
    m_name text
);


CREATE TYPE public.tp_m_info AS
(
    m_id integer,
    m_name text,
    m_value double precision,
    m_is_true boolean,
    original_ms tp_m_set_id[]
);

I can read int, double, str and even Boolean from the result:

iter[m_id].as<int>()
iter[m_name].c_str()
iter[m_value].as<double>()

// and bool like
std::string tmp_str = iter["m_is_true"].c_str();
if ("t" == tmp_str)
{
    info.m_is_merged = true;
}
else
{
    info.m_is_merged = false;
}

but I don't know how to handle "tp_m_set_id[]" It failed with something like "std::vector<std::pair<uint32_t, std::string>>"

iter[original_ms].as<std::vector<std::pair<uint32_t, std::string>>>()

Any Idea how to get it?

In "libpq" there is binary resultFormat with: PQexecParams() and paramFormats=1 see: https://www.postgresql.org/docs/10/libpq-exec.html

Is there a binary Format in "libpqxx" now? Has something changed in the last 10 years? see: http://pqxx.org/development/libpqxx/wiki/BinaryTransfers

Is there a fast way to get a block of compound data from libpqxx and convert it to C++?

Upvotes: 1

Views: 1300

Answers (1)

M. XX.
M. XX.

Reputation: 61

I guess the solution is

e.g. to use:

std::pair<int, int> my_pair = row["m_ints"].as<std::pair<int, int> >();

write into strconv.hxx:

template<> struct PQXX_LIBEXPORT string_traits<std::pair<int, int> >
{                                   
static constexpr const char *name() noexcept { return "std::pair<int, int>"; }
static constexpr bool has_null() noexcept { return false; }     
static bool is_null(std::pair<int, int>) { return false; }
[[noreturn]] static std::pair<int, int> null()
{ internal::throw_null_conversion(name()); }            
static void from_string(const char Str[], std::pair<int, int> &Obj);
static std::string to_string(std::pair<int, int> Obj);
};

and in strconv.cxx implement:

  • static void from_string(const char Str[], std::pair &Obj);
  • static std::string to_string(std::pair Obj);

now you have to recompile libpqxx.

The problem is, the implementation of "from_string" ends up in stringparsing a string like "(9,5)". And Stringparsing is not what i want.

so i'm going to try libpq.

Upvotes: 0

Related Questions