SQLAlchemy - select for update example

python, select-for-update, sqlalchemy

Solution

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

Problem

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

Original source