[odb-users] indirect relatioship between objects with std::vector<boost::variant<...>>

MM finjulhich at gmail.com
Tue May 15 08:56:45 EDT 2018


On 14 May 2018 at 16:04, Boris Kolpackov <boris at codesynthesis.com> wrote:
>
> MM <finjulhich at gmail.com> writes:
>
> > struct X {};
> > struct Y {};
> >
> > struct Aelt {
> >  boost::variant<X*, Y*> elt_;
> > };
> > struct A {
> >   std::vector<Aelt> elements_;
> > };
> > using nstring = odb::nullable<std::string>;
> >
> > #pragma db value(Aelt) definition
> > #pragma db member(Aelt::elt_) transient
> > #pragma db member(Aelt::X) virtual(nstring) get(...) set(...)   //// can be NULL
> > #pragma db member(Aelt::Y) virtual(nstring) get(...) set(...)   //// can be NULL
> > /// The getter and setter just stores the name of X or the name of Y
> >
> > #pragma db object(A) definition
> > #pragma db member(A::elements_)
> >
> > This however does not store the X/Y objects themselves if they haven't
> > been persisted.
> >
> > If I want to have odb persist/load Xs and Ys when I persist A
> > instances, I would need to implement that myself in get(...) and
> > set(...), but I feel I'd be going about that incorrectly.
>
> While I am fuzzy on what exactly you are trying to achieve, if you
> want the object pointer/relationship functionality, then you will
> need to make Alert::X and Alert::Y object pointers.
>
> Boris

Apologies, let me clarify a bit.

"A"  is a object which holds a collection of elements. These elements
are of type "Aelt", short for "A element"
Each element is a wrapper around either a pointer to X, or a pointer
to Y, that is:
the wrapper has a member that is a variant (pointer to X, pointer to Y)

Obviously as things are, there's no "object pointer/relationship functionality"

Let's start with an empty database, and imagine we have a transient
instance of A, with a vector of 10 elements, each of a which wraps a
variant that points to a X instance or a Y instance.

The behavior that I'm looking for is that if I persist A, then, I
would want my odb pragmas to persist the Xs and the Ys, but only if
they are not persisted already.
Similarly,  if I load A, and the Xs and Ys instances are not loaded
already, I'd want to load them as well.

I am sorry: Is what I'm trying to achieve a little clearer?

I followed the suggestion for storing the variant member as 2 nullable
columns, 1 for X, 1 for Y.  X and Y have string ids.
Do I have to implement the  get(...) and set(...) of those virtual
columns in such a way that they check whether a X/Y instance exists
before storing it or loading it?

Thank you



More information about the odb-users mailing list