[Libpqxx-general] Dealing with resultsets that include user-defined-types

Jeroen Vermeulen jtv at xs4all.nl
Wed Apr 22 09:19:45 UTC 2009


Maurice Gittens wrote:

> The result set includes a User defined Type.
> 
> What is the recommended way to retrieve the user defined type using pqxx?
> 
> I'm hoping I can write something like: resultset[0][0].as<std::pair<int, 
> std::string>>();
> I could not find any examples of this sort of thing.
> 
> Any pointers?

To do this, you need to teach libpqxx to convert between the client-side 
version of the type (in this case, pair<int, string>) and the string 
representation.

You do that by specializing the pqxx::internal::string_traits template 
for the client-side type.  See include/pqxx/strconv.hxx for the declaration.

It might look something like this:

typedef std::pair<int, std::string> my_type;

namespace pqxx
{
namespace internal
{
template<> struct string_traits<my_type>
{

   static const char *name() { return "my type"; }
   static bool has_null() { return true; }
   static bool is_null(my_type) { return my_type.first == -1; }
   static my_type null() { return make_pair(-1, std::string()); }

   // Convert from string representation to my_type.
   static void from_string(const char[], my_type &);

   // Convert from my_type to string representation.
   static std::string to_string(my_type);
};
} // namespace internal
} // namespace pqxx


In this example I'm assuming that an int value of -1 means that the 
object is null.  I've left the parsing & generation of strings to you.  :-)


Jeroen


More information about the Libpqxx-general mailing list