1

Let's say I have a tabel similar to this one:

PERSON:

id | person_name 

ITEM:

id | name | person_id

Items person_id is a FK to person.

I have an operation that add's items in bulk to a person. But I want to make sure no other processes are adding items concurrently to this person without blocking the entire person table.

Is there a way to achieve this in Postgres? And better a the code to accomplish this using Python SQLalchemy?

0

2 Answers 2

2

I think you want to use SELECT FOR UPDATE via Query.with_for_update. Just a warning though you have to be carefully to always lock in the same order and same way or else you can easily lockup your threads. Ie. don't lock table A then lock table B in one area of code and lock table B and then table A in another area of code because it can cause a deadlock.

# Other calls to SELECT FOR UPDATE will BLOCK when they try to lock this person
person = session.query(Person).with_for_update().filter(Person.id == 5).first()

# Update person items here
for item in person.items[0:3]:
    session.delete(item)

session.commit()

https://docs.sqlalchemy.org/en/14/orm/query.html?highlight=for_update#sqlalchemy.orm.Query.with_for_update

https://www.postgresql.org/docs/9.0/sql-select.html#SQL-FOR-UPDATE-SHARE

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much :) this is just what I needed
0

Just locking the specific person will prevent other sessions from inserting items referencing that person.

select * from person where id=? for update

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.