13

I'm trying to explicitly lock a postgres table using this sqlalchemy command:

db.engine.execute('BEGIN; LOCK TABLE database_version IN ACCESS EXCLUSIVE MODE;')

After this executes, if I go into the database client and run:

select * from pg_catalog.pg_locks;

There aren't any ACCESS EXCLUSIVE locks present.

If instead, I run the first command, but from inside the db client, it works as expected.

Is there a reason trying to get a table lock from sqlalchemy isn't working correctly?

Ideally, I want only one process to be able to query from and insert into the database_version table at a time.

2
  • When you say "after this executes", do you keep the connection open somehow? Does the script that executed that statement exit?
    – univerio
    May 19, 2016 at 20:34
  • I put a time.sleep(20) in there after that line to give me time to switch over to the client and run the query.
    – Andrew
    May 20, 2016 at 12:03

2 Answers 2

13

So it turns out that I needed to start a nested transaction from the session object instead of trying to BEGIN one using straight SQL.

db.session.begin_nested()
db.session.execute('LOCK TABLE database_version IN ACCESS EXCLUSIVE MODE;')

Then, i insert the new row:

new_version = DatabaseVersion(version=version + 1)
db.session.add(new_version)
db.session.commit()

and then finally commit again to close out the nested transaction:

db.session.commit()
1

with_lockmode("...") is now deprecated in sqlalchamy, see a reference here: https://kite.com/python/docs/sqlalchemy.orm.Query.with_lockmode

The solution now is to use:

session.query(database_version).with_for_update()
1
  • This doesn't seem to lock the table. I tested with the 2 simple, identical that do this on the same table and then sleep for 10 seconds. They both were able to get the lock. Andrew's answer OTOH does work (only 1 script gets the lock at the same time).
    – Garrett
    Nov 18, 2021 at 21:46

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.