Idempotent updating (Update or insert)

2,619 views
Skip to first unread message

Nickle

unread,
Nov 25, 2010, 11:02:52 AM11/25/10
to sqlalchemy
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?

Nick

Michael Bayer

unread,
Nov 25, 2010, 12:05:58 PM11/25/10
to sqlal...@googlegroups.com

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 sqlal...@googlegroups.com.
> To unsubscribe from this group, send email to sqlalchemy+...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
>

Nick Leaton

unread,
Nov 25, 2010, 12:10:11 PM11/25/10
to sqlal...@googlegroups.com
Thanks Michael,

I'll check the two articles out tonight

Nick

--
Nick

Reply all
Reply to author
Forward
0 new messages