[odb-users] PostgreSQL & uuid type

Boris Kolpackov boris at codesynthesis.com
Fri May 18 10:36:21 EDT 2012


Hi,

Xentrea <meow at xentrea.me> writes:

> How mapping *char *or *unsigned char* to *uuid* for PostgreSQL database?
> 
> For example  (didn't work) :(
> 
> typedef std::vector<char> uuid;
> #pragma db value(uuid) type("UUID")
> 
> #pragma db object
> class object
> {
>   ...
> 
>   uuid id_; //
> };

At the moment we don't provide a default mapping for Postgres UUID type
mainly because there is no single "default" C++ type. Possible options
are std::vector<[unsigned] char> and [unsigned] char[16]. std::vector
seems a bit wasteful and char[16] could be a bit too low-level (i.e.,
such a mapping will be difficult to use as an object id).

But you can always provide your won mapping. This thread describes the
overall procedure in detail:

http://www.codesynthesis.com/pipermail/odb-users/2012-March/000482.html

For the PostgreSQL UUID type, the traits function signatures are as
follows:

static void
set_value (value_type&, const unsigned char*, bool is_null);

static void
set_image (unsigned char*, bool& is_null, const value_type&);

For example, here is an implementation for std::vector<unsigned char>:

#include <vector>
#include <memory>
#include <cassert>

#include <odb/pgsql/traits.hxx>

namespace odb
{
  namespace pgsql
  {
    template <>
    class value_traits<std::vector<unsigned char>, id_uuid>
    {
    public:
      typedef std::vector<unsigned char> value_type;
      typedef std::vector<unsigned char> query_type;
      typedef unsigned char* image_type;

      static void
      set_value (value_type& v, const unsigned char* i, bool is_null)
      {
        if (is_null)
          v.clear ();
        else
          v.assign (i, i + 16);
      }

      static void
      set_image (unsigned char* i, bool& is_null, const value_type& v)
      {
        is_null = v.empty ();

        if (!is_null)
        {
          assert (v.size () == 16);
          std::memcpy (i, &v.front (), 16);
        }
      }
    };
  }
}

Boris



More information about the odb-users mailing list