Threading tip: SQLAlchemy / Elixir

22 December 2007 | Modified: 22 December 2007

I was having some trouble saving new object in SQLAlchemy / Elixir when created in a different thread than the one that loaded the collection. The errors I got were "object already attached to session". First I tried to have one global session but sqlite complained terribly. Then after some searching I found out the recommended approach in SQLAlchemy.

session.merge(object) #move object to session of current thread
object.flush() #flush/save as normal as object is now in correct session

and deleting works like this:

td = object
td.expunge()
session.merge(td)

td.update()
td.delete()

session.flush()

Stupid oversight I know, but it's not exactly spelled out in the documentation.