On Nov 25, 2010, at 11:02 AM, Nickle wrote:

> I'm trying to get my head around idempotent updating.
> 
> ie I'm creating some objects, I want to store them. These objects
> might or might not be already stored in the database. If they are, I
> want to update them if necessary  (a field has changed), or insert
> them if they do not exist.
> 
> What's the preferred approach?

>From a SQL perpsective there's a SELECT of the row, then an INSERT or UPDATE 
>based on the result of the SELECT, unless you're using an extended form of SQL 
>such as MySQL's REPLACE.

While there are ways to use REPLACE and similar, the ORM standardizes on the 
old fashioned way.    The Session.merge() method implements one form of this 
operation.  If you have the primary key of the object ahead of time, using 
merge() will accept the given object as "state" and look up the PK if exists, 
else create. copying the state you give it onto the one in the session.  
merge() is powerful since it runs along cascade lines to operate on a whole 
series of objects at once (and as such can be tricky).   Lots of documentation 
at 
http://www.sqlalchemy.org/docs/orm/session.html?highlight=merge#unitofwork-merging
 .

For simple cases like looking up a tag or keyword, as well as cases where you 
don't have the primary key up front, there's a recipe that illustrates one way 
to create an object interface that hides most of this detail at 
http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject .


> 
> Nick
> 
> -- 
> 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.
> 

-- 
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