Lock在Postgres/SQLAlchemy上添加具有特定外键ID的行



假设我有一个类似的标签:

PERSON:
id | person_name 
ITEM:
id | name | person_id

Items person_id是一个FK到person。

我有一个将item批量添加给person的操作。但是我想确保没有其他进程并发地向这个person添加项目而不阻塞整个person表。

是否有办法在Postgres中实现这一点?使用Python SQLalchemy完成此操作的代码更好吗?

我认为您想通过Query.with_for_update使用SELECT FOR UPDATE。只是一个警告,你必须小心地以相同的顺序和方式锁定,否则你很容易锁定你的线程。Ie。不要先锁定表A,然后在一个代码区域锁定表B,再锁定表B,然后在另一个代码区域锁定表A,因为这会导致死锁。

# 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

锁定特定的人将阻止其他会话插入引用该人的项。

select * from person where id=? for update

最新更新