[odb-users] Storing a UUID as binary(16) in mysql

Boris Kolpackov boris at codesynthesis.com
Mon Jul 30 08:15:00 EDT 2012


Hi Trevor,

Trevor Gattis <trevor at trevorgattis.com> writes:

> I'm wondering if anyone has come across a solution for storing a
> boost::uuids::uuid member value automagically as a binary(16) in 
> our mysql database.

We should probably support this in the Boost profile (added to the
TODO list). In the meantime, you will need to provide a custom
value_traits specialization. Something along these lines:

// uuid-traits.hxx
//
#ifndef UUID_TRAITS_HXX
#define UUID_TRAITS_HXX

#include <cstring> // std::memcpy
#include <cstddef> // std::size_t
#include <cassert>

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/nil_generator.hpp>

#include <odb/mysql/traits.hxx>

namespace odb
{
  namespace mysql
  {
    template <>
    struct default_value_traits< ::boost::uuids::uuid, id_blob>
    {
      typedef ::boost::uuids::uuid value_type;
      typedef ::boost::uuids::uuid query_type;
      typedef details::buffer image_type;

      static void
      set_value (value_type& v,
                 const details::buffer& b,
                 std::size_t n,
                 bool is_null)
      {
        if (is_null)
          v = ::boost::uuids::nil_uuid ();
        else
        {
	  assert (n == 16);
          std::memcpy (v.data, b.data (), 16);
        }
      }

      static void
      set_image (details::buffer& b,
                 std::size_t& n,
                 bool& is_null,
                 const value_type& v)
      {
        is_null = false;
        n = 16;

        if (n > b.capacity ())
          b.capacity (n);

        std::memcpy (b.data (), v.data, 16);
      }
    };
  }
}

#endif

Assuming this is saved in uuid-traits.hxx, you can then compile your
header like this:

odb ... --odb-epilogue '#include "uuid-traits.hxx"' ...

And in your header itself you can write:

#include <boost/uuid/uuid.hpp>

#pragma db value(boost::uuids::uuid) type("BINARY(16)")

#pragma db object
class object
{
  ...

  boost::uuids::uuid id;
};

Boris



More information about the odb-users mailing list