SQLAlchemy - select for update example

user317033 picture user317033 · Apr 10, 2012 · Viewed 36.1k times · Source

I'm looking for a complete example of using select for update in SQLAlchemy, but haven't found one googling. I need to lock a single row and update a column, the following code doesn't work (blocks forever):

s = table.select(table.c.user=="test",for_update=True)
# Do update or not depending on the row
u = table.update().where(table.c.user=="test")         
u.execute(email="foo") 

Do I need a commit? How do I do that? As far as I know you need to: begin transaction select ... for update update commit

Answer

Matthew Moisen picture Matthew Moisen · Mar 4, 2017

If you are using the ORM, try the with_for_update function:

foo = session.query(Foo).filter(Foo.id==1234).with_for_update().one()
# this row is now locked

foo.name = 'bar'
session.add(foo)

session.commit()
# this row is now unlocked