On Apr 8, 2011, at 12:59 PM, gwozdziu wrote:

> 
> #before executing this code we have object with id = 5 in our database
> 
> obj = self.mapper.get_from_dto(dto)  # creating the object from values
> provided by user , this object has id = 5
> self.mapper.add(obj) # we are putting new object (with id = 5).
> It
> conflicts with already existing object
> self.mapper.commit() # commit. New object overrides old one

this all depends on what get_from_dto() does.  If it says:

        obj = MyObject(<values from the user>)

now "obj" is known as "transient".  When you add() it to the session, it 
becomes "pending".  When flush() proceeds, you will get an Integrity Error if 
ID # 5 already exists.   If you want to merge the values from MyObject onto a 
possibly already existing object in the DB, you use merge:   obj = 
session.merge(obj).

On the other hand, if get_from_dto() says:

        obj = session.query(MyObject).get(5)

then "obj" is "persistent", and is already in the session.   Calling 
session.add(obj) has no net change.   There's no error but also nothing has 
actually happened.

Finally, if get_from_dto() is more like:

        obj = some_other_session.query(MyObject).get(5)
        some_other_session.close()

then "obj" is detached.    When you call session.add(obj), "obj" becomes the 
object that represents row #5 in the session.    This might be what you're 
looking for, but this is an unusual case.   There is of course no error because 
you are handing the Session an object that is detached, and becomes persistent 
again - it represents row #5 from the database already, so its the correct row, 
though it may be out of date.   If you've done something to it that you don't 
want to persist, that's more on your end, but it's a little strange your 
application isn't able to be aware of that much sooner.

Anyway, you can test for "identity" using:

        from sqlalchemy.orm.util import has_identity
        if not has_identity(obj):
                session.add(obj)

if the case is as simple as, the row is out of date and you want to guard 
against that, you can use a version_id_col for that use case - it will raise if 
the version you give to the session is older than what's currently in the 
database.

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to