1

When a method declared in a model, is there a lock when the method is called that is only unlocked when the session is committed or the method returns?

For example, I declare an SQLAlchemy model as follow:

class FooModel(Base):
    bar = db.Column(db.Integer, default=0)

    def increase_bar():
        self.bar += 1
        db.session.add(self)
        db.session.commit()

(I'm using Flask-SQLAlchemy)

If there are two requests that call foo.increase_bar() at the same time, would foo.bar increase by two (there is a lock and the method is atomic) or just by one (there is no lock and there is a concurrency problem)?

If it is not atomic, is there a way I can make it be?

Huy Ngo
  • 125
  • 9
  • 1
    Related: https://stackoverflow.com/questions/9667138/how-to-update-sqlalchemy-row-entry, https://stackoverflow.com/questions/2334824/how-to-increase-a-counter-in-sqlalchemy, – Ilja Everilä Aug 21 '20 at 05:32
  • @IljaEverilä So if I understand correctly, instead of writing `self.bar += 1` here, I should've written `self.bar = FooModel.bar + 1`? – Huy Ngo Aug 21 '20 at 06:48
  • 1
    Yes, if not using explicit locking, for example SELECT ... FOR UPDATE, or a transaction isolation level that enforces (as if) serial execution. – Ilja Everilä Aug 21 '20 at 07:47

0 Answers0