[odb-users] Persisting objects after ID change

Boris Kolpackov boris at codesynthesis.com
Tue Dec 30 08:40:42 EST 2014


Hi Erez,

Erez Pics <picserez at gmail.com> writes:

> The flow: I have an ODB object that has been persisted before with a
> temp identifier, I set a new value to it's identity field and call
> data_base->update(object), the result "object not persistent"
> exception, ODB refuses to update an existing object to use the new
> identifier.

The whole ODB architecture assumes that object identifiers are
immutable. In fact, conceptually, saying something like "I set
a new value to it's identity field" doesn't make sense since
if you change the object's identity, it is no longer the same
object. Or, to put it in more technical terms, when you call
update(), underneath, ODB executes "UPDATE ... WHERE id = ?"
with the value for id coming from the object identifier member.
But, since its value you have changed, ODB will not be able to
find the original row in the database.

This is why in my original reply to your idea of using negative
id values to indicate a special object state I suggested that
a separate flag might be a cleaner solution.

But, if you still want to update the object id, there is a way,
not a very elegant one, though. The idea is to map another special
class to the same table that would allow you to change the id.
Here is an outline:

#pragma db object table("my_object")
class my_object // You original object.
{
  ...

  #pragma db id column("id")
  unsigned int id;
};

#pragma db object table("my_object")
struct my_object_id
{
  my_object_id (unsigned int o, unsigned int n): old_id (o), new_id (n) {}

  #pragma db id column("id")
  unsigned int old_id;

  #pragma db column("id")
  unsigned int new_id;
};

my_object o = ...;

db.update (my_object_id (o.id, -o.id));

Note that my_object_id should come after my_object in the header file
in order to get the correct table definition in the generated schema.

Boris



More information about the odb-users mailing list