Here's a pattern that I see a lot that SQLAlchemy doesn't really seem to
support: update a row if it exists, or insert it if it doesn't.

Imagine you're writing a web spider, so you've got a table with a
primary key of the URL, with another column for the page's body.  Your
spider comes across a page which it might or might not have seen before.
What it should do is try to insert the page, and if that fails with a
duplicate key error, then try to update it.  There is no way to do this
in one line in SQLAlchemy, but there should be.

1. save_or_update does not work, because it does not try the insert and
catch a failure; it merely checks to see if the object in the session is
marked as being already persisted.  When it does try the insert, if the
object with that primary key is already there, it fails.

2. You could do it the long way: 
try:
  page = Page (url = url, body = body)
  Session.save(page)
  Session.commit()
except IntegrityError:
  Session.close()
  page = Session.query(Page).filter(url = url)...
  page.body = body
  Session.save(page)
  Session.commit()
  
But boy is that a lot of lines!  What I want to do is:

  page = Page (url = url, body = body)
  Session.insert_or_update(page)
  Session.commit()

Is this functionality there, and I just don't understand it?


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com
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